微信小程序获取地理位置定位

需要在onLoad里面调用此方法

微信小程序地理定位

需要去百度地图api申请ak

 _getUserLocation() {
    var self = this
    wx.getSetting({
      success: (res) => {
        console.log('用户授权情况', res)
        //未授权
        if (res.authSetting['scope.userLocation'] !== undefined &&
          res.authSetting['scope.userLocation'] !== true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置,请确认授权',
            success: function (res) {
              console.log(res)
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) { //确认授权, 通过wx.openSetting发起授权请求
                wx.openSetting({
                  success: function (res) {
                    if (res.authSetting["scope.userLocation"] == true) {
                      wx.showModal({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      self._getCityLocation()
                    } else {
                      wx.showModal({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          self._getCityLocation()
          console.log('这个为undefined')
        } else {
          console.log('授权成功')
          self._getCityLocation()
        }
      }
    })
  },
  _getCityLocation() {
    let self = this
    wx.getLocation({
      type: 'wgx84',
      success: (res) => {
        console.log(res)
        let latitude = res.latitude
        let longitude = res.longitude
        let speed = res.speed
        wx.request({
          url: 'https://api.map.baidu.com/geocoder/v2/?ak=IQAk65u2Zswtl16q19AgzgY9krmSRt28&location=' + res.latitude + ',' + res.longitude + '&output=json',
          data: {},
          header: { 'Content-type': 'application/json' },
          success: function (ops) {
            console.log(ops)
            var weizhi = ops.data.result.addressComponent.city
            self.setData({
              weizhi:weizhi
            })
          },
          fail: function (resq) {
            wx.showModal({
              title: '信息提示',
              content: '请求失败',
              showCancel: false,
              confirmColor: '#f37938'
            });
          }
        })
      },
      fail: (res) => {
        wx.showModal({
          title: '信息提示',
          content: '请求失败',
          showCancel: false,
          comfirmColor: '#f37938'
        })
      }
    })

 },
发布了12 篇原创文章 · 获赞 1 · 访问量 205

猜你喜欢

转载自blog.csdn.net/ws072488/article/details/103241457
今日推荐