背景:需要通過給定的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>