0

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.

2

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
      })
    }),
  })
  ];
}
  • That still doesn't fix it, it's the same as before: The stroke style is applied, but no text appears. And I don't get an error message in firefox. – gHupf Mar 4 at 13:47
  • And one more thing: If I change the text to a string (text: 'Hello') I get the error message "TypeError: t.getFill is not a function" – gHupf Mar 4 at 13:53
  • If you are placing text on linestring features you either need a placement point geometry or must use placement: 'line' It is also usual to specify stroke and fill style for the text, although OpenLayer will set defaults if not specified. – Mike Mar 4 at 14:02
  • I didn't know about the placement, thanks! But I still get the same error as mentioned above "TypeError: t.getFill is not a function" and no labels are displayed – gHupf Mar 4 at 14:12
  • text: was below the }), which closed the ol.style.Text({ – Mike Mar 4 at 14:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.