[GIS] Add labels to points in OpenLayers

labelingopenlayers-2

I have a Layer:

          pointLayer = new OpenLayers.Layer.Vector("Point Layer", {
            strategies: [strategy],
            styleMap: new OpenLayers.StyleMap({
                "default": {
                    label : "${text}",
                    pointRadius: 10,
                    fillColor: "#ffcc66",
                    fillOpacity: 0.8,
                    strokeColor: "#cc6633",
                    strokeWidth: 2,
                    strokeOpacity: 0.8
                },
                "select": {
                    fillColor: "#8aeeef",
                    strokeColor: "#32a8a9"
                }
            })
        });  

I create this layer without any feature. I periodically call the server and get json objects from it. The json objects have coordinate attributes and a text attribute. After i get the objects, i put points on the layer. I set the text attribute in the point features:

pointFeature.attributes = {
    text: jsonObj.text
};

The problem is that the labels don't appear on the layer (but the points appear). I noticed that the labels appeared only when i added the point features to the layer before i added the layer to the map.

I found the redraw() method, but it doesn't work because after the server call i remove all the points from the layer and add the new points to it.

To summarize the problem: i want to display labels of point features which were added to the layer after the layer was added to the map.

Best Answer

try to attach a style to each feature (point) before adding it to the layer. http://dev.openlayers.org/docs/files/OpenLayers/Feature/Vector-js.html#OpenLayers.Feature.Vector.style

eg

pointFeature.style = {
                label : "${text}",
                pointRadius: 10,
                fillColor: "#ffcc66",
                fillOpacity: 0.8,
                strokeColor: "#cc6633",
                strokeWidth: 2,
                strokeOpacity: 0.8
            }