<p>本篇文章主要讲解在微信小程序中,如何利用微信自带的api(wx.getLocation())结合百度地图的逆地址解析api来获取当前所在城市名。</p><p>实现起来也比较简单,步骤为:</p><p>1--利用微信小程序接口 wx.getLocation() 获取当前经纬度。使用简单,具体可以参照微信小程序api。</p><p>https://mp.weixin.qq.com/debug/wxadoc/dev/api/location.html#wxopenlocationobject</p><p>2--拿到经纬度之后,通过微信的wx.request()方法请求百度地图的解析接口,传入我们获取到的经纬度,拿到当前定位的城市。</p><p>接口为:</p><p>url: &#39;https://api.map.baidu.com/geocoder/v2/?ak=您的ak&amp;location=&#39; + latitude + &#39;,&#39; + longitude + &#39;&amp;output=json&#39;</p><p>ak需要在百度地图api官网去注册,然后创建一个应用,如此便可拿到您的ak。</p><p>index.js代码如下:</p><pre class="brush:js;toolbar:false">Page({ data:{ currentCity:&#39;&#39; }, onLoad:function(options){ this.getLocation(); }, getLocation:function(){ varpage=this wx.getLocation({ type:&#39;wgs84&#39;,//默认为wgs84返回gps坐标,gcj02返回可用于wx.openLocation的坐标 success:function(res){ //success varlongitude=res.longitude varlatitude=res.latitude page.loadCity(longitude,latitude) } }) }, loadCity:function(longitude,latitude){ varpage=this wx.request({ url:&#39;https://api.map.baidu.com/geocoder/v2/?ak=您的ak&amp;location=&#39;+latitude+&#39;,&#39;+longitude+&#39;&amp;output=json&#39;, data:{}, header:{ &#39;Content-Type&#39;:&#39;application/json&#39; }, success:function(res){ //success console.log(res); varcity=res.data.result.addressComponent.city; page.setData({currentCity:city}); }, fail:function(){ page.setData({currentCity:&quot;获取定位失败&quot;}); }, }) } })</pre><p>loadCity()方法中,获取到信息之后打印出来,拿到的信息是非常详细的,如下图:</p><p><img src="/up_pic/201906/171032204874.png" title="171032204874.png" alt="1.png"/></p><p>我们这里需要的是当前的city,即:res.data.result.addressComponent.city。如果项目中有需要更加丰富的信息,也可使用此方法,比较简便。</p><p>index.wxml代码如下:</p><p>&lt;!--index.wxml--&gt;</p><p>&lt;view class=&quot;container&quot;&gt;</p><p>当前城市为:{{currentCity}}</p><p>&lt;/view&gt;</p><p>效果如下:</p><p><img src="/up_pic/201906/171031487076.png" title="171031487076.png" alt="2.png"/></p>
返回顶部 留言