1. 程式人生 > >button獲取使用者授權以及地理位置授權回撥資訊

button獲取使用者授權以及地理位置授權回撥資訊

1. 獲取使用者授權資訊

<button open-type='getUserInfo' bindgetuserinfo="getUserInfo">獲取使用者授權</button>

當前未授權的狀態下每次點選都會調起授權彈窗,getUserInfo函式為彈窗點選的回撥
2. 獲取地理位置資訊

<button open-type='openSetting' bindopensetting="getOpenSetting">獲取地理位置授權</button>

當前未授權的狀態下每次點選都會調起授權彈窗,getOpenSetting函式為使用者進入設定頁面後的回撥,地理位置已授權才能獲取經緯度資訊。
3. JS檔案

//獲取使用者授權
getUserInfo:function(e){
    wx.getSetting({
      success: (res) => {
        console.log('是否授權', res.authSetting["scope.userInfo"])
        if (res.authSetting["scope.userInfo"]) {
          console.log('使用者資訊',e.detail.userInfo)
        }
      }
    })
  },
  //獲取地理位置授權
  getOpenSetting(e) {
    if (e.type === "opensetting") {
      //地理位置授權
      if (e.detail.authSetting["scope.userLocation"]) {
        //獲取經緯度資訊  注:wx.getLocation只能調起一次使用者授權,拒絕後不會再次呼叫
        wx.getLocation({
          type: "wgs84",
          success: function (res) {
            that.setData({ 
              latitude: res.latitude, 
              longitude: res.longitude
              });
          },
          fail: function (res) {
            console.log(res, "地理位置失敗");
          }
        });
      } else {
        wx.showToast({
          title: "授權失敗",
          icon: "none",
          duration: 1000
        });
      }
    }
  }

wx.getsetting 可獲取當前授權狀態

 wx.getSetting({
      success (res) {
        console.log(res.authSetting)
         res.authSetting = {
           "scope.userInfo": true,//使用者資訊表示已授權
           "scope.userLocation": true//地理位置已授權
         }
      }
    })