1. 程式人生 > 其它 >【openlayers】- 繪製船舶選中框

【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';

/**
 * 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])); } }