如何从地图中删除所有图层和要素? [英] How to remove all layers and features from map?
问题描述
我正在制作地图,我想在某个事件中移除地图中的所有要素.这些特征位于动态绘制的多个图层中.
I am working on a map and I would like to remove all features from the map on a certain event. The features are in multiple layers which are plotted dynamically.
部分代码为:
$.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());
});
});
});
}
});
});
有没有办法在某个时间点获取地图上的所有图层并删除它们.
Is there a way to fetch all layers on the map at a certain point in time and remove them.
推荐答案
使用 L.Map
的 eachLayer
方法遍历所有添加到地图的图层,然后分别调用 L.Map
的 removeLayer
方法:
Loop over all the layers added to the map using the eachLayer
method of L.Map
, then call the removeLayer
method of L.Map
on each of them:
map.eachLayer(function (layer) {
map.removeLayer(layer);
});
参考文献:
eachLayer
:http://leafletjs.com/reference.html#map-eachlayer
removeLayer
:http://leafletjs.com/reference.html#map-removelayer
请注意,这会从您的地图中删除所有图层.这也意味着任何 tilelayers 等.我认为在您的情况下,最好不要将所有 featureLayers 添加到地图实例中,而是为它们创建一个组:
Please note that this wil remove ALL the layers from your map. That means also any tilelayers etc. I think in your case it would be best if you do not add all your featureLayers to the map instance, but create a group for them:
// 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());
});
});
});
}
});
});
现在您可以调用 L.LayerGroup
的 clearLayers
方法来清除组中的当前图层:
Now you can call the clearLayers
method of L.LayerGroup
which will clear of the current layers in the group:
layerGroup.clearLayers();
参考:
L.LayerGroup
:http://leafletjs.com/reference.html#layergroup
clearLayers
:http://leafletjs.com/reference.html#layergroup-clearlayers
这篇关于如何从地图中删除所有图层和要素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!