How to move the text to top left instead of the bottom left corner in a openlayers feature?

57 views Asked by At
addLabelBox(labelBoxData) {
        const newFeature = new Feature(this.feature.getGeometry());

        const textStyle = new Style({
            fill: new Fill({
                color: 'rgba(162, 72, 87, 1)'
            }),
            stroke: new Stroke({
                color: 'rgba(0, 0, 0, 1)',
                width: 2
            }),
            text: new Text({
                text: labelBoxData.text,
                font: '12px sans-serif',
                fill: new Fill({ color: '#fff' }),
                placement: 'line',
                textBaseline: 'bottom',
                textAlign: 'left'
            })
        });

        // Set the style for the new feature
        newFeature.setStyle(textStyle);

        this.labelBoxesLayer.getSource().addFeature(newFeature);
    }

I am using this function to create a rectangular feature along with the text but the issue I am facing is that the text is rendered in bottom left corner instead of the top left corner as shown in the image. Example

I have played with all the possible combinations of 'placement' and 'textBaseline' but unable to do it. Also, if the length of the text is longer than the box then the text disappears instead of the text breaking into multiple lines. I am using a textarea element to add the text. Any suggestions will be helpful.

1

There are 1 answers

2
Mike On BEST ANSWER

It do notthink you can choose which face of the polygon line placement uses. Instead you could separate the text into a separate style and set a point geometry for it

const textStyle = [
  new Style({
    fill: new Fill({
      color: 'rgba(162, 72, 87, 1)
    }),
    stroke: new Stroke({
      color: 'rgba(0, 0, 0, 1)',
      width: 2
    }),
  }),
  new Style({
    geometry: function (feature) {
      return new Point(getTopLeft(feature.getGeometry().getExtent()));
    },
    text: new Text({
      text: labelBoxData.text,
      font: '12px sans-serif',
      fill: new Fill({color: '#fff'}),
      placement: 'point',
      textBaseline: 'top',
      textAlign: 'left'
    }),
  })
];