Back

Technologies:

javascriptjavascript
avatar
Tolerim
a month ago

How can the feature style be updated outside of a mapInteraction function?

I'm currently working on making an Openlayers map more accessible by designing a list of buttons. Each button corresponds to a feature on the map and has that feature's ID as its value. When a button is focused, I can display the feature's title with an "Overlay" and open its "Popup" using "Overlay" on keyDown. However, I'm having trouble changing the style of the feature in question, as using the code:
 feature.setStyle(new Style({...style...}) 
doesn't update the feature on the map. I suspect this is because it's not within an Openlayers mapInteraction (Select condition) function. Is there another way I can change the feature's style outside of Openlayers conditions?
Answers(2)
avatar
Vogi
a month ago
Verified Answer
You can change the style of an OpenLayers feature outside of OpenLayers conditions by altering the style attribute of the feature itself so that when the redraw happens, it uses the updated style values. Here is an example approach:
var feature = vectorLayer.getFeaturesByAttribute (...);
feature.style = { strokeColor: "red" };
vectorLayer.redraw ();
You can also give a feature a customStyle property and use that only in a layer style function instead of a default style, while interactions would continue to use the defaults for interactions. I hope this helps! Let me know if you have any other questions.

Sources

javascript - OpenLayers modify feature style without overwritting ...Updating feature styles in OpenLayers 3 - Stack Overflowopenlayers 2 - Change style of existing feature in OpenLayers2 ...Update feature style outside a mapInteraction function
avatar
Tolerim
a month ago
Yes, you can trigger a style change outside of the Openlayers Select interaction function by directly accessing the feature you want to change and calling the setStyle function. Here's an example:
const feature = myVectorLayer.getSource().getFeatureById(featureId);
if (feature) {
  feature.setStyle(new ol.style.Style({...style...}));
  myVectorLayer.changed();
}
In this example, myVectorLayer is the layer that contains the feature you want to style, featureId is the ID of the feature you want to style, and style is the new style you want to apply. The getSource function is used to get the source of the layer, the getFeatureById function is used to get the feature you want to style, and the setStyle function is used to set the new style. Finally, the changed function is called on the layer to trigger a redraw of the feature on the map.
;