微信小程序开发用户位置信息授权及拒绝后再授权并加入未开GPS提醒
目录
微信小程序开发:用户位置信息授权及拒绝后再授权并加入未开GPS提醒
第一步:必须要在app.json对小程序进行全局配置
//该字段会弹窗请求第一次使用小程序的用户授权
"permission": {
"scope.userLocation": {
"desc": "我们将获取到你的位置信息" //文字最多不超过30字
}
}
第二步:在你使用定位的页面插入授权代码
data:{
isshowCIty:''
}
//我是直接放在onLoad()函数加载出来
onLoad:function(){
//wx.getSetting是获取用户授权的信息的,除了应用在位置信息授权还能应用在用户信息授权等等
wx.getSetting({
success: (res) => {
// scope.userLocation == undefined代表用户未授权且第一次登陆
console.log('检查地理位置信息是否授权', res.authSetting['scope.userLocation'])
if (res.authSetting['scope.userLocation'] == undefined) {
//如果用户是第一次登陆且未授权的情况,会直接弹窗请求授权
// 使用 getlocation 获取用户 经纬度位置
wx.getLocation({
type:'gcj02',//这里我们要指定定位类型是gcj02,因为不填默认是wgs84,定位精确度会相较于gcj02有几百到一千米的偏差,如果对精确度要求较高的请务必加上type:'gcj02'
success(res){
//获取用户位置成功后,将会返回 latitude, longitude 两个字段,代表用户的经纬度位置
console.log(res)
that.setData({
latitude: res.latitude,
longitude: res.longitude,
})
//给经纬度定义为全局变量,可以在全局调用
app.latitude=res.latitude;
app.longitude=res.longitude;
},
fail(err){
console.log(err)
//用户已授权,但是获取地理位置失败,会弹框提示用户去系统设置中打开定位
wx.showModal({
title: '',
content: '请在系统设置中打开定位服务,开启GPS后请下拉刷新',
confirmText: '确定',
success: function (res) {
}
})
}
})
}
//小程序检测到用户不是第一次进入该页面,且未授权
else if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
wx.showModal({
title: '是否授权当前位置',
content: '需要获取您的地理位置,请确认授权,否则无法获取您所需数据',
success: function (res) {
//如果点击取消则显示授权失败
if (res.cancel) {
that.setData({
isshowCIty: false
})
wx.showToast({
title: '授权失败',
icon: 'success',
duration: 1000
})
}
//如果点击确定会打开授权页请求二次授权
else if (res.confirm) {
wx.openSetting({
success: function (dataAu) {
if (dataAu.authSetting["scope.userLocation"] == true) {
wx.showToast({
title: '授权成功',
icon: 'success',
duration: 1000
})
//再次授权,调用getLocationt的API
wx.getLocation({
type:'gcj02',
success(res){
// console.log(res)
that.setData({
latitude: res.latitude,
longitude: res.longitude,
})
},
fail(err){
//用户已授权,但是获取地理位置失败,提示用户去系统设置中打开定位
wx.showModal({
title: '',
content: '请在系统设置中打开定位服务',
confirmText: '确定',
success: function (res) {
}
})
}
})
} else {
wx.showToast({
title: '授权失败',
icon: 'success',
duration: 1000
})
}
}
})
}
}
})
}
else if(res.authSetting['scope.userLocation'] == true){
//授权后默认加载,直接获取定位
wx.getLocation({
type:'gcj02',
success(res){
console.log(res);
that.setData({
latitude: res.latitude,
longitude: res.longitude,
})
},
fail(err){
//用户已授权,但是获取地理位置失败,提示用户去系统设置中打开定位
wx.showModal({
title: '',
content: '请在系统设置中打开定位服务',
confirmText: '确定',
success: function (res) {
}
})
}
})
}
}
})
}