方案一
wx.getSetting({
success(res) {
console.log('wx.getSetting:', res)
/**
* res.authSetting['scope.userLocation'] === true 同意过授权
* res.authSetting['scope.userLocation'] === false 拒绝过授权
* res.authSetting['scope.userLocation'] === undefined 从未同意或者拒绝过授权
*/
if (res.authSetting['scope.userLocation'] === undefined) {
wx.authorize({
scope: 'scope.userLocation',
success (res) {
console.log('authorize success:', res)
},
})
}else if (res.authSetting['scope.userLocation'] === false) {
wx.showModal({
title: '',
content: '去小程序设置页面设置balabala',
showCancel: true,
cancelText: '取消',
cancelColor: '#000000',
confirmText: '确定',
confirmColor: '#3CC51F',
success: (result) => {
if(result.confirm){
wx.openSetting({
success (res) {
console.log('wx.openSetting success:', res.authSetting)
},
fail: (err)=>{
console.log('wx.openSetting fail:', err)
},
complete: (info)=>{
console.log('wx.openSetting complete:', info)
},
})
}
},
})
} else {
wx.getLocation({
type: 'wgs84',
success (res) {
console.log('wx.location success:', res)
},
fail (err) {
console.log('wx.location fail:', err)
},
complete(aa) {
console.log('wx.location complete:', aa)
},
})
}
},
})
注意事项:
1、wx.openSetting
只显示小程序已经向用户申请过的权限
2、wx.getSetting
返回值中只会出现小程序已经向用户申请过的权限
3、app.json文件中配置位置信息的用途说明
"permission": {
"scope.userLocation": {
"desc": "您的位置信息将用于定位"
}
}
4、对于用户拒绝授权的情况调用wx.openSetting跳转小程序设置页面,引导用户手动开启该权限
方案二
1.当用户进入页面,开始判断用户之前是否授权;
2.如果已授权 直接获取位置信息;反之,弹框要求用户授权,
3.当用户点击确定 进入小程序授权设置界面 打开位置权限,
4.授权方法 必须写到onShow 中(便于实时监测用户是否关闭位置权限)
onShow() {
//检测用户是否之前授权
wx.getSetting({
success(res) {
if (!res.authSetting['scope.userLocation']) {
wx.authorize({
scope: 'scope.userLocation',
success() {},
fail() {
wx.showModal({
title: '小程序要获取你的地理位置',
content: '你的位置信息将用于小程序位置接口的效果展示',
success(res) {
if (res.confirm) {
wx.openSetting({
success() {
wx.getLocation({
type: 'wgs84',
success(res3) {
console.log(res3)
}
})
}
})
}
}
})
},
})
}
}
})
wx.startLocationUpdate({}) //开启小程序进入前台时接收位置消息
// 获取当前位置信息
let that = this
wx.getLocation({
type: 'gcj02',
isHighAccuracy: true,
success(res3) {
console.log(res3)
that.setData({
location: res3
})
}
})
// 打开当前位置
wx.openLocation({
latitude: this.data.location.latitude,
longitude: this.data.location.longitude,
scale: 18
})
// 选择位置
wx.chooseLocation({
latitude: this.data.location.latitude,
longitude: this.data.location.longitude,
success(res) {
console.log(res)
},
})
}