2017-06-01 54 views
0

有一个html表格中各个地方的经纬度,点击该行时,函数将纬度和经度值发送到一个javascript函数,该函数将openstreetmap地图和标记加载到bootstrap模态。 第一次调用此功能时,显示标记,但是关闭模式并重新调用函数我得到错误
未捕获错误:地图容器已经初始化。Leaflet:初始化地图容器的函数

function sendlatlng(id) { 
     var geom=document.getElementById('cor'+id).value; 
     var geom1=document.getElementById('cod'+id).value; 
     var map = L.map(('map'),{scrollWheelZoom:true}).setView([geom,geom1], 12); 
     L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 
     { 
      maxZoom: 18 
     }).addTo(map); 
     L.marker([geom,geom1]).addTo(map); 

      } 

有没有一种方式,地图div

<div id="map" class="map" style="height: 300px;"></div> 

重新初始化每一个模态被打开或函数被调用时。

回答

1

错误来自传单,因为我们试图每次创建地图容器sendlatlng被执行。没关系,因为不是试图在sendlatlng函数中创建映射和标记,我们可以创建一次,然后使用该函数更新现有对象的坐标。这里有一个例子:

<html> 
 

 
<head> 
 
    <title>A Leaflet map!</title> 
 
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" /> 
 
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script> 
 
    <style> 
 
     #map { 
 
      width: 450px; 
 
      height: 250px 
 
     } 
 
    </style> 
 
</head> 
 

 
<body> 
 

 
    <div id="map"></div> 
 

 
    <script> 
 
     //just for the demo 
 
     var defaultCoords = [-41.291, -185.229]; 
 

 
     //set up our map 
 
     var map = L.map('map').setView(defaultCoords, 12); 
 
     L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 
 
      { 
 
       maxZoom: 18 
 
      }).addTo(map); 
 

 
     //this is how we are going to demo our sendlatlng function 
 
     map.on('click', onMapClick); 
 

 

 
     //use this variable to track our marker here outside of the sendlatlng function 
 
     var myMarker = L.marker(defaultCoords).addTo(map); 
 

 
     //in our example, we are going to listend for clicks on the map to trigger 
 
     //changes to the coords with our sendlatlng function 
 
     function onMapClick(e) { 
 
      sendlatlng(e.latlng) 
 
     } 
 

 

 
     //update the map and marker positions based on the coords passed to the function 
 
     //we will just update our existing map and myMarker variables instead of create new ones 
 
     function sendlatlng(coords) { 
 
      map.setView(coords, 12); 
 
      myMarker.setLatLng(coords); 
 

 
     } 
 
    </script> 
 
</body> 
 

 
</html>

在演示中,我们正在引发与地图上用鼠标点击sendlatlng功能。这将重新映射地图并将myMarker移动到新中心。

如果,例如,你想创建的点击位置的新标记,我们能做到这一点,你原本的功能,以同样的方式:通过增加新的标记:L.marker(coords).addTo(map);

0

如果你创建地图并尝试再次映射它,你会得到这个错误。试试以下示例代码

//Use this before creating the map 

if (map != undefined) { 
    map.remove(); 
} 

//Use this after adding tile layer 

setTimeout(function() { map.invalidateSize() }, 1200);