OpenLayers – Displaying Feature Labels in JavaScript

javascriptopenlayers

I try to add labels of a vector I added in openlayers with a stylefunction. The function works for stroke, but no text is displayed and I can't find a solution for it.

My code is the following:

var myfeature = new ol.layer.Vector({
  title: '  myfeature',
  source: new ol.source.Vector({
      url: 'data/myfeature.geojson',
      format: new ol.format.GeoJSON()
  }),
  style: styleFunction
});

function styleFunction() {
  return [
  new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: [0, 0, 0, 1.0],
      width: 1,
      lineDash: [1, 5, 3, 5]
    }),
    text: new ol.style.Text({
      font: '50px Calibri'
      }),
      text: myfeature.get('label')
    })
  ];
}

The fault is probably in text: myfeature.get('label'), but I can't say what I do wrong nor worked anything else I tried.

Best Answer

You have declared myfeature as your layer. OpenLayers passes individual features as a parameter of the style function, so you must add a parameter to the function and use that to get properties

function styleFunction(feature) {
  return [
  new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: [0, 0, 0, 1.0],
      width: 1,
      lineDash: [1, 5, 3, 5]
    }),
    text: new ol.style.Text({
      font: '50px Calibri'
      text: feature.get('label'),
      placement: 'line',
      fill: new ol.style.Fill({
        color: '#000'
      }),
      stroke: new ol.style.Stroke({
        color: '#fff',
        width: 3
      })
    }),
  })
  ];
}