微信公衆號 sdk 獲取當前地址

最近遇到一個需求,需要在公衆號的 web 項目中獲取當前用戶的位置。這邊使用SDK 去找到當前的經緯度後,卻一直沒法看到地址。那麼我們這邊使用騰訊地圖 API 的 逆地址解析就可以完成我們要的功能

記得在騰訊 api 那邊勾選 WebServiceAPI

在這裏插入圖片描述

作爲學習記錄

代碼如下:

wx.getLocation({
    type: 'wgs84', // 默認爲wgs84的gps座標,如果要返回直接給openLocation用的火星座標,可傳入'gcj02'
    success: function (res) {
        var lng = res.longitude;
        var lat = res.latitude;
        $('#Longitude').val(lng);
        $('#Latitude').val(lat);
        console.log(lat + "," + lng);
        $.ajax({
            type: 'get',
            url: 'http://apis.map.qq.com/ws/geocoder/v1',
            dataType: 'jsonp',
            data: {
                key: "你的key值",//開發密鑰
                location: lat + "," + lng,//位置座標
                get_poi: "1",//是否返回周邊POI列表:1.返回;0不返回(默認)
                coord_type: "1",//輸入的locations的座標類型,1 GPS座標
                parameter: { "scene_type": "tohome", "poi_num": 20 },//附加控制功能
                output: "jsonp"
            },
            success: function (data, textStatus) {
                if (data.status == 0) {
                    var address = data.result.formatted_addresses.recommend;
                    alert(data.result.address + address);
                } else {
                    alert("位置獲取錯誤,請聯繫管理員!")
                }
            },
            error: function () {
                alert("位置獲取錯誤,請聯繫管理員!")
            }
        });
    }
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章