先上代码
let that = this
// 获取用户是否开启 授权获取当前的地理位置、速度的权限。
uni.getSetting({
success (res) {
console.log(res)
// 如果没有授权
if (!res.authSetting['scope.userLocation']) {
// 则拉起授权窗口
uni.authorize({
scope: 'scope.userLocation',
success () {
//点击允许后--就一直会进入成功授权的回调 就可以使用获取的方法了
uni.getLocation({
type: 'wgs84',
success: function (res) {
that.longitude = res.longitude
that.latitude = res.latitude
let jinweidu = {
longitude: res.longitude,
latitude: res.latitude,
}
uni.setStorageSync('jinweidu', jinweidu);
console.log(res)
console.log('当前位置的经度:' + res.longitude)
console.log('当前位置的纬度:' + res.latitude)
that.getlist()
}, fail (error) {
uni.showToast({
title: '获取地址失败,请检查手机是否打开定位功能,未打开将导致部分功能不可用',
icon:'none'
});
}
})
},
fail (error) {
//点击了拒绝授权后--就一直会进入失败回调函数--此时就可以在这里重新拉起授权窗口
console.log('拒绝授权', error)
uni.showModal({
title: '提示',
content: '若点击不授权,将无法使用位置功能',
showCancel: false,
// cancelText: '不授权',
// cancelColor: '#999',
confirmText: '授权',
confirmColor: '#f94218',
success (res) {
console.log(res)
if (res.confirm) {
// 选择弹框内授权
uni.openSetting({
success (res) {
console.log(res.authSetting)
}
})
} else if (res.cancel) {
// 选择弹框内 不授权
console.log('用户点击不授权')
}
}
})
}
})
} else {
// 有权限则直接获取
uni.getLocation({
type: 'wgs84',
success: function (res) {
that.longitude = res.longitude
that.latitude = res.latitude
let jinweidu = {
longitude: res.longitude,
latitude: res.latitude,
}
uni.setStorageSync('jinweidu', jinweidu);
console.log(res)
console.log('当前位置的经度1:' + res.longitude)
console.log('当前位置的纬度1:' + res.latitude)
that.getlist()
}, fail (error) {
uni.showToast({
title: '获取地址失败,请检查手机是否打开定位功能,未打开将导致部分功能不可用',
icon:'none'
});
console.log('失败', error)
}
})
}
}
})
}
将此方法放到onLoad生命周期内,第一次进入页面会出现授权弹窗(如下图)
点击允许就可以获取到经纬度了
如果拒绝授权位置信息的话就会出现弹窗进行提醒,提醒内容可以自己更改。
这个时候点击弹窗的授权会进入设置页面,允许位置信息再返回就可以获取到经纬度了
上面的代码是相当于强制用户授权位置信息,这是因为我的项目必须获取用户的位置信息,要不然无法使用,实际使用的时候根据项目的需求看是否需要强制用户授权位置信息,不需要的话就把弹窗的取消按钮加上就可以了。
特别注意:
uni.openSetting调起客户端小程序设置界面,返回用户设置的操作结果,此api只能在小程序中使用