赞
踩
先写入BMap,再npm install–这个配置说明可百度–这里顺便提一下,不是很详细
1:index.html 中引入js(百度的密匙自己百度一下,申请就好了)
http://api.map.baidu.com/api?v=2.0&ak=你的密匙"
2:新建一个js文件–地图专用
export default {
init: function (){
const AK = ‘你的密匙’;
const BMap_URL = 'https://api.map.baidu.com/api?v=2.0&ak=’+ AK +"&s=1&callback=onBMapCallback";
return new Promise((resolve, reject) => {
// 如果已加载直接返回
if(typeof BMap !== “undefined”) {
resolve(BMap);
return true;
}
// 百度地图异步加载回调处理
window.onBMapCallback = function () {
resolve(BMap);
};
let getCurrentCityName = function () {
return new Promise(function (resolve, reject) {
let myCity = new BMap.LocalCity()
myCity.get(function (result) {
resolve(result.name)
})
})
}
// 插入script脚本
let scriptNode = document.createElement(“script”);
scriptNode.setAttribute(“type”, “text/javascript”);
scriptNode.setAttribute(“src”, BMap_URL);
document.body.appendChild(scriptNode);
});
}
}
3:需要用的组件里开始引用和调用
写在方法里,在mounted里调用–下面代码不可少
city(){
map.init().then(BMap =>{
const locationCity = new BMap.Geolocation();
var that = this;
locationCity.getCurrentPosition(
function getinfo(options){
let city = options.address.city; //此处拿到位置相关信息
that.LocationCity = city;
console.log(options)
},
function (e){
that.LocationCity = '定位失败';
console.log('定位失败')
},
{provider: 'baidu'}
)
})
},
只需三步就行,看了好多例子都是有问题,这个很实用,欢迎留言,多多交流
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。