I am developing a OpenLayers application which does dynamic classification of a vector layer. Therefore I am trying to loop through a specific number of thematic classes (categories) and define a filter for each class inside.
A OpenLayers object called OpenLayers.Filter.Function represents each of the filters. Each OpenLayers.Filter.Function overwrites the evaluate() function of the OpenLayers class.
My code looks like this:
var rules = new Array();
for (var i = 0; i < numClasses; i++) {
filter_x = function() {
return new OpenLayers.Filter.Function({
evaluate: function(attributes) {
// some code to define the filter
// uses specific values: array[i] & array[i+1
}
var rule_x = new OpenLayers.Rule({
filter: filter_x,
symbolizer: { fillColor: colors[i],
fillOpacity: 0.5, strokeColor: "white"}
});
rules.push(rule_x);
}
thematicStyle.addRules(rules);
Unfortunately this does not work. It seems that all filters execute the evaluate()-function of the last loop cycle.
Do you have any ideas?
You’re doing a closure over
iwhich is mutable, that is, for all of your rules, the value ofiwill be the same in the end, namely,numClasses - 1.iis the same variable, shared for all iterations. No copy is created inside the body of the loop.Here’s the right way to do it:
In future versions of Javascript, you’ll be able to do
let j = iinside the for-loop, but for now on, you’re stuck with these semantics.