原文链接: https://blog.youkuaiyun.com/qq_42778001/article/details/104922059
因为需要做一个获取附近商家的功能。所以需要获取当前的经度和纬度的值,在原文的基础上修改为自己想要的效果
想要的效果:
弹出弹框,如果允许直接授权,如果不允许,弹出请授权位置的窗口
点击确认授权,跳到设置授权页面
如果打开获取地理位置,否则继续弹出请授权位置的弹框
在methods中写方法:
/ 判断是否已经授权
getSetting() {
const that = this
uni.getSetting({
success(res) {
console.log(res)
if (res.authSetting['scope.userLocation']) {
that.getLocation()
} else {
that.getAuthorize()
}
}
})
},
// 获取用户的地理位置,
getLocation() {
const that = this
uni.getLocation({
type: 'gcj02',
altitude: true,
success(res) {
console.log(res)
}
})
},
// 用户授权
getAuthorize() {
const that = this
uni.authorize({
scope: 'scope.userLocation',
success(res) {
that.getLocation()
},
// 授权失败
fail(err) {
uni.showModal({
title: '提示',
content: '请授权位置获取附近的商家!',
showCancel: false,
confirmText: '确认授权',
success() {
uni.openSetting({
success(res) {
console.log(res)
},
fail(err) {
console.log(err)
}
})
}
})
}
})
}
在onShow中调用
onShow: function() {
this.getSetting()
},