小程序---获取地理位置及获取用户userinfo信息


<template> <view> <!-- 测试 --> <view class="bar"> <button open-type="getUserInfo" @getuserinfo="wxLogin">登录/注册</button> <button open-type="openSetting" bindopensetting="callback">打开设置</button> </view> <van-button type="default" @tap="show">默认按钮</van-button> <van-popup show="{{ show }}" @close="onClose">内容</van-popup> </view> </view> </template> <script> import wepy from 'wepy'; export default class Personal extends wepy.page { config = { navigationBarTitleText: '个人中心', usingComponents: {} }; data = {}; methods = { async wxLogin(e) { //获取wx的login信息 let resLogin = await wepy.login(); //调用查询/获取地理位置方法 this.methods.getUserLocation(); //获取用户userinfo this.userinfo = e.detail.userInfo; //存入localstorge wepy.setStorage({ key: 'userinfo', data: this.userinfo }); //从localstorge拿地址信息 let locadate = wepy.getStorageSync('locationdate'); //从localstorge拿userinfo信息 let obj = wepy.getStorageSync('userinfo'); this.userInfo = obj; if (!obj) { //如果userinfo不存在说明该用户不同意授权 //将虚拟token放入localstorge wepy.setStorage({ key: 'token', data: '123456789' }); } else { //如果userinfo存在说明该用户同意授权 //将真实token放入localstorge wepy.setStorage({ key: 'token', data: resinfo.data.Token }); this.tokendate = resinfo.data.Token; } }, openSetting() { wx.openSetting(); }, getUserLocation() { wx.getSetting({ success: res => { // res.authSetting['scope.userLocation'] == undefined 表示 初始化进入该页面 // res.authSetting['scope.userLocation'] == false 表示 非初始化进入该页面,且未授权 // res.authSetting['scope.userLocation'] == true 表示 地理位置授权 if ( res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true ) { //未授权 wepy.showModal({ title: '请求授权当前位置', content: '需要获取您的地理位置,请确认授权', success: res => { if (res.cancel) { //取消授权 wepy.showToast({ title: '拒绝授权', icon: 'none', duration: 1000 }); } else if (res.confirm) { //确定授权,通过wx.openSetting发起授权请求 wepy.openSetting({ success: res => { if (res.authSetting['scope.userLocation'] == true) { wepy.showToast({ title: '授权成功', icon: 'success', duration: 1000 }); //再次授权,调用wx.getLocation的API this.geo(); } else { wepy.showToast({ title: '授权失败', icon: 'none', duration: 1000 }); } } }); } } }); } else if (res.authSetting['scope.userLocation'] == undefined) { //用户首次进入页面,调用wx.getLocation的API this.geo(); } else { console.log('授权成功'); //调用wx.getLocation的API this.geo(); } } }); }, async geo() { //地理位置授权获取 let result = await wepy.getLocation(); //拼接为字符串 this.locationdate = result.latitude + ',' + result.longitude; //存入locastorge wepy.setStorage({ key: 'locationdate', data: this.locationdate }); } }; } </script> <style > </style>

 1. 因为微信更新后,userinfo接口只能由用户自己去触发,所以只能设置按钮,但是可以修改按钮样式,比如,:登陆/注册

 2. location获取地理位置的接口有一点很坑的地方就是.如果第一次用户点击了拒绝,那么当你再次调用这个接口获取信息或者重新授权时,系统默认用户上次点击了拒绝,则不会弹框,直接按用户已拒绝处理,所以解决办法就是从新写一个弹框,让用户知道自己没有授权,然后自己主动从opensetting开启权限,这样在此调用的时候就会直接获取用户的地理位置信息,但是如果用户再次没有开权限,就又需要判定一遍,所以,层层逻辑下还是挺麻烦的.

3.因为需求更改,现在又有了promise和es6模式下的代码.过几天上传一下