选择的效果图展示
直接上代码就完事了
watch: {
drawData: {
handler (val) {
this.isAirport ? this.showPolygon(this.drawData) : this.showPolyline(this.drawData)
},
deep: true
}
}
drawInteraction () {
this.map = new Map({
target: this.$refs.map,
layers: this.sourseLater,
view: new View({
center: fromLonLat([120.004686, 30.297546]),
zoom: 10.5,
maxZoom: 18,
minZoom: 8
})
})
this.source = new VectorSource()
this.draw = new Draw({
source: this.source,
type: this.isAirport ? 'Polygon' : 'LineString', // 判断是否为多边形
style: [
new Style({
stroke: new Stroke({
width: 3,
color: '#CBFFFE',
lineDash: [0.1, 5]
}),
zIndex: 2
})
]
})
this.draw.on('drawstart', (evt) => {
// 在这里在每次开始画之前都会把之前已经画的清除
if (!this.isMultiple) this.source.clear()
})
this.map.addInteraction(this.draw)
this.draw.on('drawend', (evt) => {
const geometry = evt.feature.getGeometry()
const corrdinates = geometry.getCoordinates()
this.drawData = corrdinates
this.multipleDrawData.push(corrdinates)
})
}
/**
*
* @param {*} points 多边形坐标点
*/
showPolygon (points) {
let _points = points
_points = [_points]
// 多边形的数据格式是[[[lng,lat],[lng,lat]……]]外围两个中括号
var polygonFeature = new Feature({ // 路线
geometry: new Polygon(_points)
})
// polygonFeature.setId(fenceId)
this.source.addFeature(polygonFeature)
}
/**
*
* @param {*} points 线型的点坐标
*/
showPolyline (points) {
const _points = points
var lineFeature = new Feature({ // 路线
geometry: new LineString(_points, 'XY')
})
// lineFeature.setId(fenceId)
// 将所有矢量图层添加进去
this.source.addFeature(lineFeature)
}
parseLonlatsObj2Coordinates (lonlats) {
if (lonlats) {
const wrapCoordinatesPolygon = []
for (let i = 0; i < lonlats.length; i++) {
const coordinatesPolygon = []
for (let j = 0; j < lonlats[i].length; j++) {
const pointTransform = fromLonLat([lonlats[i][j].longitude, lonlats[i][j].latitude])
coordinatesPolygon.push(pointTransform)
}
wrapCoordinatesPolygon.push(coordinatesPolygon)
}
return wrapCoordinatesPolygon
} else {
return null
}
}
onkeydown (e) {
const ev = e || event || window.event || window.arguments.callee.caller.arguments[0]
// 键盘按键判断:1-49;2-50;3-51 13是回车
if (ev && ev.keyCode === 32) {
this.draw.finishDrawing()
}
}