javascript 刷新传单地图:地图容器已经初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19186428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:42:10  来源:igfitidea点击:

refresh leaflet map: map container is already initialized

javascriptleaflet

提问by leandro713

I have a page where given a select to the user he can switch the leaflet map I show.

我有一个页面,其中给了用户一个选择,他可以切换我显示的传单地图。

After a initial leaflet map load, my problem is when i want to refresh the map.

在初始传单地图加载后,我的问题是我想刷新地图。

I always get "Map container is already initialized":

我总是得到“地图容器已经初始化”:

The problem line is:

问题线是:

var map = L.map('mapa').setView([lat, lon], 15);

Initially it loads well, but when I select another parameter in the form and want to display the map another time it crashes.

最初它加载得很好,但是当我在表单中选择另一个参数并希望再次显示地图时它崩溃了。

btw, I've tried to destroy and recreate $('#mapa')with jQuery before the second setView()but it shows the same error.

顺便说一句,我试图$('#mapa')在第二次之前用 jQuery销毁和重新创建,setView()但它显示了相同的错误。

采纳答案by Artem Kovalov

Html:

网址:

<div id="weathermap"></div>

JavaScript:

JavaScript:

function buildMap(lat,lon)  {
    document.getElementById('weathermap').innerHTML = "<div id='map' style='width: 100%; height: 100%;'></div>";
    var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
                    osmAttribution = 'Map data ? <a href="http://openstreetmap.org">OpenStreetMap</a> contributors,' +
                        ' <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
    osmLayer = new L.TileLayer(osmUrl, {maxZoom: 18, attribution: osmAttribution});
    var map = new L.Map('map');
    map.setView(new L.LatLng(lat,lon), 9 );
    map.addLayer(osmLayer);
    var validatorsLayer = new OsmJs.Weather.LeafletLayer({lang: 'en'});
    map.addLayer(validatorsLayer);
}

I use this:

我用这个:

document.getElementById('weathermap').innerHTML = "<div id='map' style='width: 100%; height: 100%;'></div>";

to reload content of div where render map.

重新加载渲染地图的 div 内容。

回答by Josh

Try map.remove();before you try to reload the map. This removes the previous map element using Leaflet's library (instead of jquery's).

试着map.remove();尝试重新加载地图前。这将使用 Leaflet 的库(而不是 jquery 的)删除先前的地图元素。

回答by yit770

the best way

最好的方法

map.off();
map.remove();

You should add map.off(), it also works faster, and does not cause problems with the events

您应该添加 map.off(),它的运行速度也更快,并且不会导致事件出现问题

回答by Dipin Raj C

Before initializing map check for is the map is already initiated or not

在初始化地图之前检查地图是否已经启动

var container = L.DomUtil.get('map');
      if(container != null){
        container._leaflet_id = null;
      }

回答by Damico

When you just remove a map, it destroys the div id reference, so, after remove() you need to build again the div where the map will be displayed, in order to avoid the "Uncaught Error: Map container not found".

刚删除地图时,它会破坏 div id 引用,因此,在 remove() 之后,您需要重新构建将显示地图的 div,以避免出现“未捕获的错误:未找到地图容器”。

if(map != undefined || map != null){
    map.remove();
   $("#map").html("");
   $("#preMap").empty();
   $( "<div id=\"map\" style=\"height: 500px;\"></div>" ).appendTo("#preMap");
}

回答by leandro713

well, after much seeking i realized it's well documented at http://leafletjs.com/examples/layers-control.html

好吧,经过多次寻找,我意识到它在http://leafletjs.com/examples/layers-control.html上有详细记录

i've ended not repainting the map, but print it once and repaint the points on each new ajax call, so the problem was how to clean up the old points and print only the new ones. i've ended doing this:

我结束了没有重新绘制地图,而是打印一次并在每个新的 ajax 调用中重新绘制点,所以问题是如何清理旧点并仅打印新点。我已经结束了这样做:

var point = L.marker([new_marker[0], new_marker[1]]).addTo(map).bindPopup('blah blah');
points.push(point); 
//points is a temporary array where i store the points for removing them afterwards

so, at each new ajax call, beforepainting the new points, i do the following:

因此,在每次新的 ajax 调用中,绘制新点之前,我会执行以下操作:

for (i=0;i<points.length;i++) {
  map.removeLayer(points[i]);
}
points=[];

so far, so good :-)

到目前为止,一切都很好 :-)

回答by Bashirpour

回答by saeed karimi

What you can try is to remove the map before initialising it or when you leave the page:

您可以尝试在初始化之前或离开页面时删除地图:

if(this.map) {
  this.map.remove();
}

回答by LeNantais

Before initializing map check for is the map is already initiated or not

在初始化地图之前检查地图是否已经启动

var container = L.DomUtil.get('map');

if(container != null){

container._leaflet_id = null;

}

It works for me

这个对我有用

回答by Роман

if you want update map view, for example change map center, you don't have to delete and then recreate the map, you can just update coordinate

如果要更新地图视图,例如更改地图中心,则不必删除然后重新创建地图,只需更新坐标即可

const mapInit = () => {
 let map.current = w.L.map('map');

 L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright" target="_blank">OpenStreetMap</a> contributors'
 }).addTo(map.current);
}

const setCoordinate = (gps_lat, gps_long) => {
  map.setView([gps_lat, gps_long], 13);
}

initMap();

setCoordinate(50.403723 30.623538);

setTimeout(() => {
  setCoordinate(51.505, -0.09);
}, 3000);