小程序獲取用戶位置信息後再次手動受權

最近使用小程序獲取當前的地理位置,提示「getLocation須要在app.json中聲明permission字段」,而後在app.json中增長permission屬性配置:git

"permission": {
    "scope.userLocation": {
      "desc": "你的位置信息將用於小程序位置接口的效果展現"
    }
 },

用戶首次進入獲取其地理位置信息要先通過受權,若是用戶贊成將成功獲取到其地理位置,而後頁面顯示一個‘獲取位置信息’按鈕,點擊後跳到地圖並標識其當前所在位置;若是開始受權時用戶拒絕了,那麼頁面會顯示一個‘受權並獲取位置信息’按鈕,用戶點擊後會跳到受權設置頁面,須要進行手動設置,設置後根據結果,若是設置了贊成那麼返回後顯示地圖上的其所在位置,若是沒有設置贊成返回後仍是顯示‘受權並獲取位置信息’按鈕。json

wxml:小程序

<button wx:if="{{isLocation}}" bindtap='Location'>獲取位置信息</button>
<button wx:else open-type="openSetting" bindopensetting='bindopensetting'>點擊受權並獲取位置信息</button>

js:app

data:{
    isLocation: false  
},

/**
   * 生命週期函數--監聽頁面加載
   */
onLoad: function(options){
var that = this;
//彈出受權用戶確認後獲取其地理位置 wx.getLocation({ type:
'wgs84', success: function (res) { var latitude = res.latitude var longitude = res.longitude that.setData({ isLocation: true, latitude: latitude, longitude: longitude }) }, fail: function (res) { console.log('拒絕受權') that.setData({ isLocation: false }) } }) }, //獲取位置信息 Location: function (e) { wx.openLocation({ latitude: this.data.latitude, longitude: this.data.longitude, scale: 18 }) }, //手動設置受權 bindopensetting: function (e) { var that = this; if (!e.detail.authSetting['scope.userLocation']) { that.setData({ isLocation: false }) } else { that.setData({ isLocation: true, }) wx.getLocation({ type: 'wgs84', success: function (res) { var latitude = res.latitude var longitude = res.longitude that.setData({ latitude: latitude, longitude: longitude }) wx.openLocation({ latitude: latitude, longitude: longitude, scale: 18 }) } }) } },

用戶首次進入經過onload 中的 wx.getLocation彈框受權位置,若是贊成isLocation設置爲true並保存位置信息,這時頁面直接顯示「獲取位置信息」按鈕,點擊後經過Location事件直接打開地圖,經過開始贊成受權後保存的經緯度顯示當前位置。 若是用戶第一次拒絕了受權,那麼isLocation設置爲false,顯示的是「點擊受權並獲取位置信息」按鈕,這時這個button按鈕的設置方式open-type=「openSetting」 bindopensetting=‘bindopensetting’,用按鈕的open-type發起打開受權設置頁,bindopensetting是設置用戶設置受權以後的回調,咱們可在回調裏判斷用戶勾沒勾選贊成受權,若是判斷贊成了,那麼isLocation設置爲true,以後顯示的都是「獲取位置信息」,沒必要受權直接顯示地圖;若是沒有勾選贊成那麼isLocation設置是false,以後再通過這個頁面仍是顯示「點擊受權並獲取位置信息」。最後注意的是在回調裏能夠用回調函數的參數來判斷e.detail.authSetting。函數

相關文章
相關標籤/搜索