工作杂记

经纬度判断国内外

2019-06-25  本文已影响0人  Lingli_yu

背景:需要通过给定的GCJ02(火星坐标)判断国内外,国内则打开高德地图,国外则打开google 地图并标识

问题点整理:
需要根据经纬度判断国内国外:高德地图API(逆地理编码)

国内通过GCJ02坐标系坐标打开高德地图:高德地图API(单点标注))

需要将GCJ02坐标系转为GPS坐标系(WGS84):坐标系转换谷歌地图API(这里也可以不需要转坐标系,高德获取到的坐标,国内的是经过偏移算法处理的--国家规定的,获取到国外的坐标就是GPS坐标)

关键点:通过高德逆地理编码API获取数据时,当获取到数据为空时存在两种情况: 海上和国外,以此判断国内外。

代码实现如下

   <script src="https://unpkg.com/gcoord/dist/gcoord.js"></script>
   <script>
        function Location (lng, lat){
            this.lng = +lng;
            this.lat = +lat;
        }

        Location.prototype.gcj02towgs84 = function() {
            return gcoord.transform([this.lng, this.lat], gcoord.GCJ02, gcoord.WGS84);
        };

        Location.prototype.locationReq = function() {
            var _this = this;
            var path = 'https://restapi.amap.com/v3/geocode/regeo?key=08b01605f97da862b15aceb0fb20d243&extensions=all&location='
                + this.lng+','+ this.lat;
            var xhr = new XMLHttpRequest();
            xhr.open('GET',path, true);
            xhr.send();

            xhr.onreadystatechange = function(rep) {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    if (rep.currentTarget && rep.currentTarget.response) {
                        _this.openMap(JSON.parse(rep.currentTarget.response));
                    }
                }
            }
        };

        Location.prototype.openMap = function(rep) {
            var wgLocation = this.gcj02towgs84(this.lng, this.lat);
            var aMap = 'https://uri.amap.com/marker?position='+ this.lng+','+ this.lat;
            var gMap = 'https://www.google.com/maps/search/?api=1&query='+wgLocation[0]+','+ wgLocation[1];

            if (rep && rep.status !== '1') return;
            if (rep && rep.regeocode) {
                if (rep.regeocode.formatted_address.length) {
                    window.location.replace(aMap)
                } else {
                    window.location.replace(gMap)
                }
            }
        };
        var locationArr= [ 122, 103 ];
        var locationIns = new Location(locationArr[0], locationArr[1]);
        locationIns.locationReq();
    </script>
上一篇 下一篇

猜你喜欢

热点阅读