一、安装百度地图
npm install vue-baidu-map --save
// 或者
yarn install vue-baidu-map
二、在main.js中引用
import BMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
// ak 是在百度地图开发者平台申请的密钥 详见 http://lbsyun.baidu.com/apiconsole/key */
ak: 'YOUR_APP_KEY'
})
三、看一下具体代码吧
<template>
<div class="mapbox">
<baidu-map
:center="center"
:zoom="zoom"
:map-click="false"
@mousemove="syncPolygon"
@ready="handler"
style="height:800px"
@click="paintPolygon"
@rightclick="newPolygon"
>
<bm-polygon
:path="path"
v-for="path of polygonPath.paths"
:key="path.toString()"
stroke-color="blue"
fill-color="red"
:fill-opacity="0.8"
:stroke-opacity="0.5"
:stroke-weight="2"
@click="alertpath"
:editing="true" //覆盖物可编辑
@lineupdate="updatePolygonPath" //为了监测编辑覆盖物事件
/>
<bm-control>
<button @click="toggle('polygonPath')">{{ polygonPath.editing ? '停止绘制' : '开始绘制' }}</button>
</bm-control>
</baidu-map>
</div>
</template>
<script>
export default {
name: 'Polygon',
data () {
return {
haha: '百度地图',
center: { lng: 116.412732, lat: 39.911707 },
zoom: 13,
polygonPath: {
editing: false,
paths: [] // 绘制完成后的经纬度,其实是在画的时候动态push的,因为在点击的时候触发了 paintPolygon 函数
}
}
},
mounted: function () {
},
methods: {
handler ({ BMap, map }) {
console.log(BMap, map)
map.enableScrollWheelZoom(true)
// map.centerAndZoom('青岛市', 13)
},
getClickInfo (e) {
console.log(e.point.lng)
console.log(e.point.lat)
},
// 开启多边形绘制
toggle (name) {
this[name].editing = !this[name].editing
// 在这里做一步判断,如果有路径且开启绘制就把原来的路径清空
if (this.polygonPath.paths && this.polygonPath.editing) {
this.polygonPath.paths = []
}
},
// 鼠标移动时
syncPolygon (e) {
if (!this.polygonPath.editing) {
return
}
const { paths } = this.polygonPath
if (!paths.length) {
return
}
const path = paths[paths.length - 1]
if (!path.length) {
return
}
if (path.length === 1) {
path.push(e.point)
}
this.$set(path, path.length - 1, e.point)
},
// 鼠标右键点击时往路径里push一个面
newPolygon (e) {
if (!this.polygonPath.editing) {
return
}
// 当开始绘制后把按钮调回开始绘制状态,防止绘制多个图形
this['polygonPath'].editing = !this['polygonPath'].editing
const { paths } = this.polygonPath
if (!paths.length) {
paths.push([])
}
const path = paths[paths.length - 1]
path.pop()
if (path.length) {
paths.push([])
}
},
// 鼠标左键多边形绘制
paintPolygon (e) {
if (!this.polygonPath.editing) {
return
}
const { paths } = this.polygonPath
!paths.length && paths.push([])
paths[paths.length - 1].push(e.point)
},
alertpath (e) {
console.log(e.currentTarget.so)
console.log(this.polygonPath.paths[0])
},
updatePolygonPath(e) {
//编辑覆盖物时触发,获取坐标点集合
this.polygonPath.paths[0] = e.target.getPath()
}
}
}
如何取得多边形编辑之后的坐标点集合?
被这个问题困扰了住了,先在网上找了好多资料都没找到,在百度地图api文档,发现getPath()方法可以获得,但是找不到多边形的原型,最后在vue-baidu-map官网发现lineupdate事件可以监听到

地图可编辑状态

本文介绍如何在Vue项目中使用vue-baidu-map组件来绘制并编辑多边形,通过监听lineupdate事件获取编辑后的坐标点集合,解决在百度地图API中获取多边形编辑路径的问题。
绘制多边形,支持编辑&spm=1001.2101.3001.5002&articleId=109405953&d=1&t=3&u=31df613f84a044438df5c2b955eeb9c5)
928

被折叠的 条评论
为什么被折叠?



