1

I would like to have more control of the label placement for polygon geometries in OpenLayers. In some cases, I need to rotate the Label. How does that work if I draw the style on the canvas directly? Currently, the Text just disappears if I apply rotation and the anchor of rotation

My code so far:

const interactionLayer = new VectorImageLayer({
    source: featureSource,
    zIndex: Number.MAX_SAFE_INTEGER,
    style: (feature, resolution) => {
        return new Style({
            renderer: (pxGeometry, state) => {
                if (!isPolygon(pxGeometry)) {
                    return;
                }
                const [x, y] = polylabel(pxGeometry, 1.0);

                const polygon = new Polygon(pxGeometry);

                const olContext = toContext(state.context);

                olContext.setFillStrokeStyle(
                    new Fill({
                        color: "rgba(0,0,0,0.5)",
                    }),
                    new Stroke({
                        color: "#FF0000",
                    })
                );

                olContext.drawGeometry(polygon);

                state.context.save();
              
                state.context.rotate(-Math.PI / 2);
                state.context.translate(x, y);
                
                state.context.fillText(`x: ${x}, y: ${y}`, x, y);

                state.context.restore();
            },
        });
    },
});

The result if translating and then apply rotation:

enter image description here

4
  • 1
    Try translating to the required position before rotating the context.
    – Mike
    Commented Dec 17, 2022 at 13:16
  • Did that, see my edit. x and y commin from this lib github.com/mapbox/polylabel it's "pole of inaccessibility", in my case just the center of the polygon currently
    – BR75
    Commented Dec 17, 2022 at 13:36
  • 1
    You have already translated to x, y so the fillText should be done at 0, 0
    – Mike
    Commented Dec 17, 2022 at 15:14
  • You are right, works as expected, thank you so much. Would accept your answer if you like to answer
    – BR75
    Commented Dec 17, 2022 at 18:17

1 Answer 1

2

Call .translate(x, y) before applying rotation at the required position, and no further x, y offset is required in fillText() if it has already been translated.

            state.context.translate(x, y);
            state.context.rotate(-Math.PI / 2);
            
            state.context.fillText(`x: ${x}, y: ${y}`, 0, 0);

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.