2013-08-29 192 views
8

我正在使用Leaflet.js作爲地圖。現在我想從地圖中刪除添加的圖層。通過點擊輸入#按鈕,所有選中的複選框將被更改爲未選中,並且所有相應的圖層將從地圖中移除。Leaflet.js:如何從地圖中刪除多個圖層

要從地圖中刪除圖層,需要圖層的ID。此ID等於相應複選框的ID。這就是爲什麼我使用jQuery獲取所有選中的複選框的ID並將其值存儲在一個對象中,這裏稱爲 someObj.idsChecked

當我嘗試使用儲值 VAL去除一層這是行不通的,而的console.log顯示想要的值。這裏例如:mapcat52。

雖然將以前的ID硬編碼插入到像 map.removeLayer(mapcat52)這樣的函數中,但它按預期工作。

我的代碼或我的想法中的錯誤在哪裏?
任何幫助非常感謝。

的HTML

<input type="button" id="selectnone" value="deselect all" /> 

<!-- checkboxes --> 
<input id="mapcat52" type="checkbox" name="maplayer" class="maplayer"> 
<label for="mapcat52">Map Layer One</label> 

<input id="mapcat53" type="checkbox" name="maplayer" class="maplayer"> 
<label for="mapcat53">Map Layer Two</label> 

... 

的JS:

$('#selectnone').click(function() { 
    var someObj = {}; 
    someObj.idsChecked = []; 

    $("input:checkbox").each(function() { 
     if ($(this).is(":checked")) { 

      someObj.idsChecked.push($(this).attr("id")); 
     } 
    }).attr('checked', false); 

    $.each(someObj.idsChecked,function(id, val) { 

      // displays the wanted value, e.g. "mapcat52" if checkbox with this id is checked 
      console.log(val); 

      // does not work: inserted value 
      map.removeLayer(val); 

      // works: hard coded value of the leaflet.js/input id 
      map.removeLayer(mapcat52); 
     }); 

}); 
+0

這可能幫助:https://stackoverflow.com/questions/39186001/ how-to-close-all-popups –

回答

6

根據廣告傳單API文檔http://leafletjs.com/reference.html#map-removelayer,removeLayer需要一個ILAYER參數:removeLayer(<ILayer> layer)但你傳遞一個字符串:$(this).attr("id")

看起來你已經有了一個變量中的圖層對象:mapcat52。當你創建它們,你可以保存層的物體,然後通過ID查找它們傳遞給removeLayer:

var layers = new Array(); 

// create layer 
var mapcat52 = new MyCustomLayer(latlng); 

// save to layers list 
layers["mapcat52"] = mapcat52; 
... 

// remove layers 
$.each(someObj.idsChecked, function(id, val) { 
    // look up layer object by id 
    var layerObj = layers[val]; 
    // remove layer 
    map.removeLayer(layerObj); 
}); 
+0

非常感謝您的建議。這似乎符合我的情況。我會很快嘗試。 – LuNarez

16

我想說的最簡單的方法刪除/添加(切換)層從地圖是使用a LayerGroup

在將單個圖層添加到地圖之前,將它們添加到LayerGroup中,然後將該LayerGroup添加到地圖中。

然後當你不得不刪除圖層時,只需調用clearLayers()函數。

退房的API爲圖層組http://leafletjs.com/reference.html#layergroup

var map = L.map('leafletMap', {minZoom:11}).setView([37.8, -96], 11); 
var assetLayerGroup = new L.LayerGroup(); 
var marker1 = L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.'); 
var marker2 = L.marker([39.74, -104.99]).bindPopup('This is Denver, CO.'), 
assetLayerGroup.addLayer(marker1); 
assetLayerGroup.addLayer(marker2); 

當刪除複選框被選中

assetLayerGroup.clearLayers(); 
+0

感謝您提供乾淨,清晰的示例。很難找到其中的一個! – jmadsen