2

I have LineString in openlayers-3. I want to set 2 label for this feature In the start and end of the feature. An example is as follow:

enter image description here

How Can I do this labels?

1 Answer 1

2

I resolve this question own and I want to share it with others.
In first step, we define an method that get two point with a max to calculate the position of label. See image:

enter image description here

The code is as follow:

function getLineStylePosition(firstCoor, lastCoor, max)
{
    var deltaX = lastCoor[0] - firstCoor[0];
    var deltaY = lastCoor[1] - firstCoor[1];

    var rotation = Math.atan(deltaY/deltaX) * - 1;

    var offsetX = max * Math.cos(rotation) * (-1);
    var offsetY = max * Math.sin(rotation) * (-1);

    var textAlign = 'right';
    if(deltaX < 0)
    {
        offsetX *= -1;
        offsetY *= -1;
        textAlign = 'left';
    }

    return {
        rotation: rotation,
        textAlign: textAlign,
        offsetX: offsetX,
        offsetY: offsetY
    };
};   

Now you have the offset of style. You can define a style as follow:

var startTextStyle = new ol.style.Text(getLineStylePosition(firstCoor, lastCoor, 15));
startTextStyle.setText("label 1");
startTextStyle.setFont("Arial");
startTextStyle.setFill(new ol.style.Fill({color: 'blue'});

var startStyle = new ol.style.Style({
    text: startTextStyle,
    geometry: new ol.geom.Point(firstCoor)
});

Copy this code for Label 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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