gpt4 book ai didi

jquery - 如何从 map 中删除所有图层和要素?

转载 作者:行者123 更新时间:2023-12-03 22:23:32 24 4
gpt4 key购买 nike

我正在制作 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com