微信小程序-用户地理位置授权以及获取用户位置信息


微信小程序有个bug,一旦用户拒绝获取地理位置信息后,重新进入小程序不会再弹出提示框获取用户信息,只有在设置里面允许获取地理位置信息

onLoad: function () {
    var that = this
    wx.getSetting({
      success: (res) => {
        // res.authSetting['scope.userLocation']  undefined-表示初始化进入该页面 false-表示非初始化进入该页面,且未授权
        if (res.authSetting['scope.userLocation'] != true) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              that.getLocation()
            },
            fail: function(error) {
              wx.showModal({
                title: '提示',
                content: '您未开启保定位权限,请点击确定去开启权限!',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting()
                  }
                },
                fail: function() {
                  wx.showToast({
                    title: '未获取定位权限,请重新打开设置',
                    icon: 'none',
                    duration: 2000 
                  })
              })
            }
          })
        }else {
          that.getLocation()
        }
      }
    })
  },
  getLocation: function(){
    const that = this
    var i = setInterval(function() {
      wx.getLocation({
        type: 'gcj02', // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标  
        success: function(res) {
          that.setData({
            latitude: res.latitude,
            longitude: res.longitude,
          })            
          var longitude = res.longitude
          var latitude = res.latitude
          that.loadCity(longitude, latitude)
          clearInterval(i)
        },
        fail: function() {
          wx.showToast({
            title: '手机定位未打开',
            icon: 'none',
            duration: 2000 
          })
        },
        complete: function() {
          // complete  
        }
      })
    }, 2000)
  },
  loadCity: function(longitude, latitude) {
    var that = this
    //请求的地址是腾讯地图,参考文档https://lbs.qq.com/service/webService/webServiceGuide/webServiceOverview
    wx.request({
      url:'https://apis.map.qq.com/ws/geocoder/v1/?location='+latitude + ','+longitude +'&key=SSSBZ-SQZK6-U3XSL-EPA5P-6VNK6-ANF4P&get_poi=1',
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        const data = res.data
        app.globalData.location = data.result.address_component
        var location = data.result.address
        that.setData({
          location: location
        });
      },
      fail: function() {  
        console.log("失败")
      },
      complete: function() {
        // complete  
      }
    })
  }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM