16

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.

3 Answers 3

26

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()

3
  • I like the thinking! The problems is though that the "layer.getFeatureById(featureID))" statement returns null, and so the removeFeature() doesnt work. Im 100% that i have the right FeatureIDs though.... any more thoughts? Commented Sep 13, 2011 at 14:23
  • 1
    Scratch that. I was using the wrong featureID. Im using your second example and it works perfectly. Nice one! Commented Sep 13, 2011 at 14:43
  • 1
    I'm getting layer.removeFeatures is not a function Commented Aug 11, 2022 at 23:31
5

This worked for me:

*layer.removeFeatures(featureObject);*

But i've got the feature as a global variable, maybe in other cases you should try to keep the feature ID in order to search to remove it.

2

This worked for me to remove a single feature in OpenLayers 6:

layer.getSource().removeFeature(feature);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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