vue專案中使用百度地圖
阿新 • • 發佈:2020-12-13
近期有一個專案,考生報名的時候,需要填寫自己的居住地址,要求通過地圖來選擇地址,獲取考生居住地的經緯度,方便主考單位就近給考生安排考場。
本人主要是做後端開發,前端開發不是很熟,在此記錄一下,也方便其他有需求的朋友參考一下。如有不足之處,歡迎指正。
功能實現細節:
第一步安裝外掛: npm install vue-baidu-map --save
第二步:全域性註冊,在main.js中引入以下程式碼
import BaiduMap from 'vue-baidu-map' Vue.use(BaiduMap, { ak: '你申請的key' })
第三步:介面程式碼
<template> <div class="app-container"> <el-autocomplete v-model="mapLocation.address" :fetch-suggestions="querySearch" placeholder="請輸入詳細地址" style="width: 80%" :trigger-on-focus="false" @select="handleSelect" /> <div style="margin: 5px"> <baidu-map :center="mapCenter" :zoom="zoom" @ready="handler" style="height:1080px" @click="getClickInfo" :scroll-wheel-zoom='true'> </baidu-map> </div> </div> </template> <script> export default { name: 'TestBaiDu', data () { return { mapCenter: { lng: 109.45744048529967, lat: 36.49771311230842 }, zoom: 13, mapLocation: { address: undefined, coordinate: undefined } } }, methods: { handler ({BMap, map}) { this.BMap = BMap this.map = map if (this.mapLocation.coordinate && this.mapLocation.coordinate.lng) { this.mapCenter.lng = this.mapLocation.coordinate.lng this.mapCenter.lat = this.mapLocation.coordinate.lat this.mapZoom = 15 map.addOverlay(new this.BMap.Marker(this.mapLocation.coordinate)) } else { this.mapCenter.lng = 113.271429 this.mapCenter.lat = 23.135336 this.mapZoom = 10 } }, getClickInfo (e) { console.log(e.point.lng) console.log(e.point.lat) this.mapCenter.lng = e.point.lng this.mapCenter.lat = e.point.lat }, querySearch(queryString, cb) { var that = this var myGeo = new this.BMap.Geocoder() myGeo.getPoint(queryString, function(point) { if (point) { that.mapLocation.coordinate = point that.makerCenter(point) } else { that.mapLocation.coordinate = null } }, this.locationCity) var options = { onSearchComplete: function(results) { if (local.getStatus() === 0) { // 判斷狀態是否正確 var s = [] for (var i = 0; i < results.getCurrentNumPois(); i++) { var x = results.getPoi(i) var item = { value: x.address + x.title, point: x.point } s.push(item) cb(s) } } else { cb() } } } var local = new this.BMap.LocalSearch(this.map, options) local.search(queryString) }, handleSelect(item) { var { point } = item this.mapLocation.coordinate = point this.makerCenter(point) }, makerCenter(point) { if (this.map) { this.map.clearOverlays() this.map.addOverlay(new this.BMap.Marker(point)) this.mapCenter.lng = point.lng this.mapCenter.lat = point.lat this.mapZoom = 15 } } } } </script>
第四步:執行效果 ,輸入框輸入地址,選擇搜尋的結果,獲得該地址的經緯度