官方文档https://lbs.amap.com/demo/javascript-api-v2/example/overlay-editor/polylineeditor
生成矢量图形如上,代码如下
const markerAddof = ref(false)
// 绘图
function drawMark () {
if (!markerAddof.value) {//限制矢量图形点击只显示一个
if (cameraId.value !== 0) {
markerQure()
} else {
squareVertices.value = calculateSquareVertices(
cameraLatInpt.value,//中心坐标
cameraLngInpt.value,//中心坐标
1000
)
setTimeout(() => {
markerQure()
}, 1000)
console.log('squareVertices.value', squareVertices.value)
}
markerAddof.value = true
}
}
对地图进行渲染, 如果点击后只显示一个矢量图形,可以加上限制判断,不需要的不用加。必须添加中心点,需要根据中心点进行渲染
// 画图各个点标记
const calculateSquareVertices = (centerLat, centerLng, sideLength) => {
// 将长度从米转换为经度差值
const deltaLat = (sideLength / 111300) * 1.1
const deltaLng =
(sideLength / (111300 * Math.cos(centerLat * (Math.PI / 180)))) * 1.1
// console.log('deltaLat', deltaLat)
// console.log('deltaLng', deltaLng)
const vertices = [
{ lat: Number(centerLat) + deltaLat, lng: Number(centerLng) - deltaLng }, // 右上角
{ lat: Number(centerLat) - deltaLat, lng: Number(centerLng) - deltaLng }, // 右下角
{ lat: Number(centerLat) - deltaLat, lng: Number(centerLng) + deltaLng }, // 左下角
{ lat: Number(centerLat) + deltaLat, lng: Number(centerLng) + deltaLng }, // 左上角
]
console.log(vertices)
return vertices
}
通过计算给四周的点进行标记,可以直接使用该算法
// 绘图变化
const markerQure = () => {
console.log('进来了没有地图渲染')
// console.log('squareVertices.value', squareVertices.value)
if (view.value) {
// polyEditor.value.close()
// polyEditor.value = null
// map.value.clearMap()
}
const path: any = []
if (cameraId.value !== 0) {
squareVertices.value.forEach((i) => {
path.push([i[0], i[1]])
})
} else {
console.log(' squareVertices.value2', squareVertices.value)
squareVertices.value.forEach((i) => {
path.push([i.lng, i.lat])
})
}
console.log('path', path)
const polygon = new AMap.Polygon({
path: path,
strokeColor: '#FF33FF',
strokeWeight: 6,
strokeOpacity: 0.2,
fillOpacity: 0.4,
fillColor: '#1791fc',
zIndex: 50,
bubble: true,
})
console.log('polygon', polygon)
map.value.add([polygon])
map.value.setFitView()
// centerPointFn()
polyEditor.value = new AMap.PolygonEditor(map.value, polygon)
polyEditor.value.addAdsorbPolygons([polygon])
polyEditor.value.open()
// 监听坐标点的变化
polyEditor.value.on('addnode', function (event) {
squareVertices.value = []
event.target.getPath().forEach((i) => {
squareVertices.value.push({
lng: i.lng,
lat: i.lat,
})
})
console.log('这里有吗', squareVertices.value)
// centerPointFn()
})
view.value = true
// 监听拖动变化
polyEditor.value.on('adjust', function (event) {
squareVertices.value = []
event.target.getPath().forEach((i) => {
squareVertices.value.push({
lng: i.lng,
lat: i.lat,
})
})
console.log('坐标参数', squareVertices.value)
// centerPointFn()
})
polyEditor.value.on('removenode', function (event) {
squareVertices.value = []
event.target.getPath().forEach((i) => {
squareVertices.value.push({
lng: i.lng,
lat: i.lat,
})
})
console.log('坐标参数2', squareVertices.value)
// centerPointFn()
})
}
通过改变点的位置,对矢量图形重新绘画并重新获取各个点的位置进行渲染