寫在前面:在tarbar主頁面,再次授權JS代碼請放在onshow里面;在詳情頁(非一級主頁面),再次授權JS代碼請放在onReady里面,具體原因我前面博客講了的。
我們知道:
1、微信的getLocation接口,是獲取用戶當前地理位置的,返回經緯度、速度等信息;
2、它的默認工作機制:
首次進入頁面,調用該api,返回用戶授權結果,並保持該結果。
只要用戶未刪除該小程序或變更授權情況,那么用戶再次進入該頁面,
授權結果還是不變,且不會再次調用該API;
3、那么問題來了:如何不要求用戶刪除小程序情況下,再次發起授權請求呢? KEY:wx.openSetting
1、效果圖:首次進入某頁面
拒絕授權后,再次進入該頁面或者點擊頁面某按鈕(獲取位置)綁定JS
2、不知道有沒有細心的道友,發現上面2個彈出框的結構是一樣的,前者使用的是wx.getLocation接口自帶的樣式,后者使用的wx.showModel接口帶的樣式
3、廢話不多說,簡單講一下原理:首次進入該頁面,onload或者onshow調用wx.getLocation要求用戶進行授權;用戶拒絕后,再次進入該頁面,我們通過wx.getSetting接口,返回用戶授權的情況:
JS打印:=> ||| console控制台輸出:=>
然后,根據上面JS中,res.authSetting['scope.userLocation']的值與true比較,為true就是授權了,false就是拒絕授權了。
我們這里考慮的是拒絕授權,再調用wx.openSetting接口,請求再次授權,返回授權結果處理數據和業務。over,就是這么EASY!
4、我這里只打印出了userInfo和userLocation的接口返回信息,當然你還可以打印其他的信息,只要你之前調用過這些微信API,詳見微信的scope表:https://mp.weixin.qq.com/debug/wxadoc/dev/api/authorize-index.html
5、詳情代碼:
//地圖功能單獨拿出來 -xzz1023 var village_LBS = function(that){ //var that = this; // ------------ 騰訊LBS地圖 -------------------- wx.getLocation({ type: 'gcj02', //返回可以用於wx.openLocation的經緯度 success: function (res) { // 調用接口, 坐標轉具體位置 -xxz0717 demo.reverseGeocoder({ location: { latitude: Number(res.latitude), longitude: Number(res.longitude) }, success: function (res) { console.log(res); that.setData({ start_address: res.result.address, //起點地址 city: res.result.address_component.city, //起點城市 district: res.result.address_component.district //區 }) } }); }) ) Page({ onLoad: function (options) { var that = this; village_LBS(that); } onReady: function () { var that = this; wx.getSetting({ success: (res) => { console.log(res); console.log(res.authSetting['scope.userLocation']); if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {//非初始化進入該頁面,且未授權 wx.showModal({ title: '是否授權當前位置', content: '需要獲取您的地理位置,請確認授權,否則地圖功能將無法使用', success: function (res) { if (res.cancel) { console.info("1授權失敗返回數據"); } else if (res.confirm) { //village_LBS(that); wx.openSetting({ success: function (data) { console.log(data); if (data.authSetting["scope.userLocation"] == true) { wx.showToast({ title: '授權成功', icon: 'success', duration: 5000 }) //再次授權,調用getLocationt的API village_LBS(that); }else{ wx.showToast({ title: '授權失敗', icon: 'success', duration: 5000 }) } } }) } } }) } else if (res.authSetting['scope.userLocation'] == undefined) {//初始化進入 village_LBS(that); } } }) } })