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

2022-01-12 00:00:00 leaflet javascript

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

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":

问题行是:

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.

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

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

推荐答案

Html:

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

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);
}

我用这个:

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

在渲染地图的地方重新加载 div 的内容.

to reload content of div where render map.

相关文章