[GIS] Providing alternative “label” when styling vector layer with OpenLayers 2

labelingopenlayers-2sldvector

I'm using OpenLayers2.12 and I am styling a vector layer using your typical new OpenLayers.Style({

Now, this layer does two things.

First , renders polygons from GeoServer, so in the style I have 'label': '${p_name}'. Works fine.

The second thing the layer does is providing tools to the user to edit an already existing polygon. So when a user chooses to edit a polygon, (resize it for example) the familiar little points appear , as handlers.

Now, these points/handlers render "undefined", as name because the 'label': '${p_name}' is actually undefined. Did not came from GeoServer.

Is there a workaround? How can I set an alternative name for the handlers?

Best Answer

You can define an custom label-fetching function, instead of just using unprocessed feature attributes. To do this you have to define 'context' property in your OpenLayers.Style, eg.

new OpenLayers.Style({
fillColor: 'blue',
strokeColor: 'navy',
strokeWidth: 3,
pointRadius: 9,
fillOpacity: 0.6,
strokeOpacity: 0.75,
label: '${label}',
fontColor: "black",
fontFamily: "Arial",
fontSize: 11
},
{
    context: {
        label:function(feature) {
            if(feature.attributes['p_name']) {
                return feature.attributes.p_name;
            } else {
                return '';
            }
        }
}
});

This style will render the p_name attribute if defined, and an empty string otherwise, which will result in no label.