I have a leafletmap that only renders into one corner. When I resize the browser window, the whole map renders.
That is how I invoce the map
var map = L.map('map',
{ crs: L.CRS.EPSG3857 }
).setView([105.2, 100], 6);
var tiles = L.tileLayer('http://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}.{ext}', {
attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> — Map data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
subdomains: 'abcd',
ext: 'png'
}).addTo(map);
And this is my css
.myContainer {
width: 1024px;
height: 800px;
position: relative;
}
.map {
width: 1024px;
height: 800px;
z-index: 0;
}
The map
is wrapped in a container
. Everything I found online regarding this problem points to relative sizes in the map- or its parent container. However, I have absolute sizes. I load the .css
before the .js
(where I initialize the map). The map will be displayed not on the startpage, but when you click on a submenue point.
Why is the map not rendered properly?
The map will be displayed not on the startpage, but when you click on a submenue point.
You're initializing the map on a hidden or zero-size container, which makes this question a duplicate of 2nd leaflet map not rendering correctly
The answer is the same: run map.invalidateSize()
whenever the map should become visible, or when you change its dimensions or visibility.
As IvanSanchez stated, map.invalidateSize() is indeed the way to go.
A useful code example for map refresh every 2 seconds in Javascript would be:
//Using setInterval can help the reloading or refreshing of the map itself.
setInterval(function() {
map.invalidateSize();
}, 2000);
...Note that setInterval() counts time in milliseconds so for example , 2000
are 2 seconds.
map
in map.invalidateSize()
is the name of the variable you set your map to when you initialized it:
Map initialization example:
var map = L.map(...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With