[GIS] How to change color of a feature in openlayers

openlayers-2

I'm loading a geojson file into openlayers to show some polygons. From this file I also create a list of all names of these polygons.

Now I want to change the color of a polygon when selected from the list (clicked on the name).

What I've tried is to create a style (http://docs.openlayers.org/library/feature_styling.html) but I couldn't find out how to add this style to the polygon. How can I do that?

Best Answer

You may just to create a style symbolizer hash set and assign it to your selected polygon before adding it to the layer:

var selected_polygon_style = {
    strokeWidth: 5,
    strokeColor: '#ff0000'
    // add more styling key/value pairs as your need
};

selectedFeature.style = selected_polygon_style;
layer.addFeatures([selectedFeature]);

At this page (http://docs.openlayers.org/library/feature_styling.html) you can find much information about the style properties you can modify:

  • fillColor
  • fillOpacity
  • strokeColor
  • strokeOpacity
  • strokeWidth
  • strokeLinecap
  • strokeDashstyle
  • ...