我在OpenLayers 5中有一个多边形特征。它有一些随机ID,我需要在多边形的中心稍微右对齐显示。
我使用ol.style.Text()
样式在多边形上显示id。我可以使用类的offsetX
和offsetY
选项来管理对齐,但是如何在html元素中显示文本或模仿它,因为ol.style.Text()
只接受文本数据。
openlayers中的叠加肯定会解决问题,我可以在几何上使用getInteriorPoint()
获得多边形的中点,但我不想使用叠加,因为地图上可能有大量的多边形并且为每个多边形添加叠加会降低性能和内存利用率。
这是我想要实现的预期输出:
这是我的代码:
还要检查我做了什么来切换Id ON和OFF,并提及是否可以改进。可以根据缩放级别打开和关闭ID。
您可以在canvas元素中绘制背景而不是使用CSS,而是以图标样式使用它。并使用样式函数设置多边形内部点的样式,而无需创建更多功能:
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;
}
}