OpenLayers 2 – How to Draw Feature with Style and Preserve After Map Redraw

openlayers-2style

The function that I am trying to work on is: click on a feature and change its color. I tried to approach this by first recreating the feature with custom style:

layer.drawFeature(feature, myStyle);

this gave me the desired shape but it was lost after layer redraw.

Then I tried to use a clone of the feature:

layer.drawFeature(feature.clone(), myStyle);

this time the new shape would not disappear but it's not sync with the map, i.e. it does not resize/ move with the map.

I do notice that the following post was about a similar issue. I wonder if there's a way without creating an extra overlay? I could live with the cloned feature thing if that can be put to work.

Openlayers – Losing selection or style on layer redraw

Any suggestions will be greatly appreciated!

Best Answer

The drawFeature function does not save the style. The feature is redrawn with the layer style again when the layer is redrawn. You may assign the style to the feature, and drawFeature again. Now when redrawing the feature, the assigned style will be used.

feature.style = myStyle;
layer.drawFeature(feature);

Have a look at the drawFeature documentation. It gives more detailed information.