1
votes

Hello I need to display some text below each point from a GeoJson layer in an OpenLayers map. I have a GeoJson source and I'm able to plot Points at right coordinates on the map. I would like to draw also some text below the Point and the text is from a property.

My GeoJson is like this:

{ "type": "FeatureCollection",
"features": [
  { "type": "Feature",
    "geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
    "properties": {"name": "example text"}
    },
  {... other features ... }
   ]
 }

And I need to display the text "example text" below the Point. How to do that?

1

1 Answers

1
votes

I have modified http://openlayers.org/en/latest/examples/geojson.html?q=GeoJSOn example to demonstrate how to do this. I have modified the GeoJSON data to add some properties.

Since you want to text declared in properties of feature the styling needs to be handled per feature basis.

Relevant Code:

var styleFunction = function(feature) {

        var text = new ol.style.Style({
            text :new ol.style.Text({
                text: feature.getProperties().name,**//this is where the property value used**
                font: '12px Calibri,sans-serif',
                weight:'Bold',
                fill: new ol.style.Fill({ color: '#000' }),
                stroke: new ol.style.Stroke({
                    color: '#D3D3D3', width: 10
                }),
                offsetX: 30,
                offsetY: -25,
                rotation: 0
            })
        });
        return [styles[feature.getGeometry().getType()],text];
      };

Create a ol.style.Text object and append that object to ol.Feature style property(one for the Feature styling and another for labels)

I have created a working code in plunker. Go through this link.