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?

7

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
  • ...
| improve this answer | |
  • 9
    But what if it's already on the layer? I found this solution : mylayer.drawFeature(mylayer.getFeatureById(id), {fillColor: "#00ffff", strokeColor: "#00ffff"}); – jlai79 Jan 28 '13 at 19:58
  • yes, you are right, you just redraw it with new style. – mfdev Jan 29 '13 at 7: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]);
| improve this answer | |
  • This didn't work for me, I got "Uncaught TypeError: feature.setStyle is not a function" – Matthew Lock Feb 12 '19 at 11:01
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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.