PHP: Calculate Distance Between Two Coordinates


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:

function distance($point1, $point2)
{
    $EarthRadiusMeters = 6378137.0; // meters
    $dLat = ($point2[0] - $point1[0]) * pi() / 180;
    $dLon = ($point2[1] - $point1[1]) * pi() / 180;
    $a = sin($dLat / 2) * sin($dLat / 2) + cos($point1[0] * pi() / 180) * cos($point2[0] * pi() / 180) *
        sin($dLon / 2) * sin($dLon / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    return $EarthRadiusMeters * $c;
}

Example:

$point1 = array(32.9697, -96.80322);
$point2 = array(29.46786, -98.53506);

echo distance($point1,$point2);

Result:
423232.85930123

Note: Result as meters

Ellipsoidal parameters:

Name           Major axis, a (km)    Flattening (f)
WGS84          6378.13700	   1/298.257223563
GRS80/NAD83    6378.13700	   1/298.257222101
WGS66          6378.145            1/298.25
GRS67/IAU68    6378.16000          1/298.2472
WGS72          6378.135            1/298.26
Krasovsky      6378.245            1/298.3
Clarke66/NAD27 6378.2064           1/294.9786982138

Image copyright: movable-type.co.uk

Leave a Reply