[GIS] leaflet remove a specific type of features from featuregroup

leaflet

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.

Best Answer

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.