2nd leaflet map not rendering correctly

狂风中的少年 提交于 2020-01-11 12:59:13

问题


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?



来源:https://stackoverflow.com/questions/33740130/2nd-leaflet-map-not-rendering-correctly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!