大前端

前端学习之家-大前端

微信小程序 获取用户信息和地理位置

获取用户信息如nickName:

wxml:

<view>
  <view>{{myNickName}}</view>
</view>

js:

  data: {
    myNickName:""
  },
  getUser: function () {
    wx.getUserProfile({
      desc: '展示用户信息', //必填
      success:  (res)=> {//要用箭头函数,this才能获取到当前对象
        console.log(res.userInfo.nickName);//得到一个用户对象
        this.setData({
          myNickName:res.userInfo.nickName
        })
      }
    })
  },

获取地理位置信息如城市名:

wxml:

<view>
  <view>{{myCityName}}</view>
</view>

js:

onLoad: function (options) {
    wx.getLocation({
      altitude: false,
      type: "wgs84",
      success: (res) => {
        console.log(res);
        let latitude = res.latitude; //纬度
        let longitude = res.longitude; //经度
        wx.request({
          url: 'https://api.map.baidu.com/reverse_geocoding/v3/',
          data: {
            ak: "您的ak",
            output: "json",
            coordtype: "wgs8411",
            location: latitude + "," + longitude, //纬度,经度
          },
          success: (res) => {
            console.log(res.data.result);
            this.setData({
              myCityName: res.data.result.addressComponent.city
            })
          }
        })
      }
    })
  }

发表评论:

Copyright Your WebSite.Some Rights Reserved.