0

htmlテーブル内のさまざまな場所の緯度と経度を持ち、その行をクリックすると関数が緯度と経度の値をjavascript関数に送信し、javascript関数がブートストラップモーダル。 これは、関数が呼び出されて初めてマーカが表示されますが、モーダルを閉じると再び呼び出されます。エラーが発生します。
キャッチされていないエラー:マップコンテナは既に初期化されています。リーフレット:地図コンテナを初期化する関数

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); 
関連する問題