【Openlayers】- 绘制船舶选中框
实现原理:使用 openlayers 中的 style 多边形绘制,然后边框使用虚线,以 3:4:3:0 的比例,实现选中框的绘制
openlayers版本:6.5.0
1、效果图

2、代码如下
import { Stroke, Style, RegularShape } from 'ol/style';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import VectorSource from 'ol/source/Vector';
/**
* list: [lon, lat]
* radius: 选中框的半径,即中心点到四个顶点的距离
*/
drawCheckBoxByRadius(list, radius) {
var shipCheckBoxId = "ship_check_box"
// 首先获取选中框
var CheckBoxFeature = this.shipCheckBoxSource.getFeatureById(shipCheckBoxId);
if (CheckBoxFeature === null) { // 若选中框不存在,开始绘制选中框
// init选中框的 Layer 和 Source
this.initShipCheckBoxSource()
this.shipCheckBoxLayer.setSource(this.shipCheckBoxSource)
// 根据半径,计算出选中框的边长
var longRadius = radius * Math.SQRT2;
let styless = new Style({
image: new RegularShape({
stroke: new Stroke({
color: "#f00",
width: 0.8,
// 实虚比例,这里使用3:4:3:0比例,显示效果为 3实线 4透明 3实线 0透明,依次循环,形成一个选中框样式
lineDash: [longRadius * 3 / 10, longRadius * 4 / 10, longRadius * 3 / 10, 0]
}),
radius: radius,
points: 4,
// openlayers中,多边形默认角朝上,所以需要将图形翻转45度
rotation: Math.PI / (180 / 45),
}),
})
let shipFeature = new Feature({
geometry: new Point([list[0], list[1]])
});
// 放入id方便随时获取
shipFeature.setId(shipCheckBoxId);
shipFeature.setStyle(styless)
this.shipCheckBoxSource.addFeature(shipFeature);
} else { // 若选中框已存在,重新定位
CheckBoxFeature.setGeometry(pointLonLat(list[0], list[1]));
}
},
initShipCheckBoxSource() {
this.shipCheckBoxSource = new VectorSource({
features: [],
});
}

浙公网安备 33010602011771号