如何从地图中删除所有图层和要素?

我正在制作地图,我想在某个事件中删除地图上的所有function。 这些要素采用多层动态绘制。

一些代码是:

$.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()); }); }); }); } }); }); 

有没有办法在某个时间点获取地图上的所有图层并将其删除。

使用eachLayer方法L.Map添加到地图的所有图层,然后在每个L.Map上调用L.MapremoveLayer方法:

 map.eachLayer(function (layer) { map.removeLayer(layer); }); 

参考文献:

eachLayer : http : eachLayer

removeLayer : http : //leafletjs.com/reference.html#map-removelayer

请注意,这将删除地图中的所有图层。 这也意味着任何tilelayers等。我认为在你的情况下,最好不要将所有featureLayers添加到地图实例,而是为它们创建一个组:

 // 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方法,它将清除组中的当前层:

 layerGroup.clearLayers(); 

参考:

L.LayerGroup : http : L.LayerGroup

clearLayers : http : clearLayers