I want to write labels near linestring features on my map. I calculated but it works wrong.

My layer style function is like following:

layerFeatures = new ol.layer.Vector({
    source: sourceFeatures,
    style: function(feature, resolution){

        let first = feature.getGeometry().getCoordinates()[0];
        let last = feature.getGeometry().getCoordinates()[1];

        let rotation = -Math.atan2((last[1] - first[1]),(last[0] - first[0]));

                    var style = new ol.style.Style({
             fill: new ol.style.Fill({
             color: 'rgba(255,255,255,0.4)'
           stroke: new ol.style.Stroke({
             color: '#3399CC',
             width: 1.25
           text: new ol.style.Text({
             font: '14px Verdana',
             fill: new ol.style.Fill({
              color: '#000000'
             stroke: new ol.style.Stroke({
              color: '#f2f',
              width: 1

        let label = feature.get("properties").name;


        return [style];


The directions of labels are wrong. It shold be readable direction, but some of them are reversed.

and my working code is here


Using atan would give better results than atan2:

let rotation = -Math.atan((last[1] - first[1])/(last[0] - first[0]));

You could also switch to a more recent version of OpenLayers and use the

placement: 'line',

option in ol.style.Text (introduced in version 4) which avoids having to set rotation

  • how can I set the offsetx and ofsety? I want to set text 10px up of the line. – barteloma Aug 29 '19 at 21:38
  • textBaseline: 'bottom', offsetY: -10, works correctly with version 4, but with the version in your jsfiddle the offset doesn't take account of rotation. – Mike Aug 29 '19 at 21:58

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.