How to calculate the distance between two points in PHP

Snippet

There are many applications in which it is useful to know the distance between two latitude and longitude coordinates. Here is a PHP function that makes the calculations easier.

downloadcopy
<?php
function calcDistance($departureLatitude, $departureLongitude, $arrivalLatitude, $arrivalLongitude){
    $a1 = deg2rad($arrivalLatitude);
    $b1 = deg2rad($arrivalLongitude);
    $a2 = deg2rad($departureLatitude);
    $b2 = deg2rad($departureLongitude);
    $res = 2 * asin(sqrt(pow(sin(($a2 - $a1) / 2), 2) + cos($a2) * cos($a1) * pow(sin(($b2 - $b1) / 2), 2)));
    return 6371008 * $res;
}

// Here’s an example of the function in action, using two coordinates between New York and London
$point1 = array(40.712772, -74.006058);
$point2 = array(51.509865, -0.118092);
$distance = calcDistance($point1['0'], $point1['1'], $point2['0'], $point2['1']);
echo $distance . ' meters';