[javascript] 두 좌표 사이의 거리를 계산하는 기능

현재 아래 기능을 사용하고 있으며 제대로 작동하지 않습니다. Google지도에 따르면 이 좌표 사이의 거리 (에서 59.3293371,13.4877472~까지 59.3225525,13.4619422)는 2.2킬로미터이며 함수는 1.6킬로미터를 반환합니다 . 이 함수가 올바른 거리를 반환하도록하려면 어떻게해야합니까?

function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1);
  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; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}

jsFiddle : http://jsfiddle.net/edgren/gAHJB/



답변

당신이 사용하는 것을 하는 것을 까마귀 파리로 구의 두 점 사이의 거리를 계산 haversine 공식 . 제공 한 Google지도 링크는 직선이 아니기 때문에 거리를 2.2km로 표시합니다.

Wolphram Alpha는 지리적 계산을 수행하는 데 유용한 리소스이며 이며이 두 지점 사이 1.652km 입니다.

주행 거리 대 직선 거리 (빨간색 광산).

까마귀 파일과 같은 직선 거리를 찾고 있다면 함수가 올바르게 작동하는 것입니다. 원하는 거리가 주행 거리 (또는 자전거 거리 또는 대중 교통 거리 또는 도보 거리) 인 경우 매핑 API ( 경우 거리를 포함하여 적절한 경로를 얻으려면 Google 또는 Bing 이 가장 인기있는)를 합니다.

또한 Google Maps API는 구면 거리에 대해 패키지화 된 방법을 제공합니다. google.maps.geometry.spherical 네임 스페이스 (look computeDistanceBetween). 아마도 자신의 것을 굴리는 것보다 낫습니다 (먼저 지구 반경에보다 정확한 값을 사용합니다).

우리들 사이에서 까다롭기 때문에, “직선 거리”라고 말할 때, 실제로 “구면의 직선”을 말하고 있는데, 이것은 실제로 곡선 (즉, 큰 원 거리)입니다.


답변

나는 전에 비슷한 방정식을 작성했다-그것을 테스트하고 1.6 km를 얻었다.

귀하의 Google지도에 DRIVING 거리가 표시되었습니다.

함수는 까마귀가 날아갈 때 계산합니다 (직선 거리).

alert(calcCrow(59.3293371,13.4877472,59.3225525,13.4619422).toFixed(1));



    //This function takes in latitude and longitude of two location and returns the distance between them as the crow flies (in km)
    function calcCrow(lat1, lon1, lat2, lon2)
    {
      var R = 6371; // km
      var dLat = toRad(lat2-lat1);
      var dLon = toRad(lon2-lon1);
      var lat1 = toRad(lat1);
      var lat2 = toRad(lat2);

      var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      var d = R * c;
      return d;
    }

    // Converts numeric degrees to radians
    function toRad(Value)
    {
        return Value * Math.PI / 180;
    }


답변

데릭의 솔루션은 나에게 잘 작동했으며, 단순히 PHP로 변환했습니다. 누군가가 도움이되기를 바랍니다.

function calcCrow($lat1, $lon1, $lat2, $lon2){
        $R = 6371; // km
        $dLat = toRad($lat2-$lat1);
        $dLon = toRad($lon2-$lon1);
        $lat1 = toRad($lat1);
        $lat2 = toRad($lat2);

        $a = sin($dLat/2) * sin($dLat/2) +sin($dLon/2) * sin($dLon/2) * cos($lat1) * cos($lat2);
        $c = 2 * atan2(sqrt($a), sqrt(1-$a));
        $d = $R * $c;
        return $d;
}

// Converts numeric degrees to radians
function toRad($Value)
{
    return $Value * pi() / 180;
}


답변

이 시도. VB.net에 있으며 Javascript로 변환해야합니다. 이 함수는 10 분 단위로 매개 변수를 승인합니다.

    Private Function calculateDistance(ByVal long1 As String, ByVal lat1 As String, ByVal long2 As String, ByVal lat2 As String) As Double
    long1 = Double.Parse(long1)
    lat1 = Double.Parse(lat1)
    long2 = Double.Parse(long2)
    lat2 = Double.Parse(lat2)

    'conversion to radian
    lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0
    long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0
    lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0
    long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0

    ' use to different earth axis length
    Dim a As Double = 6378137.0        ' Earth Major Axis (WGS84)
    Dim b As Double = 6356752.3142     ' Minor Axis
    Dim f As Double = (a - b) / a        ' "Flattening"
    Dim e As Double = 2.0 * f - f * f      ' "Eccentricity"

    Dim beta As Double = (a / Math.Sqrt(1.0 - e * Math.Sin(lat1) * Math.Sin(lat1)))
    Dim cos As Double = Math.Cos(lat1)
    Dim x As Double = beta * cos * Math.Cos(long1)
    Dim y As Double = beta * cos * Math.Sin(long1)
    Dim z As Double = beta * (1 - e) * Math.Sin(lat1)

    beta = (a / Math.Sqrt(1.0 - e * Math.Sin(lat2) * Math.Sin(lat2)))
    cos = Math.Cos(lat2)
    x -= (beta * cos * Math.Cos(long2))
    y -= (beta * cos * Math.Sin(long2))
    z -= (beta * (1 - e) * Math.Sin(lat2))

    Return Math.Sqrt((x * x) + (y * y) + (z * z))
