經(jīng)緯度判斷國(guó)內(nèi)外

背景:需要通過給定的GCJ02(火星坐標(biāo))判斷國(guó)內(nèi)外,國(guó)內(nèi)則打開高德地圖,國(guó)外則打開google 地圖并標(biāo)識(shí)

問題點(diǎn)整理:
需要根據(jù)經(jīng)緯度判斷國(guó)內(nèi)國(guó)外:高德地圖API(逆地理編碼)

國(guó)內(nèi)通過GCJ02坐標(biāo)系坐標(biāo)打開高德地圖:高德地圖API(單點(diǎn)標(biāo)注))

需要將GCJ02坐標(biāo)系轉(zhuǎn)為GPS坐標(biāo)系(WGS84):坐標(biāo)系轉(zhuǎn)換谷歌地圖API(這里也可以不需要轉(zhuǎn)坐標(biāo)系,高德獲取到的坐標(biāo),國(guó)內(nèi)的是經(jīng)過偏移算法處理的--國(guó)家規(guī)定的,獲取到國(guó)外的坐標(biāo)就是GPS坐標(biāo))

關(guān)鍵點(diǎn):通過高德逆地理編碼API獲取數(shù)據(jù)時(shí),當(dāng)獲取到數(shù)據(jù)為空時(shí)存在兩種情況: 海上和國(guó)外,以此判斷國(guó)內(nèi)外。

代碼實(shí)現(xiàn)如下

   <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>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容