微信小程序获取当前所在城市

来源:互联网 发布:php base64解码乱码 编辑:程序博客网 时间:2024/06/04 19:24

本篇文章主要讲解在微信小程序中,如何利用微信自带的api(wx.getLocation())结合百度地图的逆地址解析api来获取当前所在城市名。

实现起来也比较简单,步骤为:

1--利用微信小程序接口 wx.getLocation() 获取当前经纬度。使用简单,具体可以参照微信小程序api。

https://mp.weixin.qq.com/debug/wxadoc/dev/api/location.html#wxopenlocationobject

2--拿到经纬度之后,通过微信的wx.request()方法请求百度地图的解析接口,传入我们获取到的经纬度,拿到当前定位的城市。

接口为:

url: 'https://api.map.baidu.com/geocoder/v2/?ak=您的ak&location=' + latitude + ',' + longitude + '&output=json'
ak需要在百度地图api官网去注册,然后创建一个应用,如此便可拿到您的ak。


index.js代码如下:

Page({  data: {    currentCity: ''  },  onLoad: function (options) {    this.getLocation();  },  getLocation: function () {    var page = this    wx.getLocation({      type: 'wgs84',   //默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标       success: function (res) {        // success          var longitude = res.longitude        var latitude = res.latitude        page.loadCity(longitude, latitude)      }    })  },  loadCity: function (longitude, latitude) {    var page = this    wx.request({      url: 'https://api.map.baidu.com/geocoder/v2/?ak=您的ak&location=' + latitude + ',' + longitude + '&output=json',      data: {},      header: {        'Content-Type': 'application/json'      },      success: function (res) {        // success          console.log(res);        var city = res.data.result.addressComponent.city;        page.setData({ currentCity: city });      },      fail: function () {        page.setData({ currentCity: "获取定位失败" });      },          })  }})  


loadCity()方法中,获取到信息之后打印出来,拿到的信息是非常详细的,如下图:


我们这里需要的是当前的city,即:res.data.result.addressComponent.city。如果项目中有需要更加丰富的信息,也可使用此方法,比较简便。


index.wxml代码如下:

<!--index.wxml-->  <view class="container">  当前城市为:{{currentCity}}  </view>  

效果如下:






文章参考来自:http://blog.csdn.net/tammy1151/article/details/56494776


阅读全文
0 0
原创粉丝点击