微信小程序的新版本更新后获得用户的地理位置需要先声明用途
具体做法,在app.json中增加permission字段
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示"
}
},
然后获取位置信息时 getLocation+openSetting可以实现地理位置再次授权,即如果用户第一次拒绝了,可以调用openSetting再次请求用户授权,通过res.authSetting['scope.userLocation']的值与true比较,为true就是授权了,false就是拒绝授权
getUserLocation: function () {
let vm = this;
wx.getSetting({
success: (res) => {
if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
wx.showModal({
title: '请求授权当前位置',
content: '需要获取您的地理位置,请确认授权',
success: function (res) {
if (res.cancel) {
wx.showToast({
title: '拒绝授权',
icon: 'none',
duration: 1000
})
} else if (res.confirm) {
wx.openSetting({
success: function (dataAu) {
if (dataAu.authSetting["scope.userLocation"] == true) {//res.authSetting['scope.userLocation']的值与true比较,为true就是授权了,false就是拒绝授权了
wx.showToast({
title: '授权成功',
icon: 'success',
duration: 1000
})
//再次授权,调用wx.getLocation的API
vm.getLocation();
} else {
wx.showToast({
title: '授权失败',
icon: 'none',
duration: 1000
})
}
}
})
}
}
})
} else if (res.authSetting['scope.userLocation'] == undefined) {
//调用wx.getLocation的API
vm.getLocation();
}
else {
//调用wx.getLocation的API
vm.getLocation();
}
}
})
},