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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With