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

时间:2015-02-21 13:27:02

标签: jquery leaflet mapbox

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

部分代码是:

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

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

4 个答案:

答案 0 :(得分:19)

使用eachLayer的{​​{1}}方法遍历添加到地图的所有图层,然后在每个图层上调用L.Map removeLayer方法:

L.Map

参考文献:

map.eachLayer(function (layer) { map.removeLayer(layer); }); http://leafletjs.com/reference.html#map-eachlayer

eachLayerhttp://leafletjs.com/reference.html#map-removelayer

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

removeLayer

现在,您可以调用// 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()); }); }); }); } }); }); 的{​​{1}}方法,该方法将清除该组中的当前图层:

clearLayers

参考:

L.LayerGrouphttp://leafletjs.com/reference.html#layergroup

layerGroup.clearLayers(); http://leafletjs.com/reference.html#layergroup-clearlayers

答案 1 :(得分:2)

您可以使用以下真实检查来查看它是否是有效的geoJSON对象:

map.eachLayer(function(layer) {
  if (!!layer.toGeoJSON) {
    map.removeLayer(layer);
  }
});

答案 2 :(得分:0)

在mabox-gl绘图库中,有一个函数可以执行此操作。

draw.deleteAll().getAll();

这将删除地图上的所有要素和图层。

答案 3 :(得分:0)

基于 iH8 的回答,但如果您想移除平铺层之外的所有层,则更简洁。只需通过检查 _url:

var osmUrl = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png'

map.eachLayer(function (layer) {
    if (osmUrl != layer._url){map.removeLayer(layer)};
});
相关问题