微信小程序地理位置授权

微信小程序地理位置授权

1、小程序中获取当前的地理位置,需要用户授权scope.userLocation
首先在app.json中配置

"permission": {
    "scope.userLocation": {
        "desc": "你的位置信息将用于计算与门店的距离"
    }
}

2、判断首次打开时用户是否获得了地理位置授权

//获取定位
//判断是否获得了用户地理位置授权
getSetting: function() {
    let that = this;
    wx.getSetting({
        success: (res) => {
            // 查看位置权限的状态 如果是首次授权(undefined)或者之前拒绝授权(false)            
            //!res.authSetting['scope.userLocation']
            if (res.authSetting['scope.userLocation'] == false) {
                //之前拒绝授权(false)
                that.openConfirm()
            } else {
                //如果是首次授权则弹出授权窗口进行授权,如果之前进行了授权,则获取地理位置信息
                that.getLocation()
            }
        }
    })
},
openConfirm: function() {
    let that = this;
    wx.showModal({
        content: '检测到您没打开定位权限,是否去设置打开?',
        confirmText: "确认",
        cancelText: "取消",
        success: function(res) {
            console.log(res);
            //点击“确认”时打开设置页面
            if (res.confirm) {
                console.log('用户点击确认')
                wx.openSetting({
                    success: (res) => {
                        that.getLocation()
                    }
                })
            } else {
                console.log('用户点击取消')
            }
        }
    });
},
getLocation: function() {
    let that = this;
    wx.getLocation({
        type: 'gcj02',
        altitude: true,
        success: function(res) {},
        fail: function(res) {
           console.log("---未授权---");
           wx.openSetting({})
        },
        complete: function(res) {},
    })
},

posted @ 2021-03-03 15:58  清言  阅读(1931)  评论(0编辑  收藏  举报