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

标签 openlayers-3

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

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

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

最佳答案

客户端的另一个选择是仅标记多多边形的多边形部分中较大的一个。 对于此选项,您不需要服务器端的任何控制。因此,请使用以下代码或直接访问 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;
 }

关于openlayers-3 - 如何在开放层 3 中为每个多多边形显示一个标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37306548/

相关文章:

javascript - 我们可以让 ol.Overlay 在 OpenLayers 3 上可拖动吗?

openlayers-3 - 如何获得 map 控件或互动

javascript - 以像素为单位的 OpenLayers 特征

javascript - 无法在 OpenLayers3 中获取相对 URL

javascript - openlayers 3 ,聚类多边形或线串

javascript - 在 Firefox 和 ie/edge 上使用 openlayers 3 未加载 map

node.js - Nodejs Openlayers 3 map 服务器

javascript - Chrome 处于最大化窗口模式时不显示 OpenLayers-3 栅格层

javascript - 使用具有不同投影的 ol3-google-maps

javascript - OpenLayers 3 和 Geoserver : Create popup on marker click