11

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?

jlai
  • 211
  • 1
  • 2
  • 4
  • Can someone pass the link for a working code link for reference, I've got the same requirement now but the links are not working – Manjunath D Dec 25 '22 at 06:07

3 Answers3

9

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
  • ...
tremendows
  • 103
  • 4
mfdev
  • 1,948
  • 1
  • 12
  • 19
  • 9
    But what if it's already on the layer? I found this solution : mylayer.drawFeature(mylayer.getFeatureById(id), {fillColor: "#00ffff", strokeColor: "#00ffff"}); – jlai Jan 28 '13 at 19:58
  • yes, you are right, you just redraw it with new style. – mfdev Jan 29 '13 at 07:13
2

Using the case in the other answer.

Just changing the using of the "setStyle()"

This case worked for me.

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

selectedFeature.setStyle(selected_polygon_style);
layer.addFeatures([selectedFeature]);
Jorge Rocha
  • 131
  • 1
  • 7
1

Whit OpenLayers 4.6.5 for change color i'm using this:

myLayer.getSource().getFeatures()[1].setStyle(new ol.style.Style({
      image: new ol.style.Icon(/** @type {module:ol/style/Icon~Options} */({ // /** @type {olx.style.IconOptions} */
        color: '#00ffff', //  #FF0000
        crossOrigin: 'anonymous',
        src: '/img/dot.png'
      }))
    }));

getFeatures()[1] is one of element of my Feature. If I would change ALL features then i would use a Loop.

tinlyx
  • 11,057
  • 18
  • 71
  • 119
faienz93
  • 11
  • 1