LuN*_*rez 8 javascript checkbox maps jquery leaflet
我正在使用Leaflet.js作为地图.现在我想从地图中删除添加的图层.通过单击输入#button,所有选中的复选框将更改为未选中,并且所有相应的图层将从地图中删除.
要从地图中删除图层,需要图层的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>
...
Run Code Online (Sandbox Code Playgroud)
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);
});
});
Run Code Online (Sandbox Code Playgroud)
Shr*_*rma 20
我想说从地图中删除/添加(切换)图层的最简单方法是使用LayerGroup.
在将单个图层添加到地图之前,请将它们添加到LayerGroup,然后将该LayerGroup添加到地图中.
然后,当您必须删除图层时,只需调用clearLayers()函数即可.
查看LayerGroup http://leafletjs.com/reference.html#layergroup的API
例
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);
Run Code Online (Sandbox Code Playgroud)
选中删除复选框时
assetLayerGroup.clearLayers();
Run Code Online (Sandbox Code Playgroud)
根据Leaflet API doc http://leafletjs.com/reference.html#map-removelayer,removeLayer接受一个ILayer参数:removeLayer( <ILayer> layer )
但是你传递了一个String:$(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);
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
34901 次 |
最近记录: |