微信小程序弹出用户授权弹窗,微信小程序引导用户授权,获取位置经纬
2019-02-20 本文已影响75人
编程小石头666
我们在开发小程序时,有些操作必须让用户授权。比如我们获取用户位置,需要用户授权位置信息。授权操作我们需要给用户弹窗提示,在用户禁用某些权限时,又要引导用户去设置页开启相应权限。我们这里就以获取经纬度为例,来带大家学会友好的引导用户授权。
老规矩,先看效果图

一,我们使用位置信息,就需要授权
//校验位置权限是否打开
checkLocation() {
let that = this;
//选择位置,需要用户授权
wx.getSetting({
success(res) {
if (!res.authSetting['scope.userLocation']) {
wx.authorize({
scope: 'scope.userLocation',
success() {
wx.showToast({ //这里提示失败原因
title: '授权成功!',
duration: 1500
})
},
fail() {
that.showSettingToast('需要授权位置信息');
}
})
}
}
})
},

首先检验用户是否授权位置信息的权限“scope.userLocation”,如果有授权,我们就可以直接去获取用户的位置经纬度了。如果没有授权,我们就弹窗引导用户去设置页。去设置页的方法如下
// 打开权限设置页提示框
showSettingToast: function (e) {
wx.showModal({
title: '提示!',
confirmText: '去设置',
showCancel: false,
content: e,
success: function (res) {
if (res.confirm) {
wx.navigateTo({
url: '../setting/setting',
})
}
}
})
},

由于去设置页,需要用户手动触发,这里我们就用一个setting.wxml页作为过过渡页。

我们这个过渡页的按钮,用户点击后就会去真正的授权页了。

当用户开启地理位置授权后。我们再点击获取位置,就可以获取到用户当前的经纬度了。

完整代码如下
//index.js
Page({
getLocation() {
this.checkLocation();
let that = this;
wx.chooseLocation({
success: function(res) {
var latitude = res.latitude
var longitude = res.longitude;
that.setData({
address: "经纬度:" + longitude + ", " + latitude,
})
}
});
},
//校验位置权限是否打开
checkLocation() {
let that = this;
//选择位置,需要用户授权
wx.getSetting({
success(res) {
if (!res.authSetting['scope.userLocation']) {
wx.authorize({
scope: 'scope.userLocation',
success() {
wx.showToast({ //这里提示失败原因
title: '授权成功!',
duration: 1500
})
},
fail() {
that.showSettingToast('需要授权位置信息');
}
})
}
}
})
},
// 打开权限设置页提示框
showSettingToast: function (e) {
wx.showModal({
title: '提示!',
confirmText: '去设置',
showCancel: false,
content: e,
success: function (res) {
if (res.confirm) {
wx.navigateTo({
url: '../setting/setting',
})
}
}
})
},
})
到此我们就实现了小程序引导授权的全部功能,并且可以获取到用户的位置经纬度了。是不是很简单。
如果有关于小程序的问题,可以加我微信2501902696(备注小程序)