Question

I need to add custom labels to elements on my Vector layer, however in every example of code I see only directly passed parameters with {$param} syntax, like:

    var myStyle = new OpenLayers.StyleMap({
        default:{
            pointRadius: 40,
            externalGraphic:'img/pin.png',
            label: "{$param}"
        }
    });

Thing I'd need is to make a kind of data renderer like this one:

    var myStyle = new OpenLayers.StyleMap({
        default:{
            pointRadius: 40,
            externalGraphic:'img/pin.png',
            label: function(){
                if (param === 1){
                    return "one";
                } else {
                    return "not one";
                }
            }()
        }
    });

So the problem is - how to get param value into a variable to process it in this case?

Was it helpful?

Solution

What you are looking for is a context which allows to bind a function instead of a template param:

var myContext = {
  getLabel: function(feature) {                    
    return feature.attributes.label;
  }
};
var template = {
  label: "${getLabel}"
};
var style = new OpenLayers.Style(template, {
  context : myContext
});

Here are some resources:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top