這兩天在做小程序調取地圖的時候遇到一個問題,如果用戶第一次拒絕了位置權限請求。那麼就不會再次喚起授權彈出。需要我們引導用戶去開啓。
具體做法如下。
在 aap.json
中加入授權配置
"permission": {
"scope.userLocation": {
"desc": "你的位置信息將用於小程序位置接口的效果展示"
}
}
在 page頁面中使用,需要有幾個注意的地方,初次使用的時候,去申請權限。這裏我是放在onShow
方法裏面。
onShow: function () {
//初始獲取定位權限
wx.authorize({
scope: 'scope.userLocation',
success: (res) => {
},
})
},
然後在調用地圖地位。或者獲取用戶權限的函數去判斷是否有定位權限,如果沒有那麼引導用戶開啓權限。
如下:我有一個Input去觸發選擇地圖事件。
<input bindfocus="openMap" value='{{address}}' placeholder="點擊選擇詳細地址"></input>
事件處理
openMap:function(e){
var that = this
wx.getSetting({
success(res){
//這裏判斷是否有地位權限
if (!res.authSetting['scope.userLocation']) {
wx.showModal({
title: '提示',
content: '請求獲取位置權限',
success:function(res){
if(res.confirm==false){
return false;
}
wx.openSetting({
success(res) {
//如果再次拒絕則返回頁面並提示
if (!res.authSetting['scope.userLocation']) {
wx.showToast({
title: '此功能需獲取位置信息,請重新設置',
duration: 3000,
icon: 'none'
})
} else {
//允許授權,調用地圖
that.chooseMap()
}
}
})
}
})
} else {
//如果有定位權限,調用地圖
that.chooseMap()
}
}
})
},
chooseMap(){
var that = this
wx.chooseLocation({
success: function (res) {
that.setData({
address: res.address,
latitude: res.latitude,
longitude: res.longitude
})
},
fail: function (res) {
console.log(res)
}
})
},