Gerald Ding
Gerald Ding

Reputation: 15

Open Layers 3 Labels won't show

I'm trying to make my map display labels. But no text is showing up on my map. There are no errors. Here's how I create the style:

labelItem = {name: "name1", font: "arial", fontSize: 20}
computeFeatureStyle = function(labelItem) {
    return new ol.style.Style(
        {   
            stroke: new ol.style.Stroke({
                color: 'black'
            }),
            text: new ol.style.Text(
                {
                    font: labelItem.fontSize + "px helvetica," + labelItem.font,
                    text: labelItem.name,
                    fill: new ol.style.Fill(
                        {
                            color: "#000" //labelItem.fill_color
                        }),
                    stroke: new ol.style.Stroke(
                        {
                            color: "#fff", //labelItem.stroke_color,
                            width: 2
                        }),
                })
        });
};

Here I create the layer object:

labelData = [{name: "name1", font: "arial", fontSize: 20}]
createLabelLayer = function() {
    // Geometries
    // Source and vector layer
    var vectorSource = new ol.source.Vector({ projection: 'EPSG:4326' });
    var layer = new ol.layer.Vector({ source: vectorSource });
    var labelFeatures = [];
    for(var i = 0; i < labelData.length; ++i ) {
        var labelItem = labelData[i];
        var point = new ol.geom.Point(convertCoordinateToWeb( Ext.getCmp("map").map.getView().getCenter()) );
        var feature = new ol.Feature({
                                         geometry: point,
                                         name: labelItem.name
                                     });
        feature.setStyle([this.computeFeatureStyle(labelItem)]);
        vectorSource.addFeature( feature );
    }
    vectorSource.addFeatures(labelFeatures);

    return layer
};

here's my vector layer. I did map.addLayer(layer) But the labels won't show on the map. What am I doing wrong?

I also tried to add the style object to the vector directly: layer.setStyle(computeFeatureStyle(labelItem)), it still doesn't work.

Upvotes: 1

Views: 1511

Answers (1)

Alexandre Dub&#233;
Alexandre Dub&#233;

Reputation: 2829

The best way to debug your code would be to explode it a little. For example, instead of returning the style directly in the style function, put it in a variable first. Then, in your favourite browser Developer Tool, put a break point at the line you return the style. It will allow you to spy the content of the style and see if there's something wrong there.

Also, check if 'static' values would work. Hardcode the values you expect to have as result, just to test.

You could take a look at the following example, which could also help: http://openlayers.org/en/v3.3.0/examples/vector-labels.html

Upvotes: 1

Related Questions