Astrogat
Astrogat

Reputation: 1625

How to remove a feature in openlayers with multiple possible sources

I have a map with multiple layers, all connected to different vector sources.

When a user selects a feature I want him to be able to delete the feature. However, I can't seem to find a way to locate the source layer the feature is from.

If I try to just remove the feature from all layers I get an error:

Vector.js:946 Uncaught TypeError: Cannot read property 'forEach' of undefined
at Vector.removeFeatureInternal (Vector.js:946)

Is there a good way of doing finding the source layer or removing features without specifying from where?

At the moment I'm catching the exceptions, but this turns unwieldy with a lot of layers and sources.

Upvotes: 0

Views: 2564

Answers (1)

Rob
Rob

Reputation: 659

For each source, you could try to get the selected Feature. If the response is not null, the feature exists on that source. Something along this way inside your select:

const featureId = selectedFeature.getId()
map.getLayers().getArray().forEach(layer => {
  const source = layer.getSource();
  if (source instanceof VectorLayer) {
    const featureExists = source.getFeatureById(featureId);
    if (featureExists) {
      source.removeFeature(selectedFeature);
      return;
    }
  }
})

Upvotes: 2

Related Questions