1.首先要在百度地图官网(http://lbsyun.baidu.com/)上面新建实例,获取百度地图的密钥:ak
第一种方法在index.html页面引入百度地图的js
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=你的密钥"></script>
3.在你的项目webpack.base.conf.js文件里面加上下面这句:
4.在需要的页面使用的页面直接引入:
import BMap from "BMap";
// 获取当前定位
getCurrentCity() {
let geolocation = new BMap.Geolocation(); // 创建百度地理位置实例
geolocation.getCurrentPosition(function (e) {
if (this.getStatus() == BMAP_STATUS_SUCCESS) {
// 百度 geolocation 的经纬度属性不同,此处是 point.lat 而不是 coords.latitude
let point = new BMap.Point(e.point.lng, e.point.lat);
let gc = new BMap.Geocoder();
gc.getLocation(point, function (rs) {
let currentPosition = rs.point;
let addComp = rs.addressComponents; // 返回的结果
let address = addComp.city; // 拼接地址
});
} else {
console.log(this.getStatus());
}
});
},
5.注意,如果你的vue页面需要使用webview内嵌在微信小程序里面的话,会出现在ios里面不能使用的情况。
引入地图js的方法二:
单页面引入js,不全局使用。这时候我们可以动态创建一个js标签,引入到要使用的页面:
新建一个map.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);
});
}
}
在使用的页面引入:
import map from 'common/js/map.js'
//使用时:map.init().then(()=>{})
getCurrentCity() {
map.init().then(()=>{
let _this = this;
let geolocation = new BMap.Geolocation(); // 创建百度地理位置实例,代替 navigator.geolocation
geolocation.getCurrentPosition(function (e) {
if (this.getStatus() == BMAP_STATUS_SUCCESS) {
// 百度 geolocation 的经纬度属性不同,此处是 point.lat 而不是 coords.latitude
let point = new BMap.Point(e.point.lng, e.point.lat);
let gc = new BMap.Geocoder();
gc.getLocation(point, function (rs) {
let currentPosition = rs.point;
let addComp = rs.addressComponents;
});
} else {
console.log(this.getStatus());
}
});
})
},