微信小程序获取地理位置,用户未开启手机定位时的解决方案

要点:获取地理位置时,如果获取地理位置失败,有两种情况:

1、用户未给微信授权地理位置信息

2、用户未给小程序授权地理位置信息

3、系统设置中-隐私选项地理位置未开启

在获取地理位置信息失败后,判断微信app是否有定位权限,如果没有则是第一种情况,则调用api打开微信应用权限设置即可;

判断用户是否有为小程序授权地理位置,如果未授权,则是第二种情况,打开地理位置授权即可;

但是进入了fail函数,并且已有微信和小程序的地理位置授权,说明是第三种情况,需要用户在系统设置中打开定位和授权。代码如下:

wx.getLocation({
      // type: 'gcj02',//默认wgs84
      success: function (location) {
        that.globalData.location = location;
        console.log(location);
        if(successCallback){
          successCallback(location);
        }
      },
      fail: function () {
        wx.hideLoading();
        // 获取app应用授权
        // locationAuthorized-允许微信使用定位的开关
        // locationReducedAccuracy-定位准确度。true 表示模糊定位,false 表示精确定位(仅 iOS 有效)
        const appAuth = wx.getAppAuthorizeSetting();

        if(!appAuth.locationAuthorized) {
          that.showModal({
            title: '',
            content: '请授权微信定位权限',
            confirmText: '确定',
            success: function (res) {
                if(res.confirm) {
                    wx.openAppAuthorizeSetting();
                }
            }
          })
          return
        }

        wx.getSetting({
          success: function (res) {
            if (!res.authSetting['scope.userLocation']) {
              that.showModal({
                title: '',
                content: '请允许****获取您的定位',
                confirmText: '授权',
                success: function (res) {
                  if (res.confirm) {

                    that.openSetting();
                  } else {
                    console.log('get location fail');
                  }
                }
              })
            }else {
              //用户已授权,但是获取地理位置失败,提示用户去系统设置中打开定位
              that.showModal({
                title: '',
                content: '请在系统设置中打开定位服务',
                confirmText: '确定',
                success: function (res) {
                }
              })
            }
          }
        })
      }
    })

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值