3

I'm trying to add a select interaction on a vector layer and get the stroke color of the selected feature returned. I am able to set the style for the selected feature, but getStyle does not return the style of the selected feature. Can anyone help, please?

 if(this._map){
    const selectClick = new Select({
      condition: doubleClick,
       layers: [this._vectorLayer]
    });
  
  this._selectInteraction = selectClick;
  this._map.addInteraction(selectClick);
  
  selectClick.on('select', function (e) {
       console.log(e.selected[0].getStyle());
   });
  }

returns

ƒ (feature) {
        if (!feature.getGeometry()) {
            return null;
        }
        return styles[feature.getGeometry().getType()];
    }
1
  • I guess the style you get from the selected feature is the default select style. To get the style of the actual feature, you could remember the id of the selected feature and search for it in your vector layer source. When you have found it, you can query the style which should be different to the select style. Commented Apr 4, 2023 at 21:02

1 Answer 1

5

If you want to get style of selected feature, there are two things you gave to take into consideration.

First thing. If you look at the description of interaction style option (see https://openlayers.org/en/latest/apidoc/module-ol_interaction_Select-Select.html), you can read:

Style for the selected features. By default the default edit style is used (see Style). Set to null if this interaction should not apply any style changes for selected features. If set to a falsey value, the selected feature's style will not change.

This means that at the moment you are getting default edit style of the selected feature. If you want to get original feature style, you have to set style: null when defining interaction.

Second thing. If you look at the description of feature .getStyle() method (see https://openlayers.org/en/latest/apidoc/module-ol_Feature-Feature.html#getStyle), you can read:

Get the feature's style. Will return what was provided to the setStyle method.

This means you'll get feature style with the .getStyle() method only if it was previously set with the .setStyle() method.

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.