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

How to show one label per multi-polygon in open layers 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;
}});

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

ol3 不支持你想做的事情,至少 'natively' 不支持。有几种方法可以完成你想要的,但我不认为在 'client side' 上做是最好的方法。

1 - 简单快捷的方式,服务器端

如果您可以控制您的数据/服务器,那么我将从那里管理要显示的标签。您可以创建一个 'label-specific' 字段,其中包含您要显示的文本的副本,对于那些您不要将其留空的字段。如果您只希望最大的岛屿块始终具有标签,那将有效。

2 - 复杂而缓慢的方式 - 客户端

在客户端,在您的样式函数中,您可以在每个特征中循环并收集那些与试图标记的特征具有相同名称的特征,然后比较它们的几何面积。仅在没有其他具有更大面积的同名要素时才标记该要素。

这个解决方案也可以在服务器端实现。如果该要素是同名要素中面积最大的要素,则可以 return 一个值为 1 的额外字段,否则为 0。您只会标记此字段 = 1 的要素。

客户端的另一种选择是只标记多边形的多边形部分中较大的那个。 对于此选项,您不需要在服务器端进行任何控制。因此,请使用以下代码或直接访问 fiddle 以查看实际效果:

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
  })
});

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

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;
 }