Leaflet.js:如何从地图中删除多个图层
我使用Leaflet.js作为地图。现在,我想从地图中删除添加的图层。通过点击输入#button,所有选中的复选框应改为未选中,所有相应的图层都应从地图中删除。
I am using Leaflet.js for a map. Now I want to remove added layers from the map. By clicking the input #button all checked checkboxes shall be changed to unchecked and all corresponding layers shall be removed from the map.
要从地图中删除图层,需要该层。此ID等于相应复选框的ID。这就是为什么我使用jQuery获取所有选中的复选框的ID,并将它们的值存储在对象中,这里称为 someObj.idsChecked 。
To remove a layer from the map the id of the layer is needed. This id equals the id of the corresponding checkbox. That's why I use jQuery to get the ids of all checked checkboxes and store their value in an object, here called someObj.idsChecked.
当我尝试使用存储的值 val 删除一个图层时,它在控制台中不起作用。 log 显示所需的值。这里例如:mapcat52。
When I try to use the stored value val to remove one layer it doesn't work while the console.log displays the wanted value. Here for example: mapcat52.
将上面的id硬编码到 map.removeLayer(mapcat52)
While inserting the previous id hard coded into the function like map.removeLayer(mapcat52) it works as expected.
我的代码或我的想法中的错误在哪里?
任何帮助都非常感谢。
Where is the error in my code or my thoughts?
Any help is much appreciated.
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);
});
});
根据Leaflet API doc http://leafletjs.com/reference.html#map-removelayer ,removeLayer使用iLayer参数: removeLayer (< ILayer> layer)
但你传递的是一个String: $(this).attr(id)
According to the Leaflet API doc http://leafletjs.com/reference.html#map-removelayer, removeLayer takes an iLayer parameter: removeLayer( <ILayer> layer )
but you're passing it a String: $(this).attr("id")
看起来你已经有一个变量中的图层对象:mapcat52。您可以在创建图层对象时保存图层对象,然后按id查看以传递给removeLayer:
It looks like you do have the layer object in a variable already: mapcat52. You could save the layer objects when you create them, then look them up by id to pass to removeLayer:
var layers = new Array();
// create layer mapcat52
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);
});