更好的小程序内“位置获取方案”

以下代码可实现小程序内位置获取方案

粘贴即可使用,需要用到的地方导入调用就行了。

代码拆分为两个模块:

  1. getAuth_userLocation:判断是否授权(若无则拉起位置授权);
  2. getUserLocation:获取位置信息(返回经纬度信息);

优势在于代码功能清晰独立,比现有方案耦合度更低灵活性更强

// 判断是否受授权位置信息,未授权则引导授权并返回授权结果(true/false)
export function getAuth_userLocation(){
  return new Promise((resolve,reject)=>{
    wx.getSetting({
      success (res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success (res) {
              resolve(true)
              return
            },
            fail(err){
              console.log('拒绝位置授权',err);
              wx.showModal({
                title: '提示',
                content: '需授权您的位置信息,才能继续使用小程序',
                // showCancel:false,
                confirmText:'去授权',
                complete: (res) => {
                  if (res.cancel) {
                    resolve(false)
                  }
                  if (res.confirm) {
                    wx.openSetting({
                      success(res){
                        if (res.authSetting['scope.userLocation']) {
                          resolve(true)
                        }else{
                          resolve(false)
                        }
                      },
                      fail(res){
                        resolve(false)
                      }
                    })
                  }
                }
              })
            }
          })
        }else{
          resolve(true)
        }
      }
    })
  })
}
// 获取用户位置(经纬度)
export function getUserLocation(){
  return new Promise((resolve,reject)=>{
    wx.getLocation({
      success(res){
        console.log(res);
        resolve(res)
      },
       fail: async(err)=>{
         console.log('位置获取失败',err);
        let authRes = await getAuth_userLocation()
        console.log('authRes',authRes);
        if (authRes === true) {
         let res2 =  await getUserLocation()
         resolve(res2)
        }else{
          resolve(false)
          console.log('用户拒绝授权');
          // // 开启以下代码实现循环授权,直到拿到位置为止(不建议,太流氓了~~)
          // let res3 = await getUserLocation()
          // resolve(res3)
        }
      }
    }) 
  })
}

别忘了在app.json里配置以下代码,否则api无权调用,会报错。

"permission": {
	"scope.userLocation": {
      "desc": "您的位置信息将用于定位" 
    }
 },
 "requiredPrivateInfos":[
    "getLocation"
 ]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值