Vue 异步调用百度地图
新建一个map.js
export function MP(ak) {
return new Promise(function(resolve, reject) {
window.onload = function() {
resolve(BMap)
}
if(!window.BMap){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://api.map.baidu.com/api?v=2.0&ak=" + ak + "&callback=init";
script.onerror = reject;
document.head.appendChild(script);
}
})
}
在你的百度地图页面中调用
import {
MP
} from '@/assets/map'
mounted: function() {
var that = this;
this.$nextTick(function() {
MP('ak') //ak改成你的ak
.then(BMap => {
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function(r) {
if (this.getStatus() == BMAP_STATUS_SUCCESS) {
var lon = r.point.lng
var lat = r.point.lat
var point = new BMap.Point(lon, lat);
// 根据坐标得到地址描述
var myGeo = new BMap.Geocoder();
myGeo.getLocation(point, function(result) {
var city = result.addressComponents.city;
var prov = result.addressComponents.province;
that.location = city
that.lng = lat + ',' + lon
that.prov = prov
if (city) {
that.location = city
} else {
that.location = '定位失败'
}
});
}
}, {
enableHighAccuracy: true
})
})
})
},
推荐一个百度地图的 插件 (vue-baidu-map)
https://github.com/Dafrok/vue-baidu-map
网友评论