實現思想:通過定位獲取到當前所在城市名;
1、在工程目錄index.html中引入:
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=您的密鑰"></script>
ps:秘鑰可以去百度開發者平台申請
2、在build/webpack.base.conf.js(與entry同級)中配置:
entry:{
app:'./src/main.js'
},
externals:{
"BMap":“BMap”
},
3、重新運行一下npm install或者yarn;
4、配置好以后到對應需要獲取城市名的頁面引入百度地圖對象 BMap:
import BMap from 'BMap'
5、獲取城市:
html部分
<div>{{LocationCity}}</div> <!-- 渲染層 -->
js部分
export default{
data(){
return{
LocationCity:"正在定位" //給渲染層定義一個初始值
}
},
mounted(){
this.city() //觸發獲取城市方法
},
methods:{
city(){ //定義獲取城市方法
const geolocation = new BMap.Geolocation();
var _this = this
geolocation.getCurrentPosition(function getinfo(position){
let city = position.address.city; //獲取城市信息
let province = position.address.province; //獲取省份信息
_this.LocationCity = city
}, function(e) {
_this.LocationCity = "定位失敗"
}, {provider: 'baidu'});
}
}
}
以上便是獲取當前城市的代碼,如果存在問題,希望各位光頭,哦不,是各位程序猿朋友提出,我會依據自己能力,給予大家幫助,同時優化代碼。
