我在尝试弄清楚如何在 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;
}});
如果可能的话,我想在最大的多边形上显示标签。
最佳答案
客户端的另一个选择是仅标记多多边形的多边形部分中较大的一个。 对于此选项,您不需要服务器端的任何控制。因此,请使用以下代码或直接访问 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/