本文實例講述了微信小程序出現(xiàn)wx.getLocation再次授權(quán)問題的解決方法。分享給大家供大家參考,具體如下:
首先,在page外定義一個公共函數(shù)用于發(fā)送獲取位置的請求
var getLocation = function (that) { wx.getLocation({ type: 'wgs84', success: function (res) { // 經(jīng)緯度 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: '授權(quán)失敗', icon: 'success', duration: 1000 }) } })}然后,在page中需要位置調(diào)用page外部的getLocation 函數(shù)
wx.getSetting({ success: (res) => { if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {//非初始化進入該頁面,且未授權(quán) wx.showModal({ title: '是否授權(quán)當前位置', content: '需要獲取您的地理位置,請確認授權(quán),否則無法獲取您所需數(shù)據(jù)', success: function (res) { if (res.cancel) { that.setData({ isshowCIty: false }) wx.showToast({ title: '授權(quán)失敗', icon: 'success', duration: 1000 }) } else if (res.confirm) { wx.openSetting({ success: function (dataAu) { if (dataAu.authSetting["scope.userLocation"] == true) { wx.showToast({ title: '授權(quán)成功', icon: 'success', duration: 1000 }) //再次授權(quán),調(diào)用getLocationt的API getLocation(that); } else { wx.showToast({ title: '授權(quán)失敗', icon: 'success', duration: 1000 }) } } }) } } }) } else if (res.authSetting['scope.userLocation'] == undefined) {//初始化進入 getLocation(that); } else { //授權(quán)后默認加載 getLocation(that); } }})上述過程執(zhí)行順序為:
1.先加載wx.getLocation彈出自己的授權(quán)框,如圖

然后,點擊確定即可授權(quán),若點擊取消則取消授權(quán),當再次需要授權(quán)時,會調(diào)用我們自定義的Modal框,如圖
新聞熱點
疑難解答