微信公众号-定位之地址逆解析&导航

在微信JS_SDK工具包中为我们提供了地理定位的功能,但是该接口只返回了经纬度并没有返回准确的位置信息,此时我们可以通过调用腾讯地图的方法进行地址逆解析。

1. 获取地理位置接口

        wx.ready(function() {
            wx.getLocation({
                type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
                success: function(res) {
                    // alert(JSON.stringify(res))
                    let lat = res.latitude; // 纬度,浮点数,范围为90 ~ -90
                    let lng = res.longitude; // 经度,浮点数,范围为180 ~ -180。
                    
                }
            });
        
        });

2. 地址逆解析

  在页面中引入腾讯地图相关的js,这里的key你可以自己去申请

<script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=Z4MBZ-N3BHJ-NKSFN-FQ3U3-HLUOZ-KTFB3"></script>

  地址逆解析代码

geocoder = new qq.maps.Geocoder({
    complete:function(result){
        console.log(JSON.stringify(result.detail));
    }
});
var coord=new qq.maps.LatLng(lat, lng);
geocoder.getAddress(coord)

console.log(JSON.stringify(result.detail));结果如下:

{
    "address":"中国浙江省杭州市滨江区泰安路239号",
    "addressComponents":{
        "country":"中国",
        "province":"浙江省",
        "city":"杭州市",
        "district":"滨江区",
        "street":"泰安路",
        "streetNumber":"泰安路239号",
        "town":"西兴街道",
        "village":""
    },
    "location":{
        "lat":30.21,
        "lng":120.21
    },
    "nearPois":[
        {
            "latLng":{
                "lat":30.209749,
                "lng":120.20974
            },
            "id":"6786134103275397876",
            "name":"杭州市滨江区文化中心",
            "address":"浙江省杭州市滨江区泰安路200号",
            "category":"文化场馆:文化宫",
            "dist":0,
            "type":0
        }
    ]
}

使用微信内置地图查看位置接口,导航功能

$('.postion')导航按钮,这里需要注意的是如果不是float类型IOS不能调起导航
$('.postion').on('click',function(){
    wx.openLocation({
        longitude: parseFloat(res.shops.longitude),//必须是float类型
        latitude: parseFloat(res.shops.latitude),
        name: res.shops.designation,//目的地的名称
        address: res.shops.province+res.shops.city+res.shops.district+res.shops.address //目的地的地址
    }) 
})

效果图如下:

当你微笑的时候,全世界都会对你微笑。
原文地址:https://www.cnblogs.com/liruoruo/p/10273055.html