要点:获取地理位置时,如果获取地理位置失败,有两种情况:
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) {
}
})
}
}
})
}
})