Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show one label per multi-polygon in open layers 3?

Tags:

openlayers-3

I'm having an issue trying to figure out how to show one label per multipolygon in OL3. It currently shows the label for every polygon which is not ideal under any circumstance in this particular scenario.

screenshot

var vector = new ol.layer.Vector({
source: new ol.source.Vector({
    format: new ol.format.GeoJSON(),
    projection: 'EPSG:4326',
    url: 'resources/ol3/countries.geojson'
}),
style: function (feature, resolution) {
    style.getText().setText(resolution < 10000 ? feature.get('NAME') : '');
    style.getFill().setColor('rgba(255, 255, 255, 0)');
    return styles;
}});

I'd like to show the label on the largest polygon if possible.

like image 568
Jordan Harding Avatar asked Dec 24 '22 05:12

Jordan Harding


1 Answers

One more option for the client side is to label just the bigger one, out of the polygon parts of the multipolygon. For this option you dont need any control on the server-side. So use the following code or go direclty to the fiddle to see it in action:

var vector = new ol.layer.Vector({
  style: function (feature, resolution) {
    var polyStyleConfig = {
      stroke: new ol.style.Stroke({
        color: 'rgba(255, 255, 255, 1)',
        width: 1
      }),
      fill: new ol.style.Fill({
        color: 'rgba(255, 0, 0,0.3)'
      })
    }
    var textStyleConfig = {
      text:new ol.style.Text({
        text:resolution < 100000 ? feature.get('NAME') : '' ,
        fill: new ol.style.Fill({ color: "#000000" }),
        stroke: new ol.style.Stroke({ color: "#FFFFFF", width: 2 })
      }),
      geometry: function(feature){
        var retPoint;
        if (feature.getGeometry().getType() === 'MultiPolygon') {
          retPoint =  getMaxPoly(feature.getGeometry().getPolygons()).getInteriorPoint();
        } else if (feature.getGeometry().getType() === 'Polygon') {
          retPoint = feature.getGeometry().getInteriorPoint();
        }
        console.log(retPoint)
        return retPoint;
      }
    }
    var textStyle = new ol.style.Style(textStyleConfig);
    var style = new ol.style.Style(polyStyleConfig);
    return [style,textStyle];
  },
  source: new ol.source.Vector({
    url: 'http://openlayers.org/en/v3.8.2/examples/data/geojson/countries.geojson',
    format: new ol.format.GeoJSON(),
    wrapX: false
  })
});

You also need a helper function to verify which one is the bigger polygon:

function getMaxPoly(polys) {
  var polyObj = [];
  //now need to find which one is the greater and so label only this
  for (var b = 0; b < polys.length; b++) {
    polyObj.push({ poly: polys[b], area: polys[b].getArea() });
  }
  polyObj.sort(function (a, b) { return a.area - b.area });

  return polyObj[polyObj.length - 1].poly;
 }
like image 176
pavlos Avatar answered Feb 13 '23 09:02

pavlos