3

Is there any way in leaflet to delete a specific type of features from a feature group (mixed content: markers, polygons, polylines)? I know this code that work: map.removeLayer(drawnItems); but it delete all the objects within the drawnItems featuregroup. I only need a specific type of features, for example all the markers to be deleted.

7

In a similar way to my answer to leaflet count by featuretypes in featuregroup :

drawnItems
  .filter(function(layer) {
    return layer instanceof L.Marker;
  })
  .forEach(function(layer) {
    map.removeLayer(layer);
  });

Or in a shorter one-liner using arrow functions:

drawnItems.getLayers().filter(l=>l instanceof L.Marker).forEach(l=>map.remove(l));

Remember to check the documentation for Array.prototype.filter and Array.prototype.forEach.

On the other hand, you should consider creating several L.FeatureGroups, one for each kind of layer you want to add/remove from/to the map.

| improve this answer | |
  • thank for your help and for the useful tips. I tested the code and it generates -drawnItems.filter is not a function- error for some reason. I tried to modify but no succes.. – Tamas Kosa Jun 21 '17 at 12:17
  • Not "some reason". If drawnItems is an instance of L.LayerGroup, then it's not an array. OTOH, drawnItems.getLayers() returns an instance of Array, which has a filter method. – IvanSanchez Jun 22 '17 at 10:16
2
if(map.hasLayer(drawnFeatures)){
    // map.removeLayer(drawnFeatures); <-- this the wrong way
    drawnFeatures.eachLayer(
        function(l){
            drawnFeatures.removeLayer(l);
    });
}   

that can delete each layer without delete Features group. can be used again for new drawn items.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.