Leaflet.js: How to remove multiple layers from map

可紊 提交于 2019-12-03 06:51:38
kielni

According to the Leaflet API doc http://leafletjs.com/reference.html#map-removelayer, removeLayer takes an ILayer parameter: removeLayer( <ILayer> layer ) but you're passing it a String: $(this).attr("id")

It looks like you do have the layer object in a variable already: mapcat52. You could save the layer objects when you create them, then look them up by id to pass to removeLayer:

var layers = new Array();

// create layer
var mapcat52 = new MyCustomLayer(latlng);

// save to layers list
layers["mapcat52"] = mapcat52;
...

// remove layers
$.each(someObj.idsChecked, function(id, val) {
    // look up layer object by id
    var layerObj = layers[val];
    // remove layer
    map.removeLayer(layerObj); 
});
Shriram Sharma

I would say the easiest way to remove/add (toggle) layers from the map would be to use a LayerGroup.

Before adding individual layers to the map, add them to a LayerGroup instead and then add that LayerGroup to your map.

Then when you have to remove the layers, just call the clearLayers() function.

Check out the API for LayerGroup http://leafletjs.com/reference.html#layergroup

Example

var map = L.map('leafletMap', {minZoom:11}).setView([37.8, -96], 11);
var assetLayerGroup = new L.LayerGroup();
var marker1 = L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.');
var marker2 = L.marker([39.74, -104.99]).bindPopup('This is Denver, CO.'),
assetLayerGroup.addLayer(marker1);
assetLayerGroup.addLayer(marker2);

When remove checkbox is checked

assetLayerGroup.clearLayers();

I wrote the below example to show how to remove multiples geoJSON layer.

///adding geoJSON data

      var myGeoJSON = L.geoJSON(myData, {

        onEachFeature: function (feature, layer) {
            layer.myTag = "myGeoJSON"
        }

    });

////// function to remove geoJSON layers

var removeMarkers = function() {
    map.eachLayer( function(layer) {

      if ( layer.myTag &&  layer.myTag === "myGeoJSON") {
        map.removeLayer(layer)
          }

        });

}

//// calling function

removeMarkers();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!