1. 程式人生 > >Vue專案通過百度地圖獲取地理定位

Vue專案通過百度地圖獲取地理定位

Vue 專案中使用百度地圖
一.寫在前面的話,在vue專案中使用H5新特性在IOS手機上開啟vue網頁會有適應性問題,並且無法獲取所在城市,因此使用第三方庫百度地圖api
二.使用步驟
1.獲取百度地圖金鑰
(1).註冊百度開發者帳戶 http://lbsyun.baidu.com/
(2).建立網站為網站申請百度地址訪問金鑰 AccessKey
2.實現百度地圖定位
(1).在vue專案中index.html中引入 百度地圖api

(2).在build/webpack.base.conf.js裡面 配置
module.exports = {
context: path.resolve(__dirname, ‘…/’),
entry: {
app: ‘./src/main.js’
},
//新增
externals: {
“BMap”: “BMap”
},
}
(3).定義方法,並在mounted中進行引用
//引入BMap
import BMap from ‘BMap’
//定義資料
data() {
location: null
},
methods:{
//定義方法
getCity(){
let _this = this
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function® {
if (this.getStatus() == BMAP_STATUS_SUCCESS) {
if(r.accuracy==null){
alert(‘您已拒絕地理位置授權’);
//使用者決絕地理位置授權
return;
}else{
const myGeo = new BMap.Geocoder()
myGeo.getLocation(new BMap.Point(r.point.lng, r.point.lat), data => {
if (data.addressComponents) {
const result = data.addressComponents
const location = {
creditLongitude: r.point.lat, // 經度
creditLatitude: r.point.lng, // 緯度
creditProvince: result.province || ‘’, // 省
creditCity: result.city || ‘’, // 市
creditArea: result.district || ‘’, // 區
creditStreet: (result.street || ‘’) + (result.streetNumber || ‘’) // 街道
}
_this.location = location;
_this.creditLongitude=location.creditLongitude;
_this.creditLatitude=location.creditLatitude;
_this.creditCity=location.creditCity;
// alert(this.getStatus());
}
})
}
}
})
},
}
//mounted中引用
mounted() {
this.getCity();
}