小程序地理位置获取与用户信息授权

博客展示了小程序开发中的相关文件,包括 app.json、app.js、html 和 index.js,涉及小程序地理位置获取、用户信息授权等开发内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

app.json:

"permission": {
    "scope.userLocation": {
      "desc": "你的位置信息将用于小程序位置接口的效果展示"
    }
}

app.js:

App({
  //全局参数
  globalData: {
    userInfo: null
  },
  onLaunch: function () {
    // 获取用户信息
    wx.getSetting({
      success: res => {
        // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
          console.log('已经授权')
        }
      }
    })
  },
})

html:

<button open-type="getUserInfo" bindgetuserinfo="getUserInfo">用户信息授权</button>
<button bindtap='onAuthLocation' >授权并获取位置</button>
<button bindtap='gotoSetting' >打开授权信息面板</button>

index.js:

const app = getApp()
Page({
  data: {
    userInfo: {},
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function () {
    //userInfo有数据
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
      })
    } 
    else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
        })
      }
    } 
    else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
          })
        }
      })
    }
  },
  //信息授权点击了允许
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
    })
  },
  //位置授权
  onAuthLocation() {
    wx.authorize({
      scope: 'scope.userLocation',
      success: (res) => {
        console.log('成功:', res)
        this.onGetLocation();//获取位置
      },
      fail: (res) => {
        console.log('失败:', res)
      },
    })
  },
  //获取位置
  onGetLocation() {
    wx.getLocation({
      success: (res) => {
        console.log('成功:', res)
      },
      fail: (res) => {
        console.log('失败:', res)
      },
    })
  },
  //授权面板
  gotoSetting() {
    wx.openSetting({
      success: (res) => {
        console.log(res)
      }
    })
  },
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值