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();
}

猜你喜欢

转载自blog.csdn.net/weixin_43837268/article/details/84634291