开启手机的定位服务-验证
uni.getSystemInfo({
success(systemRes) {
if (!systemRes.locationEnabled) {
throw("手机定位未开启,请开启后重试");
}
}
});
设置微信应用的定位权限-验证
uni.getSystemInfo({
success(systemRes) {
if (!systemRes.locationAuthorized) {
throw("微信定位权限被禁用,请开启后重试");
}
}
});
设置小程序应用的定位权限-验证
uni.getSetting({
success(res) {
if (!res.authSetting['scope.userLocation']) {
throw("用户未授权当前微信小程序应用的位置服务");
}
}
});
统一验证
因为三重验证有前后依赖关系,且微信小程序的权限可以直接引导到设置页,所以最好使用Promise统一处理:
// uniapp示例
const checkPositionSetting = async () => {
return new Promise((resolve, reject) => {
uni.getSystemInfo({
success(systemRes) {
if (systemRes.locationEnabled && systemRes.locationAuthorized) {
uni.getSetting({
success(res) {
// 检查用户是否已经授权位置信息
if (res.authSetting['scope.userLocation']) {
resolve();
} else {
// 用户未授权,提示用户授权
uni.authorize({
scope: 'scope.userLocation',
success() {
resolve();
},
fail() {
// 用户拒绝授权,给出提示
uni.showModal({
title: '授权提示',
content: '我们需要您的位置信息来提供服务,请在设置中开启权限。',
showCancel: false,
confirmText: '前往设置',
success(modelRes) {
if (modelRes.confirm) {
// 用户点击了“前往设置”,打开手机设置
uni.openSetting({
success(settingdata) {
if (settingdata.authSetting['scope.userLocation']) {
resolve();
} else {
reject('用户仍未授权位置信息');
}
}
})
}
}
})
}
});
}
}
});
} else {
if (!systemRes.locationEnabled) {
reject("手机定位未开启,请开启后重试")
}
if (!systemRes.locationAuthorized) {
reject("微信定位权限被禁用,请开启后重试")
}
}
}
});
});
}