微信小程序地理位置受权

文档

代码

wx.getSetting({
      success(res) {
        console.log('wx.getSetting:', res)
        /** 
         * res.authSetting['scope.userLocation'] === true         赞成过受权
         * res.authSetting['scope.userLocation'] === false        拒绝过受权
         * res.authSetting['scope.userLocation'] === undefined    从未赞成或者拒绝过受权
        */
        if (res.authSetting['scope.userLocation'] === undefined) {
          wx.authorize({
            scope: 'scope.userLocation',
            success (res) {
              console.log('authorize success:', res)
            },
          })
        }else if (res.authSetting['scope.userLocation'] === false) {
          wx.showModal({
            title: '',
            content: '去小程序设置页面设置balabala',
            showCancel: true,
            cancelText: '取消',
            cancelColor: '#000000',
            confirmText: '肯定',
            confirmColor: '#3CC51F',
            success: (result) => {
              if(result.confirm){
                wx.openSetting({
                  success (res) {
                    console.log('wx.openSetting success:', res.authSetting)
                  },
                  fail: (err)=>{
                    console.log('wx.openSetting fail:', err)
                  },
                  complete: (info)=>{
                    console.log('wx.openSetting complete:', info)
                  },
                })
              }
            },
          })
        } else {
          wx.getLocation({
            type: 'wgs84',
            success (res) {
              console.log('wx.location success:', res)
            },
            fail (err) {
              console.log('wx.location fail:', err)
            },
            complete(aa) {
              console.log('wx.location complete:', aa)
            },
          })
        }
      },
    })

效果图

受权弹窗
image.png
去设置弹窗
image.png
image.pnghtml

注意事项

一、wx.openSettingjson

- 3.0 版本开始,用户发生点击行为后,才能够跳转打开设置页,管理受权信息
- 真机调试才能打开设置页面
- 只会显示小程序已经向用户申请过的权限

二、wx.getSetting小程序

返回值中只会出现小程序已经向用户申请过的权限

三、app.json文件中配置位置信息的用途说明微信小程序

"permission": {
  "scope.userLocation": {
    "desc": "您的位置信息将用于定位"
  }
}

四、弹窗出现机制api

- 一旦用户选择了拒绝或者容许该权限,那么受权关系就会被记录在后台,直到用户主动删除小程序,以后再次调用该API时都不会再弹出权限申请框。
- 解决方式:对于用户拒绝受权的状况调用wx.openSetting跳转小程序设置页面,引导用户手动开启该权限
相关文章
相关标签/搜索