微信小程序定位当前城市

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wy_Blog/article/details/80762810

定位获取当前所在城市

1、利用微信小程序接口 wx.getLocation() 获取当前经纬度。

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

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



Page({
  data: {
    city: ''
  },
  onLoad: function (options) {   
    this.loadInfo();  
  },
  loadInfo: 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)
      },
      fail: function () {
        // fail  
      },
      complete: function () {
        // complete  
      }
    })
  },

  loadCity: function (longitude, latitude) {
    var page = this
    wx.request({
      url: 'http://api.map.baidu.com/geocoder/v2/?ak=写自己的ak&location=' + latitude + ',' + longitude + '&output=json&pois=1',
      //这里的ak 是去百度地图api获取的需要自己登陆获取一下  地址:https://lbsyun.baidu.com/index.php?title=wxjsapi
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        // success  
        console.log(res);
        var city = res.data.result.addressComponent.city;

        console.log("城市为" + city)
        page.setData({ city: city });
      },
      fail: function () {
        // fail  
      },
      complete: function () {
        // complete  
      }
    })
  }
});

猜你喜欢

转载自blog.csdn.net/wy_Blog/article/details/80762810