该功能只需要获取经纬度(别忘了npm百度插件)
首先需要一个js,这边我定义为map.js
在你需要的页面import
在created里加载
获取经纬度代码
map.js
export function loadBMap(funcName) {
var script = document.createElement("script");
script.src = "http://api.map.baidu.com/api?v=2.0&ak=你的秘钥&callback=" + funcName;
document.body.appendChild(script);
}
import { loadBMap } from "./../../../static/js/map";
created() {
window.initBaiduMapScript = () => {
// console.log(BMap);
this.getlocation();
};
loadBMap("initBaiduMapScript");
},
// 获取经纬度
getlocation() {
const that = this;
this.$nextTick(function() {
try {
const geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function(r) {
// console.log(r);
this.lat = r.latitude;
this.lng = r.longitude;
this.city = r.address.city;
localStorage.setItem("lat", r.latitude);
localStorage.setItem("lng", r.longitude);
localStorage.setItem("city", r.address.city);
if (this.getStatus() == BMAP_STATUS_SUCCESS) {
const { lat = null, lng = null } = r.point;
}
});
} catch (e) {
console.log(e);
}
});
}