uni-app 用户地理位置授权

最终目的:需要拿到用户的经纬度。

  允许 -> 直接获取到地理信息,如果不允许:出现下边 “温馨提示”

  确认授权 -> 会调用用户【使用地理位置页面】:

  如果没设置 直接退出,会继续弹出确认授权页面,设置 -> 会走授权成功的回调, - > 获取用户地理信息

 

在app页面添加用户授权:

<script>
export default {
    globalData: {
        userInfo: {}
    },
    onShow: function() {
        this.handleAuthorize()
    },
    methods: {
        //  获取用户的地理位置,
        getLocationFn() {
            const _this = this
            uni.getLocation({
                type: 'gcj02', // <map> 组件默认为国测局坐标gcj02
                altitude: true,
                success(res) {
                    console.log('返回的位置信息', res, _this)
                    _this.globalData.userInfo = {
                        latitude: res.latitude,
                        longitude: res.longitude
                    }
                }
            })
        },
        // 用户授权
        handleAuthorize() {
            const _this = this // 下边this 为undefined
            uni.authorize({
                scope: 'scope.userLocation', // 获取地理信息必填的参数,其它参数见文档
                success(res) {
                    _this.getLocationFn()
                },
                // 授权失败
                fail(err) {
                    err = err['errMsg']
                    uni.showModal({
                        title: '温馨提示',content: '为享受智能小程序,您必须授权!',
                        showCancel: false,confirmText: '确认授权'
                    })
                     // 这里只设置了确认按钮,没有取消按钮
                    .then(res => {
                        //res : [null, {cancel: false, confirm: true, errMsg: 'showModal: ok'}]
                        if(res[1]['confirm']) { // 点击了确认按钮时
                            // 调用下边方法时,会弹出 【使用我的地理位置】界面, 未设置直接返回,还是会走fail授权失败的函数,
                            // 还是会弹出上边的温馨提示!!!
                            // 如果设置, scope.userLocation: true
                            uni.openSetting({
                                success(res) {
                                // 如果不设置,res结果:
                                // {errMsg: "openSetting:ok", authSetting: {scope.userLocation: false}}
                                // 如果设置, res结果: 
                                // {errMsg: "openSetting:ok", authSetting: {scope.userLocation: true}}
                                // console.log('小程序设置界面:', res)
                                }
                            })
                        }
                    })
                }
            })
         }
    }
}
</script>

 

  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值