本文實例講述了微信小程序出現wx.getLocation再次授權問題的解決方法。分享給大家供大家參考,具體如下:
首先,在page外定義一個公共函數用于發送獲取位置的請求
var getLocation = function (that) { wx.getLocation({ type: 'wgs84', success: function (res) { // 經緯度 var latitude = res.latitude var longitude = res.longitude var aK = that.data.aK wx.request({ url: 'https://api.map.baidu.com/geocoder/v2/?ak=' + aK + '&location=' + latitude + ',' + longitude + '&output=json', data: {}, header: { 'content-type': 'application/json' }, success: function (res) { var city = res.data.result.addressComponent.city; that.setData({ currentCity: city }) wx.request({ url: 'xxx' + city, data: {}, header: { 'content-type': 'application/json' }, success: function (res) { that.setData({ county: res.data, }) }, }) } }) }, fail: function () { wx.showToast({ title: '授權失敗', icon: 'success', duration: 1000 }) } })}
然后,在page中需要位置調用page外部的getLocation
函數
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) { that.setData({ isshowCIty: false }) wx.showToast({ title: '授權失敗', icon: 'success', duration: 1000 }) } else if (res.confirm) { wx.openSetting({ success: function (dataAu) { if (dataAu.authSetting["scope.userLocation"] == true) { wx.showToast({ title: '授權成功', icon: 'success', duration: 1000 }) //再次授權,調用getLocationt的API getLocation(that); } else { wx.showToast({ title: '授權失敗', icon: 'success', duration: 1000 }) } } }) } } }) } else if (res.authSetting['scope.userLocation'] == undefined) {//初始化進入 getLocation(that); } else { //授權后默認加載 getLocation(that); } }})
上述過程執行順序為:
1.先加載wx.getLocation
彈出自己的授權框,如圖
然后,點擊確定即可授權,若點擊取消則取消授權,當再次需要授權時,會調用我們自定義的Modal框,如圖
其次,針對上述的Modal框點擊取消則關閉,若點擊確定則打開手機的地址授權設置,如圖
最后,若直接點擊左上方的返回箭頭則取消授權,若先選中地理位置按鈕,然后在點擊左上方的返回箭頭則授權成功,如圖
希望本文所述對大家微信小程序開發有所幫助。
新聞熱點
疑難解答