微信小程序用户拒绝微信授权后提示用户打开位置权限(判断当前位置是否在限制区域中)

在这里插入图片描述
1.在common文件夹中创建index.js文件

const amap = require('../common/amap-wx.130.js'); //引入高德微信小程序版sdk


function timeExChange(time) {
  // 时间戳 
  let timestamp = time
  let date = new Date(parseInt(timestamp) * 1000);
  let Year = date.getFullYear();
  let Moth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
  let Day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
  let Hour = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
  let Minute = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
  let Sechond = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
  let GMT = Year + '-' + Moth + '-' + Day + '   ' + Hour + ':' + Minute + ':' + Sechond;

  return GMT
}
// 获取uuid的方法,放在util里 生成不同地址
function uuid() {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4";
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
  s[8] = s[13] = s[18] = s[23] = "-";
  var uuid = s.join("");
  return uuid
}
// 检测网络
function startMonitoringNetwork() {
  wx.onNetworkStatusChange((res) => {
    switch (res.networkType) {
      case 'none':
        wx.showToast({
          title: '当前无网络,请检查您的网络连接',
          icon: 'none',
          duration: 2000,
        });
        break;
      case '2g':
      case '3g':
      case '4g':
      case '5g':
        // 可以添加相应的处理逻辑
        break;
      case 'wifi':
        // 可以添加相应的处理逻辑
        break;
      default:
        break;
    }
    // console.log('当前网络---', res.networkType);
    if (res.networkType !== 'none') {
      // socketInit(); // 调用 WebSocket 初始化函数
    }
  });
}
// 复制粘贴
function copyText(e) {
  let key = e.currentTarget.dataset.key;
  wx.setClipboardData({ //设置系统剪贴板的内容
    data: key,
    success(res) {
      wx.getClipboardData({ // 获取系统剪贴板的内容
        success(res) {
          wx.showToast({
            title: '复制成功',
            icon: "none"
          })
        }
      })
    }
  })
}
let amapPlugin = null;
let key = "高德sdk";
const provinces = ["四川省", "重庆市", "云南省", "西藏自治区"];
amapPlugin = new amap.AMapWX({
  key: key
})
// 使用高德地图获取当前定位
function getRegeo() {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '获取信息中'
    });
    amapPlugin.getRegeo({
      success: (data) => {
        console.log(data, '当前定位')
        let province = data[0].regeocodeData.addressComponent.province;
        if (provinces.indexOf(province) !== -1) {
          console.log("四川省在数组中");
          resolve(true); // 异步操作成功,将 true 作为 Promise 的结果
        } else {
          console.log("四川省不在数组中");
          resolve(false); // 异步操作成功,将 false 作为 Promise 的结果
        }
        wx.hideLoading();
      },
      fail: (err) => {
        wx.hideLoading();
        console.log(err);
        showRefuseLocationPermission();
        reject(err); // 异步操作失败,将错误信息传递给 reject
      }
    });
  });
}
// 获取位置权限
function getLocationDetail() {
  let that = this
  return new Promise((resolve, reject) => {
    // 请求用户授权,第一次进入会有位置授权的提示
    wx.authorize({
      scope: 'scope.userLocation',
      success() {
        console.log("用户成功授权位置信息")
        //  that.getUserLocation()
        getRegeo();
      },
      fail() {
        console.log("用户拒绝授权位置信息,再次提示用户授权")
        showRefuseLocationPermission()
      }
    })
  })
}
// 用户拒绝授权的展示
function showRefuseLocationPermission() {
  const that = this;
  wx.showModal({
    title: "提示",
    content: "需要获取用户位置权限",
    confirmText: "前往设置",
    showCancel: false,
    success(res) {
      if (res.confirm) {
        wx.openSetting({
          success: (res) => {
            console.log("打开设置成功", res);
            if (res.authSetting['scope.userLocation']) {
              console.log('成功授权userLocation')
              getRegeo();
            } else {
              console.log('用户未授权userLocation')
              // 递归调用本函数,(函数套函数)
              getLocationDetail()
            }
          },
          fail: (err) => {
            console.log("打开设置失败", err)
          }
        })
      }
    }
  })
}
// 深拷贝
function deepClone(obj) {
  if (typeof obj !== 'object' || obj === null) {
    return obj; // 如果不是对象类型,直接返回
  }
  let clone;
  if (Array.isArray(obj)) {
    clone = obj.map(item => deepClone(item)); // 对数组进行深度克隆
    clone = clone.filter(item => item !== undefined); // 过滤数组中的 undefined 元素
  } else {
    clone = {};
    for (let key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        clone[key] = deepClone(obj[key]); // 递归复制对象的每个属性
      }
    }
  }
  return clone;
}
// 此处要使用微信小程序的模板导出,es6导出会报错
module.exports = {
  timeExChange: timeExChange,
  copyText: copyText,
  getRegeo: getRegeo,
  uuid: uuid,
  deepClone: deepClone,
  showRefuseLocationPermission: showRefuseLocationPermission,
  getLocationDetail:getLocationDetail
};

2.app.js中引入

// app.js
// 导入模块和函数
import { getRegeo } from './common/index.js';
App({
  onLaunch() {
    this.quyu(); // 执行区域判断函数
  },
  globalData: {
    isregion: null, // 判断当前位置是否在限制区域内
  },
  // 判断当前位置是否在限制区域内,并触发 isregion 更新事件
  quyu() {
    getRegeo().then(result => {
      this.globalData.isregion = result;
      this.globalData.eventBus.trigger('isregionUpdated', result);
      // console.log("getRegeo 结果:", result);
    }).catch(err => {
      console.error("getRegeo 出错:", err);
    });
  }
});

3.在app.json中加入

  "requiredPrivateInfos": [
    "getLocation",
    "chooseLocation"
  ],
 "permission": {
    "scope.userLocation": {
      "desc": "获取用户位置信息"
    }
  }

注意:该功能中定位我用的高德地图定位获取具体的省市区,如果有需要的小伙伴可参考高德地图sdk引用

  • 15
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值