[GIS] In OpenLayers, how to set feature.style when using attribute-dependent symbolizers

openlayers-2

I am using dynamic (attribute-dependent) symbolizers on a vector layer. In this CodePen example, we have the colors of the states depeding on the PERSONS attribute, which given the number of inhabitants of that state.

I use the context property when initializing the Style, I use a StyleMap and everything works just fine.

/* Symbolizer */
symbolizer = {
    fillColor: '${getFillColor}',
    fillOpacity: 1,
    strokeWidth: 1,
    graphicName: 'circle'
};

/* Rule */
var rule = new OpenLayers.Rule({
    filter: filter,
    symbolizer: symbolizer
});

/* Context */
var context = {
    getFillColor: function(feature) {
        var persons = feature.attributes.PERSONS;
        return convertNumberToColor({
            value: persons,
            min: 453588,
            max: 29760021,
            colorRange: 'gr'
        });
    }
};

/* Style */
var style = new OpenLayers.Style({}, {
    context: context
});
style.addRules([rule]);

/* Style map */
var styleMap = new OpenLayers.StyleMap(style);
vector.styleMap = styleMap;

The problem comes when I try to highlight one of the features. By highlighting I mean this: maintain all the symbolizers of the feature and only change some. For example, in a red polygon, the highlighting would mantain its red color, but wuld change the strokeWidth.

var highlight = function(feature) {
    feature.style = $.extend({}, symbolizer, {
        strokeWidth: 5
    });
    vector.drawFeature(feature);
};

As you can see, I want to perform the highlighting in the feature.style property, because it does not interfere with the original styleMap and so I can easily remove the highlighting.

Please check out the CodePen above. When highlighting California, the fillColor should remain red, but it changes to green. The same happens with Texas.

Would you please help me to correctly implement highlighting in the feature.style propert when using attribute-dependent symbolizers?

Best Answer

After some more research, I found the solution here.

The feature.style property only accepts the symbolizer as hash style. So, we must use the styleMap to create a symbolizer for the current feature

var highlight = function(feature) {
    var style = $.extend({}, styleMap.createSymbolizer(feature), {
        strokeWidth: 5
    });
    feature.style = style;
    vector.drawFeature(feature);
};

I created a new CodePen, where the highlighting works correctly. :)