1

I am quite new to OpenLayers. Right now, I have a polygon vector with some styling applied and a label.

var style = $.extend(true, {}, OpenLayers.Feature.Vector.style['default']);
style.pointRadius = 15;
style.label = "My Polygon";
style.fillColor = #f00;
style.strokeColor = #000;

var styleMap = new OpenLayers.StyleMap({"default" : style});

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

At some point after doing some processing, I want to display the result as a label. How can I update the label? I figure it would be something like this, but this wasn't the way.

polygonLayer.options.styleMap.styles.label = "Updated label";

Thanks in advance.

1 Answer 1

3

You are on the right way. You can set new label for all features in a layer like that:

polygonLayer.styleMap.styles.default.defaultStyle.label = "new label";
polygonLayer.redraw();

As you see it's important to call redraw() method after you set new value.

That's how you change label for all features in a layer. Quite often though you'll need to set new labels per feature. To achieve that you should do following when you create pollygonLayer:

var style = $.extend(true, {}, OpenLayers.Feature.Vector.style['default']);
style.label = "${feature_name}";

Each feature has a collection of attributes. In this case value of attribute feature_name will be displayed as a label. To change label value per feature you simply change value of the attribute on that feature and then of course call redraw() on layer.

1
  • Perfect, thanks a lot. This kind of explanation should go into the documentation!
    – Kaung Htet
    Commented Jan 18, 2012 at 8:52

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.