一、安裝百度地圖
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' })
三、看一下具體代碼吧
1 <template> 2 <div class="mapbox"> 3 <baidu-map 4 :center="center" 5 :zoom="zoom" 6 :map-click="false" 7 @mousemove="syncPolygon" 8 @ready="handler" 9 style="height:800px" 10 @click="paintPolygon" 11 @rightclick="newPolygon" 12 > 13 <bm-polygon 14 :path="path" 15 v-for="path of polygonPath.paths" 16 :key="path.toString()" 17 stroke-color="blue" 18 fill-color="red" 19 :fill-opacity="0.8" 20 :stroke-opacity="0.5" 21 :stroke-weight="2" 22 @click="alertpath" 23 /> 24 <bm-control> 25 <button @click="toggle('polygonPath')">{{ polygonPath.editing ? '停止繪制' : '開始繪制' }}</button> 26 </bm-control> 27 </baidu-map> 28 </div> 29 </template> 30 31 <script> 32 export default { 33 name: 'Polygon', 34 data () { 35 return { 36 haha: '百度地圖', 37 center: { lng: 116.412732, lat: 39.911707 }, 38 zoom: 13, 39 polygonPath: { 40 editing: false, 41 paths: [] // 繪制完成后的經緯度,其實是在畫的時候動態push的,因為在點擊的時候觸發了 paintPolygon 函數 42 } 43 } 44 }, 45 mounted: function () { 46 }, 47 methods: { 48 handler ({ BMap, map }) { 49 console.log(BMap, map) 50 map.enableScrollWheelZoom(true) 51 // map.centerAndZoom('青島市', 13) 52 }, 53 getClickInfo (e) { 54 console.log(e.point.lng) 55 console.log(e.point.lat) 56 }, 57 // 開啟多邊形繪制 58 toggle (name) { 59 this[name].editing = !this[name].editing 60 // 在這里做一步判斷,如果有路徑且開啟繪制就把原來的路徑清空 61 if (this.polygonPath.paths && this.polygonPath.editing) { 62 this.polygonPath.paths = [] 63 } 64 }, 65 // 鼠標移動時 66 syncPolygon (e) { 67 if (!this.polygonPath.editing) { 68 return 69 } 70 const { paths } = this.polygonPath 71 if (!paths.length) { 72 return 73 } 74 const path = paths[paths.length - 1] 75 if (!path.length) { 76 return 77 } 78 if (path.length === 1) { 79 path.push(e.point) 80 } 81 this.$set(path, path.length - 1, e.point) 82 }, 83 // 鼠標左鍵點擊時往路徑里push一個點 84 newPolygon (e) { 85 if (!this.polygonPath.editing) { 86 return 87 } 88 // 當開始繪制后把按鈕調回開始繪制狀態,防止繪制多個圖形 89 this['polygonPath'].editing = !this['polygonPath'].editing 90 const { paths } = this.polygonPath 91 if (!paths.length) { 92 paths.push([]) 93 } 94 const path = paths[paths.length - 1] 95 path.pop() 96 if (path.length) { 97 paths.push([]) 98 } 99 }, 100 // 鼠標右鍵多邊形繪制完成 101 paintPolygon (e) { 102 if (!this.polygonPath.editing) { 103 return 104 } 105 const { paths } = this.polygonPath 106 !paths.length && paths.push([]) 107 paths[paths.length - 1].push(e.point) 108 }, 109 alertpath (e) { 110 console.log(e.currentTarget.so) 111 console.log(this.polygonPath.paths[0]) 112 } 113 } 114 }