2nd leaflet map not rendering correctly

2020-04-30 16:05发布

问题:

I have 2 tabs, each has a leaflet map. The first map is rendering correctly, but the second map is only displaying 1 tile (the rest grey) and the map is not centered on the correct area. What am I doing wrong? Thanks.

  var map = L.map('tab-1').setView([latitude, longitude], 5);

  L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
    maxZoom: 18,
    id: '',
    accessToken: ''
  }).addTo(map);

  var map2 = L.map('tab-2').setView([latitude, longitude], 5);

  L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
    maxZoom: 18,
    id: '',
    accessToken: ''
  }).addTo(map2);

回答1:

EDIT:

If the div that contains your 2nd map is not displayed (I guess it is within a "tab" with displayed: none; CSS / style), Leaflet will not be able to determine properly the map container size.

Then once your 2nd map is revealed, its container size changes, but Leaflet does not realize and still uses the previous size.

You can simply call map2.invalidateSize() once that map is revealed so that Leaflet now covers the new area with tiles.

You will also need to re-set the view (using setView or fitBounds or whatever method you prefer) as it was done previously using incorrect container bounds.

Demo: http://jsfiddle.net/ve2huzxw/52/

(uncomment line 21 and re-run to get the correct behaviour)


Original answer:

Welcome to SO!

Are you really using twice L.map(location), with the same location?

It seems to me that Leaflet would try to create 2 maps in the same container. I guess it would produce unexpected result…

This is probably a typo, is not it?



标签: leaflet