微信小程序获取当前位置

微信小程序获取当前位置

检查用户是否有已授权。当用户已操作授权的,直接调用获取当前位置方法。

项目中需求: 获取当前位置后, 把经纬度发送给后端,由于展示位置相关信息的页面是vue的, 这里应用到微信小程序跳转h5方法

直接使用代码 , 有所不足.欢迎大神指教。

效果图

在这里插入图片描述

相关API

wx.getSetting

wx.openSetting

wx.getLocation

获取用户当前设置

  1. 如用户没有授权情况,用户发生点击行为后弹窗询问,点击允许成功回调中获取当前位置

  2. 当用户点击拒绝后, 下次用户再发生点击行为后直接调起客户端设置界面,用户设置操作。【也可以用弹窗方式询问用户再调起客户端界面, 各所需】

/**
 * 授权打开定位
 */
ruleLocation: function() {
    var that = this;
    //检查地理位置授权
    wx.getSetting({
        success: (res) => {
            if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
                console.log('location', res);
                // 调起客户端设置界面
                wx.openSetting({
                    success: function(data) {
                        if (data.authSetting["scope.userLocation"] == true) {
                            //  wx.showToast({
                            //    title: '授权成功',
                            //    icon: 'success',
                            //    duration: 5000
                            //  })
                            that.getLocation();
                        } else {
                            //  wx.showToast({
                            //    title: '授权失败',
                            //    icon: 'success',
                            //    duration: 5000
                            //  })
                        }
                    }
                })
            } else {
                that.getLocation();
            }
        }
    })
},

获取当前位置经纬度

/**
 * 调用wx.getLocation系统API,获取并设置当前位置经纬度
 */
getLocation: function() {
    var that = this;
    //获取位置
    wx.getLocation({
        type: 'gcj02', //默认为 wgs84 返回 gps 座标,gcj02 返回可用于wx.openLocation的座标
        success: function(res) {
            //console.log(res.longitude+'~~~'+res.latitude);
            that.setData({
                lng: res.longitude,
                lat: res.latitude
            })
           // 处理业务逻辑 (把当前经纬度发送给后端处理等)
            
           //这里: 跳转h5页面
            wx.navigateTo({
                url: '/pages/out/out?lng='+that.data.lng+'&lat='+that.data.lat,    
            })
        },
        fail: function(e) {
            console.log("error", e);
        }
    });
},

注意:

这时,如果直接运行代码会提示需声明permission字段。那就按照提示操作吧~~~

提示操作

在这里插入图片描述

声明字段

app.json中声明permission字段, 如下

"permission": {
    "scope.userLocation": {
        "desc": "需要获取您的地理位置,请确认授权,否则地图定位功能将无法使用"
    }
},
"sitemapLocation": "sitemap.json"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章