Vue中使用百度API获取地理位置
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);
})
}
- 在VUE中调用,测试环境是将以下代码放在了mounted()中
if(sessionStorage.getItem("address")!=null){
this.address=sessionStorage.getItem("address");
console.log("address",this.address);
}
else{
this.$nextTick(()=>{
var that=this;
MP(that.ak).then(BMap=>{
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function getinfo(position){
var city = position.address.city;
var province = position.address.province;
that.address=province+city
console.log(that.address);
sessionStorage.setItem("address",that.address);
}, function(e) {
alert("获取百度定位位置信息失败");
}, {provider: 'baidu'});
})
})
}
|