2012-02-01 35 views
3

Hy!使用什么公式来计算小距离

我需要计算2个GPS点之间的距离。

我看过这个问题Formulas to Calculate Geo Proximity但我的英文太糟糕了。

我的问题是,2点是至多1公里外。 我需要,因为小的距离

最excatly公式在PHP或伪代码中的例子将是巨大的

+0

如果你需要最准确的公式,因为它是基于一个椭球而非球体 – 2012-02-01 13:54:26

回答

3

this page。它包含各种编程语言的great-circle distance计算功能。

在PHP:

function getDistance($latitude1, $longitude1, $latitude2, $longitude2) { 
    $earth_radius = 6371; // In the unit you want the result in. 

    $dLat = deg2rad($latitude2 - $latitude1); 
    $dLon = deg2rad($longitude2 - $longitude1); 

    $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($dLon/2) * sin($dLon/2); 
    $c = 2 * asin(sqrt($a)); 
    $d = $earth_radius * $c; 

    return $d; 
} 
+0

你看这个文章http://gis.stackexchange.com使用Vincenty/questions/4906/why-is-law-of-cosines-more-preferred-have-haversine-when-calculating-distance-b – user547995 2012-02-01 13:56:53

+0

它有什么问题呢? – 2012-02-01 13:59:53

0
function spherical_law_of_cosines($lat_1, $lon_1, $lat_2, $lon_2, $unit = 'mi') 
{ 
    $distance = (3956 * acos(cos(deg2rad($lat_1)) * cos(deg2rad($lat_2)) * cos(deg2rad($lon_2) - deg2rad($lon_1)) + sin(deg2rad($lat_1)) * sin(deg2rad($lat_2)))); 

    if(strcasecmp($unit, 'mi') == 0 OR strcasecmp($unit, 'miles') == 0) 
    { 
     return $distance; 
    } 

    if(strcasecmp($unit, 'km') == 0 OR strcasecmp($unit, 'kilometres') == 0 OR strcasecmp($unit, 'kilometers') == 0) 
    { 
     return 1.609344 * $distance; 
    } 

    if(strcasecmp($unit, 'm') == 0 OR strcasecmp($unit, 'metres') == 0 OR strcasecmp($unit, 'meters') == 0 
    ) 
    { 
     return 1.609344 * 1000 * $distance; 
    } 

    if(strcasecmp($unit, 'y') == 0 OR strcasecmp($unit, 'yards') == 0) 
    { 
     return 1760 * $distance; 
    } 

    if(strcasecmp($unit, 'ft') == 0 OR strcasecmp($unit, 'feet') == 0) 
    { 
     return 1760 * 3 * $distance; 
    } 

    return $distance; 
}