微信小程序定位当前城市

定位获取当前所在城市

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  
      }
    })
  }
});

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值