vue使用百度地图绘制多边形
封装的一个组件DrawMap.vue
抛出属性:
pathss(默认绘制区域)
lat(纬度)lng(经度)【中心点】
scales(缩放大小)
is_Show(是否显示编辑按钮)
<style lang="less" scoped>
.mapbox{
width: 100%;
height: 100%;
}
</style>
<template>
<div class="mapbox">
<baidu-map
:center="center"
:zoom="zoom"
:map-click="false"
@mousemove="syncPolygon"
@ready="handler"
style="height:100%"
@click="paintPolygon"
@rightclick="newPolygon"
>
<bm-polygon
:path="path"
v-for="path of polygonPath.paths"
:key="path.toString()"
stroke-color="#FE8C73"
fill-color="#FE886E"
:fill-opacity="0.8"
:stroke-opacity="0.5"
:stroke-weight="2"
@click="alertpath"
/>
<bm-control>
<button v-if="isShow" @click="toggle('polygonPath')">{{ polygonPath.editing ? '停止绘制' : '开始绘制' }}</button>
</bm-control>
</baidu-map>
</div>
</template>
<script>
export default {
props:['pathss','lat','lng','scales','is_Show'],
name:'',
data() {
return {
center: { lng: 116.412732, lat: 39.911707 },
zoom: 13,
polygonPath: {
editing: false,
paths: [
// [
// {lat: '37.796849',lng: '112.611435'},
// {lat: '37.792115',lng: '112.611004'},
// {lat: '37.792229',lng: '112.62164'},
// {lat: '37.79759',lng: '112.62164'}
// ],
] // 绘制完成后的经纬度,其实是在画的时候动态push的,因为在点击的时候触发了 paintPolygon 函数
},
//中心点
clat:'37.796849',
clng:'112.611435',
// 缩放大小
scale:15,
//是否显示按钮
isShow:false,
}
},
created(){
},
mounted() {
this.isShow=this.is_Show
this.polygonPath.paths.push(this.pathss)
if(this.lat!=''&&this.lng!=''){
this.clat=this.lat
this.clng=this.lng
}
if(this.scales!=''){
this.scale=this.scales
}
},
methods: {
handler ({ BMap, map }) {
console.log(BMap, map)
map.enableScrollWheelZoom()
let a=new BMap.Point(this.clng,this.clat)
map.centerAndZoom(a, this.scale)
},
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 () {
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([])
}
//右击结束
console.log('右击结束')
},
// 鼠标右键多边形绘制完成
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])
}
}
}
</script>