5

I try to add Features with LineString geometries in different colors to a ol.source.Vector.

I tried to do this with the following code:

var myFeature = new ol.Feature({
   geometry : new ol.geom.LineString(coordinates),
   style : new ol.style.Style({
       stroke : new ol.style.Stroke({color : "red"})})
});
mySource.addFeature(myFeature);

The coordinates are correctly transformed. The resulting LineString Feature is displayed at the correct position in the map – but not in red.

What am I doing wrong?

  • For me it seems that this is not a matter of color but of ol.style.Style or ol.style.Stroke in conjunction with an ol.Feature or ol.geom.LineString. – burghard Dec 20 '16 at 6:37
  • Digging into the Feature object by debugging, I saw that the internal property of the feature style_: null after creation (new). – burghard Dec 20 '16 at 6:56
  • Does myFeature.setStyle(new ol.style.Style({stroke : new ol.style.Stroke({color : "red"})})); work after creation? Is it really necessary to set the style for a single feature and not for the whole layer? – Lars Dec 20 '16 at 7:13
  • Does this work ? stroke: new ol.style.Stroke({ color: '#FF0000', width: 1, }) – Alexis_A Dec 20 '16 at 9:39
  • no! I even tried {color : '#f00', width:1} – burghard Dec 20 '16 at 13:55
2

You cannot just set a style as feature property and expect it to work. If you set properties in the constructor, they will be feature properties. You can either use setStyle() on the feature after the feature is constructed:

var myFeature = new ol.Feature({
  geometry: myGeometry,
});
myFeature.setStyle(myStyle);

or you can configure the vector layer with a style function that picks the style attribute from the feature:

new ol.layer.Vector({
  style: function(feature, resolution) {
    return feature.get('style');
  }
})
1

Instead of "red" in your stroke line, use the RGB value of red: 255,0,0

var myFeature = new ol.Feature({
   geometry : new ol.geom.LineString(coordinates),
   style : new ol.style.Style({
       stroke : new ol.style.Stroke({color : 255,0,0
    })
   })
 });
mySource.addFeature(myFeature);
  • The term {color : 255,0,0} is a js syntax error. I tried {color : "rgb(255,0,0)", "rgba(255,0,0,1.0)", "#rrggbb" and "#rgb" with no success. Even other styles (like width) are not recognised. – burghard Dec 20 '16 at 6:32
  • Is there possibly more information you could provide as to help solve why the color isn't not displaying? – whyzar Dec 20 '16 at 14:08
  • The color syntax in the original poster's code is perfectly fine. – ahocevar Dec 21 '16 at 9:42

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.