I have a polygon feature in OpenLayers 5. It has some random id which I need to show at the center of the polygon slightly right aligned.
I have used the ol.style.Text()
style to display the id on polygon. I can manage the alignment using the offsetX
and offsetY
options of the class but how can I display the text in html elements or imitate it, because ol.style.Text()
only accepts text data.
Overlays in openlayers will definitely solve the problem, I was able get middle point of polygon using getInteriorPoint()
on geometry but I don't want to use overlays because there could be large number of polygons on the map and adding overlay for each would deteriorate performance and memory utilization.
Here is the expected output / I am trying to achieve :
Here is my code :
Also check what I have done to toggle the Id ON and OFF and mention if that can be bettered. The ID could be turned ON and OFF based on zoom level.
Instead of using CSS you could draw the background in a canvas element and use it in an icon style. And use a style function to style the interior point of a polygon without needing to create more features:
var canvas = document.createElement("canvas");
canvas.width = ??;
canvas.height = ??;
var ctx = canvas.getContext("2d");
// draw an arraw and rounded box
.....
.....
var iconUrl = canvas.toDataURL();
var offStyle = new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255,255,255,0)'
}),
stroke: new ol.style.Stroke({
color: 'green',
width: 1.5
})
});
var onStyle = new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255,255,255,0)'
}),
stroke: new ol.style.Stroke({
color: 'black',
width: 1.5
})
});
var styleFunction = function (feature, resolution) {
if (off) { // or use (resolution > ????)
return offStyle;
else {
var styles = [onStyle];
if (feature.getGeometry().getType == 'Polygon') {
styles.push( new ol.style.Style({
geometry: feature.getGeometry().getInteriorPoint(),
image: new ol.style.Icon({
src: iconUrl,
// options to anchor the icon
....
}),
text: new ol.style.Text({
scale: 1,
text: feature.get('.....'),
font: 'normal 10px FontAwesome',
fill: new ol.style.Fill({
color: 'black'
}),
}),
zIndex: 100
}));
}
return styles;
}
}