如何在开放层3中为每个多边形显示一个标签?

Jor*_*ing 4 openlayers-3

我在尝试弄清楚如何在OL3中为每个多边形显示一个标签时遇到问题.它目前显示每个多边形的标签,在这种情况下,在任何情况下都不理想.

截图

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;
}});
Run Code Online (Sandbox Code Playgroud)

如果可能的话,我想在最大的多边形上显示标签.

pav*_*los 5

客户端的另一个选择是从多边形的多边形部分中标出较大的一个.对于此选项,您不需要在服务器端进行任何控制.因此,请使用以下代码或直接指向小提琴以查看其中的操作:

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
  })
});
Run Code Online (Sandbox Code Playgroud)

您还需要一个辅助函数来验证哪个是更大的多边形:

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;
 }
Run Code Online (Sandbox Code Playgroud)