我在 OpenLayers 5 中有一个多边形特征。它有一些随机 ID,我需要将其显示在多边形的中心,稍微右对齐。
我使用了 ol.style.Text()
样式在多边形上显示 id。我可以使用类的 offsetX
和 offsetY
选项来管理对齐,但是我如何在 html 元素中显示文本或模仿它,因为 ol.style。 Text()
只接受文本数据。
openlayers 中的叠加肯定会解决问题,我可以在几何体上使用 getInteriorPoint()
获得多边形的中点,但我不想使用叠加,因为可能有大量的多边形在 map 上添加叠加层会降低性能和内存利用率。
这是预期的输出/我正在努力实现:
这是我的代码:
同时检查我为打开和关闭 Id 所做的工作,并提及是否可以改进。可以根据缩放级别打开和关闭 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;
}
}
关于javascript - 我们可以使用 html 标签和 css 来设置 openlayers 中的功能样式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55299633/