Front-end/JS tip

javascript 두 좌표 사이의 거리 구하기

아지송아지 2022. 2. 16. 20:07
function getDistanceFromLatLonInKm(lat1,lng1,lat2,lng2) {
  function deg2rad(deg) { return deg * (Math.PI/180) }
  var R = 6371; 
  var dLat = deg2rad(lat2-lat1); 
  var dLon = deg2rad(lng2-lng1);
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *   Math.sin(dLon/2) * Math.sin(dLon/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;
  return d;
}

테스트결과 잘 나옵니다 :)

console.log(getDistanceFromLatLonInKm(37.497604, 127.026960, 37.496119, 127.027707))
// 0.17778920283873462
console.log(getDistanceFromLatLonInKm(37.497604, 127.026960, 37.494446, 127.028474))
// 0.3756981475693718
console.log(getDistanceFromLatLonInKm(37.497604, 127.026960, 37.492850, 127.029220))
// 0.5649719905623937