[GIS] Change style of existing feature in OpenLayers2

openlayers-2

I'm using OpenLayers 2 and have a number of LineStrings with custom attributes's drawn. I need to change the strokeColor on some of the lines styles programatically and have it stay this color even if the user change zoom level or toggles layer visibility.

Currently I'm filtering/selecting features with vectorLayer.getFeaturesByAttribute() and then I'm using vectorLayer.drawFeature(feature, { strokeColor: "red }) to change the line colors. This work well until the user change the zoom level or if I toggle layer visibility back and forth with vectorLayer.setVisibility(), which for some reason changes the strokeColor back to the defalt style.

What is the correct way of changing the feature style and make it "stick"?

Best Answer

Your changes are disappearing because the map is being redrawn when you toggle the visibility or change zoom level. You need to alter the style attribute of the feature itself so that when the redraw happens, it uses the updated style values.

Try this approach:

var feature = vectorLayer.getFeaturesByAttribute(...);
feature.style = { strokeColor: "red" };
vectorLayer.redraw();