ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 좌표 최단거리 검색
    IT, 프로그래밍/Javascript 2018. 8. 3. 22:34

    두 좌표간의 직선 거리를 구하기 위한 함수이며, 지도 API 등에 활용하면 될 듯 하다.


    사용해 본 결과 상당히 정확했음.


    1) prototype 사용

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
     function calculateDistance(lat1, lon1, lat2, lon2) {
              var R = 6371// km
              var dLat = (lat2-lat1).toRad();
              var dLon = (lon2-lon1).toRad(); 
              var a = Math.sin(dLat/2* Math.sin(dLat/2+
                      Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * 
                      Math.sin(dLon/2* Math.sin(dLon/2); 
              var c = * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
              var d = R * c;
              return d;
            } 
         
     
              Number.prototype.toRad = function() {
             return this * Math.PI / 180;
             
           } 
    cs




    2) prototype 미사용



    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
              function toRad(value){
                 
                 return value * Math.PI / 180;
                 
             }
            
     
            function calculateDistance(lat1, lon1, lat2, lon2) {
                  var R = 6371// km
                  var dLat = toRad(lat2-lat1);
                  var dLon = toRad(lon2-lon1); 
                  var a = Math.sin(dLat/2* Math.sin(dLat/2+ Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon/2* Math.sin(dLon/2); 
                  var c = * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
                  var d = R * c;
                  return d;
                } 
    cs


    출처 : https://stackoverflow.com/questions/5260423/torad-javascript-function-throwing-error/10459202

    http://www.movable-type.co.uk/scripts/latlong.html

Designed by Tistory.