[GIS] Remove/Delete a feature from OpenLayers vector layer

openlayers-2

I have an OpenLayers layer with several vectors on it. I know the OpenLayers Feature ID (e.g. OpenLayers.Feature.Vector_241) and I would like to know how to remove this feature and only this feature?

I have considered deleting them all and then looping through an array to redraw them, but this seems a little inelegant, and long winded.

I have tried a variety of versions of the folllowing code:

layer.removeFeatures( featureID );

And

layer.removeFeatures( [featureID] );

And

layer.removeFeatures( {feature : featureID });

Etc…

All help is welcome!

Thanks

C

Best Answer

I don't think that OpenLayers is capable of removing a feature by providing the featureID. It seems like it can only remove a features by providing a feature or an array of features:

layer.removeFeatures(featureObject);

But you could instead locate the feature first and then remove the found feature:

layer.removeFeatures(layer.getFeatureById(featureID));

Or similar if its not the OpenLayers FeatureID you have, then

layer.removeFeatures(layer.getFeatureBy('myId', myID));

For OpenLayers v6+ it's done in another way, considering that layer is a VectorLayer:

let feature = layer.getSource().getFeatureById('featureID');

getFeatureById()