uniapp获取用户当前位置信息(第一节)

本篇文章分享一下我在实际开发小程序时遇到的需要获取用户当前位置的问题,在小程序开发过程中经常使用到的获取定位功能。uniapp官方也提供了相应的API供我们使用。 官网地址:uni.getLocation(OBJECT))

  1. 首先根据官网uni.getLocation(OBJECT))来获取地理位置信息

uni.getLocation({
    type: 'wgs84',
    success: function (res) {
        console.log('当前位置的经度:' + res.longitude);
        console.log('当前位置的纬度:' + res.latitude);
    }
});

注意:这里面有个大坑(就是只会第一次授权弹出提示授权弹窗,加入拒绝授权后面不会在弹出

  1. 其次配置manifest.json文件

        "permission" : {
            "scope.userLocation" : {
                "desc" : "你的位置信息将用于小程序位置接口的效果展示"
            }
        },
        "requiredPrivateInfos": ["getLocation", "chooseLocation"]

3.这样就可以获取到当前位置信息了,效果图如下

4.下面来解决上面那个大坑(如果用户拒绝获取用户信息后,不能在弹出授权信息弹窗)

var _this=this
                uni.authorize({
                    scope: 'scope.userLocation',
                    success() { //1.1 允许授权
                    _this.getLocation();
                    },
                    fail() { //1.2 拒绝授权
                        uni.showModal({
                            content: '检测到您没打开获取信息功能权限,是否去设置打开?',
                            confirmText: "确认",
                            cancelText: '取消',
                            success: (res) => {
                                if (res.confirm) {
                                    uni.openSetting({
                                        success: (res) => {
                                            console.log(res);
                                            _this.getLocation();
                                        }
                                    })
                                } else {
                                    console.log('取消');
                                    return false;
                                }
                            }
                        })
                        return false;
                    }
                })

A.用户点击拒绝后会弹出模态框,去调用设置界面

B.点击确定即可跳转设置界面修改允许权限

这样就可以了,下一篇文章将拿到的经纬度换取中文详细地址信息。

猜你喜欢

转载自blog.csdn.net/weixin_53339757/article/details/129790201
今日推荐