### [小程序获取用户位置授权的完美讲述](https://www.prosaas.cn/article/16539) **Published:** 2020-09-10T09:17:09 **Author:** 5201314 **Excerpt:** 相关学习推荐:微信小程序教程前言小程序在开发过程中很多地方需要用户的授权,需要查询用户是否授权,没有授权引导用… ## ![](https://img.php.cn/upload/article/000/000/052/5f59eeb68b903720.jpg) > 相关学习推荐:微信小程序教程 ## 前言 小程序在开发过程中很多地方需要用户的授权,需要查询用户是否授权,没有授权引导用户去授权。所以我就把这个流程做了下封装,小可爱们可以参考一下,多多提意见一起进步。 ## 流程图 有时候项目的很多地方都会用到判断用户是否授权的逻辑,所以封装是非常有必要的。下面我们拿位置授权作为例子说一下一般的流程。 很多应用在一进入就会让用户授权地理位置,可以拿到用户的经纬度通过计算获取距离用户的距离。下面是一个简单的流程图。 ![](https://img.php.cn/upload/article/000/000/052/b3175da3c2c27716cdf863c085366bda-0.png) 开发先要通过`wx.getSettiing()`获取用户的当前设置,官方文档。如果拥有权限进行下一步操作,如果没有再次请求用户打开权限,如果点击用户点击否,授权失败。如果用户同意,调用`wx.openSetting()`调起客户端小程序设置界面,返回用户设置的操作结果,官方文档。打开设置页面后如果用户没有打开授权就返回了,会拿到授权失败的结果。如果打开了授权返回之前的页面就授权成功了。 这边要注意一点 获取地理授权 要在 app.json 添加下面代码。 "permission": {     "scope.userLocation": {       "desc": "您的位置信息将用于展示您所在城市的信息"     }   }复制代码 ##  主要代码 在utils文件夹下新建 auth.js 用于授权操作,然后在代码中就可以直接2行搞定拉! /\*\* \* 微信授权 \*/ const authList = {  userInfo: {    apiName: \['getUserInfo'\],    authTitle: '需要使用你的用户信息',    authContent: '需要使用你的用户信息,请确认授权'  },  userLocation: {    apiName: \['getLocation', 'chooseLocation'\],    authTitle: '请求授权当前位置',    authContent: '需要获取您的地理位置,请确认授权'  },  address: {    apiName: \['chooseAddress'\],    authTitle: '需要使用你的通讯地址',    authContent: '需要使用你的通讯地址,请确认授权'  },  invoiceTitle: {    apiName: \['chooseInvoiceTitle'\],    authTitle: '需要使用你的发票抬头',    authContent: '需要使用你的发票抬头,请确认授权'  },  invoice: {    apiName: \['chooseInvoice'\],    authTitle: '需要获取你的发票',    authContent: '需要获取你的发票,请确认授权'  },  werun: {    apiName: \['getWeRunData'\],    authTitle: '需要获取你的微信运动数据',    authContent: '需要获取你的微信运动数据,请确认授权'  },  writePhotosAlbum: {    apiName: \['saveImageToPhotosAlbum', 'saveVideoToPhotosAlbum'\],    authTitle: '请求授权相册',    authContent: '需要使用你的相册,请确认授权'  }, } /\*\* \* @description: 返回值中只会出现小程序已经向用户请求过的权限 \* @param {String} 权限名称 \* @return {Boolean} 是有拥有权限 \*/ const getWxSetting = key => {  if (typeof key === 'string' && !authList\[key\]) return false  return new Promise(function (resolve) {    wx.getSetting({      success: async res => {        var result = res.authSetting        // 用户拒绝过        if (result\[\`scope.${key}\`\] === false) {          // 引导去授权页          \_showModal(key).then(() => {            resolve()          })        } else {          //  已授权,或者还未授权          resolve()        }      }    })  }) } /\*\* \* @description: 引导去授权设置页面 \* @param {String} 权限名称 \* @return {Boolean} 是有拥有权限 \*/ const \_showModal = key => {  console.log(authList\[key\].authContent)  return new Promise(function (resolve) {    wx.showModal({      title: authList\[key\].authTitle,      content: authList\[key\].authContent,      success: function (res) {        if (res.confirm) {          wx.openSetting({            success: async dataAu => {              // 异步,进入授权页面授权后返回判断              if (dataAu.authSetting\[\`scope.${key}\`\] === true) {                wx.showToast({                  title: '授权成功',                  icon: 'success',                  duration: 1000                })                resolve()              } else {                wx.showToast({                  title: '授权失败',                  icon: 'none',                  duration: 1000                })              }            }          })          // 用户点击取消        } else if (res.cancel) {          wx.showToast({            title: '授权失败',            icon: 'none',            duration: 1000          })        }      }    })  }) } module.exports = {  getWxSetting }复制代码 页面js引入auth.js 传入,调用 getWxSetting 方法传入已经在auth.js中定义authList 对应的属性名 //index.js //获取应用实例 const app = getApp() const wxApi = require('../../utils/auth.js') Page({   data: {   },   // 打开地图   openMap: function() {     wxApi.getWxSetting('userLocation').then(()=>{         // 已经授权或还未授权,下面的代码也可以根据需求提取到公共文件中       wx.getLocation({         type: 'wgs84',         success: res => {           wx.openLocation({             latitude: res.latitude,             longitude: res.longitude,           })         },         fail: err => {           wx.showToast({             title: '检查手机定位权限',             icon: 'none',             duration: 2000           })         }       })     })   },   // 保存到相册   writePhotosAlbum: function() {     wxApi.getWxSetting('writePhotosAlbum').then(()=>{      // 已经授权或还未授权,下面的代码也可以根据需求提取到公共文件中       wx.downloadFile({         url: 'https://imgs.solui.cn/avatar.png',         success: function(res) {             wx.saveImageToPhotosAlbum({                 filePath: res.tempFilePath,                 success: function(res) {                    wx.showToast({                      title: '保存成功',                      icon:'none'                    })                 },                 fail: function(err) {                   wx.showToast({                     title: '保存失败',                     icon:'none'                   })                 }             })         }       })     })   },   onLoad: function () {   }, })复制代码 然后就可以进行授权后的操作了,这里的  wx.getLocation 也可以提取公共文件,这里就不再赘述了。 > 想了解更多编程学习,敬请关注php培训栏目! 以上就是小程序获取用户位置授权的完美讲述的详细内容,更多请关注知企PROSAAS其它相关文章! **Tags:** JS, json, php, 封装, 微信小程序 **Categories:** 后端开发 ---