【微信小程序】位置之重新授权

目前开发的小程序需要应用到一个获取经纬度的功能,授权的部分有点繁琐,记录一下。

1.使用 wx.getLocation()可以获取用户的位置信息,第一次会弹出微信原生的modal提问用户是否授权,之后不会再次弹出。第一次我的解决方案是,每次要定位之前getSetting,查看用户是否已授权。如果未授权执行openSetting引导用户开启授权。代码如下:

studentCheckIn: function () {
    console.log("执行签到程序");
    var student;

    var stuId = this.data.studentId;
    var courseId = this.data.courseId;
    var idKey = wx.getStorageSync('idKey');
    console.log('stuId', stuId, 'courseId', courseId, 'idKey', idKey);

    var long;
    var lati;

    wx.getSetting({
      success: function (res) {
        console.log('getSetting...', res)
        if (res.authSetting["scope.userLocation"] == true) {
          console.log("用户已开启定位授权");
        } else {
          wx.showModal({
            title: '位置信息授权',
            content: '位置授权暂未开启,无法完成签到',
            confirmText: '开启授权',
            confirmColor: '#345391',
            cancelText: '仍然拒绝',
            cancelColor: '#999999',
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  fail: function () {
                    console.log('openSetting.failed')
                  }
                })
              }
              if (res.cancel) {
                wx.showModal({
                  title: '签到失败',
                  content: '无法使用定位权限,签到失败',
                  confirmText: '太遗憾了',
                  confirmColor: '#345391',
                  showCancel: false
                })
              }
            }
          })
        }
      }
    })

    wx.getLocation({
      success: function (res) {
        console.log(res);
        long = res.longitude
        lati = res.latitude

        console.log("签到成功,等待服务器反馈")
        console.log('stuId', stuId, 'courseId', courseId, 'idKey', idKey, 'longitude', long, 'latitude', lati);
      },

      fail: function () {
        wx.showModal({
          title: '签到失败',
          content: '拒绝授权,获取位置信息失败',
          confirmText: '授权开启',
          cancelText: '我知道了',

        })
      }
    })

  },


2.上述办法有些繁琐,但是可以实现。也可以使用  wx.authorize(OBJECT)进行提前授权。

官方说明:↓
提前向用户发起授权请求。调用后会立刻弹窗询问用户是否同意授权小程序使用某项功能或获取用户的某些数据,但不会实际调用对应接口。如果用户之前已经同意授权,则不会出现弹窗,直接返回成功。

但是比较坑的是,wx.authorize(OBJECT)也只调用一次!!!!所以还是得调用openSetting引导用户开启授权。与上述方法相似,不再赘述。





你可能感兴趣的:(微信小程序开发)