2

I'm using OpenLayers 2 and have a number of LineStrings with custom attributes's drawn. I need to change the strokeColor on some of the lines styles programatically and have it stay this color even if the user change zoom level or toggles layer visibility.

Currently I'm filtering/selecting features with vectorLayer.getFeaturesByAttribute() and then I'm using vectorLayer.drawFeature(feature, { strokeColor: "red }) to change the line colors. This work well until the user change the zoom level or if I toggle layer visibility back and forth with vectorLayer.setVisibility(), which for some reason changes the strokeColor back to the defalt style.

What is the correct way of changing the feature style and make it "stick"?

2 Answers 2

1

Your changes are disappearing because the map is being redrawn when you toggle the visibility or change zoom level. You need to alter the style attribute of the feature itself so that when the redraw happens, it uses the updated style values.

Try this approach:

var feature = vectorLayer.getFeaturesByAttribute(...);
feature.style = { strokeColor: "red" };
vectorLayer.redraw();
0

you can use a stylemap with a context function:

var your_context = {
    getColor: function (feature) {
        if (feature.attributes.id == 1) {
            return "red";
        } else if (feature.attributes.id == 2) {
            return "blue";
        } else if (feature.attributes.id == 3) {
            return "cyan";
        } else {
            return "yellow";
        }
    }
};


var yourStyle = new OpenLayers.Style({
    fillColor: "white",
    strokeColor: "${getColor}",
    strokeOpacity: "0.7",
    strokeWidth: 2,
    cursor: "pointer",
        'pointRadius': 10
}, {
    context: your_context
});



var selectStyle = new OpenLayers.Style({
    'pointRadius': 15,
    strokeColor: "yellow",
});

var your_styleMap = new OpenLayers.StyleMap({
    'default': yourStyle,
        'select': selectStyle
});

var vector_layer = new OpenLayers.Layer.Vector("Vector Layer", {
    styleMap: your_styleMap
});

map.addLayer(vector_layer);

Here you can see this example in action: http://jsfiddle.net/expedio/jjbj4qn8/

2
  • Thanks for the help, but I'm not sure how this would help me. This solution is for static attribute values, right? My feature custom attributes are not static, they are generated and will change all the time. Sorry. Commented Jun 21, 2016 at 8:43
  • Stylemaps can be generated dynamically and assigned to layer programmetrically. This is better than styling features.
    – neogeomat
    Commented Sep 16, 2017 at 6:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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