1.获取百度的ak(由于谷歌对高德地图的限制,所以采用了百度地图)
将获取到的ak放到这里
//这一串代码放到index.html中
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你的ak"></script>
2.在vue.config中配置百度地图相关的
configureWebpack: {
externals: {
'BMap': 'BMap' // 百度地图配置
}
}
3:在你所需要的页面中获取数据即可(这一种方法有延迟)
method:{
getCity() {
const getLocation = new BMap.Geolocation();
getLocation.getCurrentPosition(
(position) => {
// position中存放所有的定位数据
// console.log(position);
// 这里获取的是城市和省
let city = position.address.city;
this.city=city
},
() => {
console.log('定位失败')
},
{ provider: "baidu" }
);
},
}
4:单独创建一个js文件(没有延迟)
4-1:在util文件中创建location.js文件
// 获取当前省份
const getProvince = function() {
return new Promise((resolve, reject) => {
let myCity = new BMap.LocalCity();
myCity.get((result) => {
let geoc = new BMap.Geocoder();
geoc.getLocation(result.center, (res) => {
console.log(res)
// rs 中携带着所有的定位信息,这里只获取了城市(city)和所在的区(district)
let addComp = res.addressComponents;
let result = addComp.province;
resolve(result);
});
}, {enableHighAccuracy: true});
});
}
export default getProvince ;
4-2:在需要的页面引入
import getProvince from "@/util/location"
mounted(){
this.getCity()
},
method:{
getCity() {
getProvince().then(res=>{
this.placeholder=res
})
},
}