實現(xiàn)原理和上一篇文章《微信小程序開發(fā)之獲取當(dāng)前位置所在的城市》一樣恤批,需要先申請一個AK成為開發(fā)者府寒,然后通過接口返回經(jīng)緯度來獲取城市信息凤优。
一、申請AK
進(jìn)入控制臺創(chuàng)建一個應(yīng)用题涨,申請一個基于瀏覽器端的AK偎谁。
二总滩、引入百度地圖SDK
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=填上你申請的AK"></script>
三、掛載百度地圖實例
在html中增加一個id為allmap的標(biāo)簽巡雨,用來掛載百度地圖實例闰渔。否則會報錯,出現(xiàn)Can not read property 'gc' of undefined铐望。
<div id="wrapper">
<div id="allmap"></div>
<p v-if="cityInfo.province">{{cityInfo.province}},{{cityInfo.city}},{{cityInfo.district}}</p>
<p v-if="!cityInfo.province">定位中...</p>
</div>
四澜建、js
首先,通過定位的API獲取當(dāng)前位置的經(jīng)緯度蝌以。
// vue生命周期
created () {
var that = this;
var map = new BMap.Map("allmap");
var point = new BMap.Point(116.331398,39.897445);
map.centerAndZoom(point,12);
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function(r){
if(this.getStatus() == BMAP_STATUS_SUCCESS){
console.log(r);
console.log(r.address.province);
console.log(r.address.city);
console.log("緯度為:" + r.point.lng);
console.log("經(jīng)度為:" + r.point.lat);
}
else {
alert('failed'+this.getStatus());
}
})
}
通過定位的API返回了經(jīng)緯度以及省市炕舵,但是區(qū)域結(jié)果返回為空。因此需要通過逆地址服務(wù)API來解析跟畅。
// 這里演示拆分了 需要寫在獲取經(jīng)緯度里面
var map = new BMap.Map("allmap");
// 通過經(jīng)緯度得到城市信息
map.centerAndZoom(new BMap.Point(r.point.lng, r.point.lat), 11);
// 創(chuàng)建地理編碼實例
var myGeo = new BMap.Geocoder();
myGeo.getLocation(new BMap.Point(r.point.lng, r.point.lat), function(result){
if (result){
console.log(result);
console.log(result.address);
console.log(result.addressComponents.province);
console.log(result.addressComponents.city);
console.log(result.addressComponents.district);
that.cityInfo.province = result.addressComponents.province;
that.cityInfo.city = result.addressComponents.city;
that.cityInfo.district = result.addressComponents.district;
console.log(that.cityInfo);
}
})