goscamp
goscamp

Reputation: 1106

put text in the middle of drawn areas Open Layer

I have kml files with Polygons. Each set of polygons(each kml) has a name. When I show polygons on map, I also show their name.

The issue is that the same text appear in every polygon, while I would like the text to appear once only, in the middle of all polygons.

see picture

function addMarkedArea(markedArea){

    var text =  markedArea.areaMapa == null?  markedArea.name : markedArea.name + '\n' + markedArea.areaMapa + ' ha'
    features = new ol.format.KML({
        extractStyles: false
    }).readFeatures(markedArea.kml, {
        dataProjection: 'EPSG:4326',
        featureProjection: 'EPSG:3857'
    });

    var KMLvectorSource = new ol.source.Vector({
        features: features
    });

    var KMLvector = new ol.layer.Vector({
        name: markedArea.Id,
        source: KMLvectorSource,
        style: function(feature, resolution) {
            return new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: markedArea.color,
                    width: 3
                }),
                text: styleText(text, markedArea.color).text
            });
        }
    });

    map.getView().fit(KMLvector.getSource().getExtent(), map.getSize());
    map.addLayer(KMLvector);
}

var styleText = function(text, color) {
    var zoom = map.getView().getZoom();
    var font = (zoom )
    return {
        text: new ol.style.Text({
            font: font+'px Arial',
            fill: new ol.style.Fill({
                color: color
            }),
            stroke: new ol.style.Stroke({
                color: '#000',
                width: 3
            }),
            textAlign: "center",
            textBaseline: "middle",
            text:  text,
            overflow: true
        })
    }
}

Is it possible to do?

Upvotes: 1

Views: 813

Answers (1)

Mike
Mike

Reputation: 17897

Split the style into a array and give the text part a point geometry

    style: function(feature, resolution) {
        return [
          new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: markedArea.color,
                width: 3
            })
          }),
          new ol.style.Style({
            geometry: new ol.geom.Point(ol.extent.getCenter(KMLvector.getSource().getExtent())),
            text: styleText(text, markedArea.color).text
          })
        ];

Upvotes: 5

Related Questions