【小程序记录】原生小程序引导用户地址授权
1.原生小程序引导用户地址授权
小程序里面用户取消一次获取位置授权弹窗后,后续的弹窗就不会自动弹出来了,需要咱们手动引导一下。
实现步骤
1.在getcity方法中调用wx.getLocation方法,若用户授权,则根据经纬度调用getLocations中百度api解析出定位城市。
2.若用户取消授权,则使用wx.showModal方法引导用户重新授权,在点击确认后调用微信wx.openSetting()方法打开权限设置页面,在设置页面返回时,会触发success方法,在方式里面通过res.authSetting['scope.userLocation'])判断用户是否授权地址位置,若为false,则代表用户未授权,为true则已授权,重新调用百度api获取定位。
3.用户未授权时每次进页面,都会触发wx.showModal方法来引导用户重新授权,可以达到引导用户重新授权的功能。
代码如下
Page({
onLoad: function(options) {
this.getCity()
},
// 获取城市定位
getCity() {
let that = this;
wx.getLocation({
success: res => {
that.getLocations(res);
},
fail(err) {
wx.showModal({
title: '温馨提示',
content: '为了更好的为您服务,请授权地址权限',
success(res) {
if (res.confirm) {
wx.openSetting({
success(res) {
if (res.authSetting['scope.userLocation']) {
wx.getLocation({
success: res => {
that.getLocations(res);
}
});
} else {
console.log('获取失败')
}
}
});
} else {
console.log('获取失败')
}
}
});
}
});
},
// 根据经纬度定位
getLocations(res) {
let that = this;
wx.request({
url:`https://api.map.baidu.com/geocoder/v2/?
ak=wpStIAtm70fyDoUkl3XZwy01WsLvytxj&
location=${res.latitude},${res.longitude}&output=json&pois=1`,
success(res) {
console.log(res.data.result)
}
});
}
})