运用百度api实现定位城市

1.在index.html中写

1
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=您的密钥"></script>

2.在lib里面封装一个getLocation.js

1
2
3
4
5
6
7
8
9
10
let getCurrentCityName = function() {
return new Promise(function(resolve, reject) {
let myCity = new BMap.LocalCity()
myCity.get(function(result) {
resolve(result.name)
})
})
}

export default getCurrentCityName

3.在你需要定位的文件里面写

1
2
3
4
5
mounted(){
getCurrentCityName().then((city)=>{
this.locations = city;
})
}

参考文档