End Function


자바 스크립트에서 변환 된 함수 편집

function calculateDistance(lat1, long1, lat2, long2)
  {

      //radians
      lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0;
      long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0;
      lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0;
      long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0;


      // use to different earth axis length    
      var a = 6378137.0;        // Earth Major Axis (WGS84)    
      var b = 6356752.3142;     // Minor Axis    
      var f = (a-b) / a;        // "Flattening"    
      var e = 2.0*f - f*f;      // "Eccentricity"      

      var beta = (a / Math.sqrt( 1.0 - e * Math.sin( lat1 ) * Math.sin( lat1 )));
      var cos = Math.cos( lat1 );
      var x = beta * cos * Math.cos( long1 );
      var y = beta * cos * Math.sin( long1 );
      var z = beta * ( 1 - e ) * Math.sin( lat1 );

      beta = ( a / Math.sqrt( 1.0 -  e * Math.sin( lat2 ) * Math.sin( lat2 )));
      cos = Math.cos( lat2 );
      x -= (beta * cos * Math.cos( long2 ));
      y -= (beta * cos * Math.sin( long2 ));
      z -= (beta * (1 - e) * Math.sin( lat2 ));

      return (Math.sqrt( (x*x) + (y*y) + (z*z) )/1000);
    }


답변

자바 스크립트에서 두 점 사이의 거리를 계산

function distance(lat1, lon1, lat2, lon2, unit) {
        var radlat1 = Math.PI * lat1/180
        var radlat2 = Math.PI * lat2/180
        var theta = lon1-lon2
        var radtheta = Math.PI * theta/180
        var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        dist = Math.acos(dist)
        dist = dist * 180/Math.PI
        dist = dist * 60 * 1.1515
        if (unit=="K") { dist = dist * 1.609344 }
        if (unit=="N") { dist = dist * 0.8684 }
        return dist
}

자세한 내용은 참조 링크를 참조하십시오.


답변

Haversine 공식을 사용 하여 코드의 소스 :

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::                                                                         :::
//:::  This routine calculates the distance between two points (given the     :::
//:::  latitude/longitude of those points). It is being used to calculate     :::
//:::  the distance between two locations using GeoDataSource (TM) prodducts  :::
//:::                                                                         :::
//:::  Definitions:                                                           :::
//:::    South latitudes are negative, east longitudes are positive           :::
//:::                                                                         :::
//:::  Passed to function:                                                    :::
//:::    lat1, lon1 = Latitude and Longitude of point 1 (in decimal degrees)  :::
//:::    lat2, lon2 = Latitude and Longitude of point 2 (in decimal degrees)  :::
//:::    unit = the unit you desire for results                               :::
//:::           where: 'M' is statute miles (default)                         :::
//:::                  'K' is kilometers                                      :::
//:::                  'N' is nautical miles                                  :::
//:::                                                                         :::
//:::  Worldwide cities and other features databases with latitude longitude  :::
//:::  are available at https://www.geodatasource.com                         :::
//:::                                                                         :::
//:::  For enquiries, please contact sales@geodatasource.com                  :::
//:::                                                                         :::
//:::  Official Web site: https://www.geodatasource.com                       :::
//:::                                                                         :::
//:::               GeoDataSource.com (C) All Rights Reserved 2018            :::
//:::                                                                         :::
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

function distance(lat1, lon1, lat2, lon2, unit) {
    if ((lat1 == lat2) && (lon1 == lon2)) {
        return 0;
    }
    else {
        var radlat1 = Math.PI * lat1/180;
        var radlat2 = Math.PI * lat2/180;
        var theta = lon1-lon2;
        var radtheta = Math.PI * theta/180;
        var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        if (dist > 1) {
            dist = 1;
        }
        dist = Math.acos(dist);
        dist = dist * 180/Math.PI;
        dist = dist * 60 * 1.1515;
        if (unit=="K") { dist = dist * 1.609344 }
        if (unit=="N") { dist = dist * 0.8684 }
        return dist;
    }
}

샘플 코드는 LGPLv3에 따라 라이센스가 부여됩니다.


답변

두 좌표 사이의 거리를 찾는 함수를 작성했습니다. 거리를 미터 단위로 반환합니다.

 function findDistance() {
   var R = 6371e3; // R is earth’s radius
   var lat1 = 23.18489670753479; // starting point lat
   var lat2 = 32.726601;         // ending point lat
   var lon1 = 72.62524545192719; // starting point lon
   var lon2 = 74.857025;         // ending point lon
   var lat1radians = toRadians(lat1);
   var lat2radians = toRadians(lat2);

   var latRadians = toRadians(lat2-lat1);
   var lonRadians = toRadians(lon2-lon1);

   var a = Math.sin(latRadians/2) * Math.sin(latRadians/2) +
        Math.cos(lat1radians) * Math.cos(lat2radians) *
        Math.sin(lonRadians/2) * Math.sin(lonRadians/2);
   var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

   var d = R * c;

   console.log(d)
}

function toRadians(val){
    var PI = 3.1415926535;
    return val / 180.0 * PI;
}