注意:直接引入script的话,可能会报错:Bmap is not defined
解决方案:
第一步:新建一个map.js
export function MP(ak) {
return new Promise(function (resolve, reject) {
window.onload = function () {
resolve(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);
})
}
第二步:在你的百度地图页面中调用(ak 就是你的密钥)
import {MP} from './map.js'
mounted(){
this.$nextTick(function(){
var _this = this;
MP(_this.ak).then(BMap => {
//在此调用api
_this.getMyLocation();
})
})
}
第三步:调用百度api去获取地理信息
getMyLocation(){
var that=this;
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition((r) => {
that.latitude = r.latitude;
that.longitude = r.longitude;
that.getActStoreAreaList();
}, { enableHighAccuracy: true })
},