前言:
小程序需要添加一個定位功能,主要的就是獲取用戶位置的經緯度,然后根據用戶經緯度進行一些判斷操作。
在小程序提供的Api中,獲取用戶定位信息的主要Api是 wx.getLocation(obj) 。但是使用這個API,會先獲取用戶授權。如果用戶取消授權,那么再調這個Api,也不會再出現授權頁面,也就不能再獲取用戶位置了,這就需要使用其他的Api輔助打開授權頁面了。所以獲取用戶位置就需要完整的授權、獲取位置的流程及異常流處理了。
業務流程圖:
關鍵技術點:
頁面加載默認調用 wx.getLocation ,然后如果獲取失敗則調用 wx.getSetting ,如果未授權,則調用 wx.openSetting 打開授權設置界面,如果授權界面設置允許授權,則返回頁面再次調用 wx.getLocation,主要的流程就是這個了。
示例代碼:
1 const app = getApp() 2 3 Page({ 4 data: { 5 hiddenReAuthorizePop:true,//隱藏重新授權確認彈窗 6 latitude: "", //維度,浮點數 7 longitude: "", //經度,浮點數 8 content:"本活動需要獲取位置才可以參加" 9 }, 10 onLoad: function() { 11 //1. 頁面加載的時候獲取定位 12 this.getLocation() 13 }, 14 /** 15 * 1. 獲取用戶定位 16 */ 17 getLocation: function() { 18 var self = this; 19 wx.getLocation({ 20 type: 'wgs84', // 默認為wgs84的gps坐標,如果要返回直接給openLocation用的坐標,可傳入'gcj02' 21 altitude: true, //傳入 true 會返回高度信息,由於獲取高度需要較高精確度,會減慢接口返回速度 22 success: function(res) { 23 var latitude = res.latitude; // 緯度,浮點數 24 var longitude = res.longitude; // 經度,浮點數 25 self.setData({ 26 latitude: res.latitude, 27 longitude: res.longitude 28 }) 29 }, 30 fail: function(res) { 31 //未授權就彈出彈窗提示用戶重新授權 32 self.reAuthorize(); 33 } 34 }); 35 }, 36 /** 37 * 1.2 重新授權按鈕點擊事件 38 * click event 39 */ 40 openLocationSetting: function() { 41 var self = this 42 //先獲取用戶的當前設置,返回值中只會出現小程序已經向用戶請求過的權限 43 wx.getSetting({ 44 success: function(res) { 45 if (res.authSetting && !res.authSetting["scope.userLocation"]) { 46 //未授權則打開授權設置界面 47 wx.openSetting({ 48 success: function(res) { 49 if (res.authSetting && res.authSetting["scope.userLocation"]) { 50 //允許授權,則自動獲取定位,並關閉二確彈窗,否則返回首頁不處理 51 self.getLocation(); 52 self.setData({ 53 hiddenReAuthorizePop:true 54 }) 55 wx.showToast({ 56 title: '您已授權獲取位置信息', 57 icon: 'none' 58 }) 59 }else{ 60 //未授權就彈出彈窗提示用戶重新授權 61 self.reAuthorize(); 62 } 63 } 64 }) 65 } else { 66 //授權則重新獲取位置新(授權設置界面返回首頁,首頁授權二確彈窗未關閉) 67 self.getLocation(); 68 } 69 } 70 }) 71 }, 72 /** 73 * 重新授權 74 */ 75 reAuthorize:function(){ 76 var self=this 77 self.setData({ hiddenReAuthorizePop:false}) 78 } 79 })
代碼片段地址:https://developers.weixin.qq.com/s/uRMylxmO7e3Q
原創專業博客,轉載請注明來源地址:https://www.cnblogs.com/xyyt/p/9871898.html