实现原理和上一篇文章《微信小程序开发之获取当前位置所在的城市》一样,需要先申请一个AK成为开发者,然后通过接口返回经纬度来获取城市信息。
一、申请AK
进入控制台创建一个应用,申请一个基于浏览器端的AK。
二、引入百度地图SDK
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=填上你申请的AK"></script>
三、挂载百度地图实例
在html中增加一个id为allmap的标签,用来挂载百度地图实例。否则会报错,出现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获取当前位置的经纬度。
// 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("经度为:" + r.point.lat);
}
else {
alert('failed'+this.getStatus());
}
})
}
通过定位的API返回了经纬度以及省市,但是区域结果返回为空。因此需要通过逆地址服务API来解析。
// 这里演示拆分了 需要写在获取经纬度里面
var map = new BMap.Map("allmap");
// 通过经纬度得到城市信息
map.centerAndZoom(new BMap.Point(r.point.lng, r.point.lat), 11);
// 创建地理编码实例
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);
}
})