思路:
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)
},
})
},
},
// app.json 添加
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置"
}