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...

All help is welcome!

Thanks

C

underdark
  • 84,148
  • 21
  • 231
  • 413
CatchingMonkey
  • 1,142
  • 2
  • 9
  • 24

3 Answers3

25

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

leonardofmed
  • 296
  • 2
  • 16
Chau
  • 4,480
  • 4
  • 39
  • 57
  • 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? – CatchingMonkey Sep 13 '11 at 14:23
  • 1
    Scratch that. I was using the wrong featureID. Im using your second example and it works perfectly. Nice one! – CatchingMonkey Sep 13 '11 at 14:43
  • 1
    I'm getting layer.removeFeatures is not a function – Luis A. Florit Aug 11 '22 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.

Gorloki
  • 51
  • 1
  • 1
1

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

layer.getSource().removeFeature(feature);
nerdess
  • 111
  • 3