作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在制作 map ,我想从 map 上删除特定事件的所有要素。这些特征位于动态绘制的多个图层中。
部分代码是:
$.getJSON('distributor-companies', function (data) {
var layers = [];
$.each(data, function (i, item) {
if (item.geojson != '') {
layers[i] = L.mapbox.featureLayer().addTo(map);
$.getJSON('/geojson/' + item.geojson, function (data) {
layers[i].setGeoJSON(data);
// Loop over the added layer
layers[i].eachLayer(function (layer) {
// Add click event
layer.on('click', function (e) {
// Do stuff
map.fitBounds(layers[i].getBounds());
});
});
});
}
});
});
有没有办法在某个时间点获取 map 上的所有图层并将其删除。
最佳答案
使用 eachLayer
循环添加到 map 中的所有图层方法L.Map
,然后调用removeLayer
方法L.Map
在他们每个人身上:
map.eachLayer(function (layer) {
map.removeLayer(layer);
});
引用文献:
eachLayer
: http://leafletjs.com/reference.html#map-eachlayer
removeLayer
: http://leafletjs.com/reference.html#map-removelayer
请注意,这将从 map 中删除所有图层。这也意味着任何tilelayers等。我认为在你的情况下,最好不要将所有featureLayers添加到 map 实例中,而是为它们创建一个组:
// Create group for your layers and add it to the map
var layerGroup = L.layerGroup().addTo(map);
$.getJSON('distributor-companies', function (data) {
$.each(data, function (i, item) {
if (item.geojson != '') {
// Add the new featureLayer to the layerGroup
var featureLayer = L.mapbox.featureLayer().addTo(layerGroup);
$.getJSON('/geojson/' + item.geojson, function (data) {
featureLayer.setGeoJSON(data);
featureLayer.eachLayer(function (layer) {
layer.on('click', function (e) {
map.fitBounds(featureLayer.getBounds());
});
});
});
}
});
});
现在您可以调用clearLayers
方法L.LayerGroup
这将清除组中的当前图层:
layerGroup.clearLayers();
引用:
L.LayerGroup
: http://leafletjs.com/reference.html#layergroup
clearLayers
: http://leafletjs.com/reference.html#layergroup-clearlayers
关于jquery - 如何从 map 中删除所有图层和要素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28646317/
我是一名优秀的程序员,十分优秀!