Calculate the Distance Between Two Coordinates in PHP

Sometimes you search the web for some obscure problem you need to solve, like calculating the distance between two points, thinking that you’ll for sure never need this ever again. This, my friends, is not one of those examples. While I thought I’d never need this I have come back to this helpful function time and time again. Below is a helpful function that takes in two coordinates and returns the distance. Let’s break this down.

private function distanceGeoPoints($lat1, $long1, $lat2, $long2) {
    define('EARTH_RADIUS', 3958.75);    // in miles

    $dLat = deg2rad($lat2-$lat1);
    $dLng = deg2rad($long2-$long1);

    $a = sin($dLat/2) * sin($dLat/2) +
         cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
         sin($dLng/2) * sin($dLng/2);

    $c = 2 * atan2(sqrt($a), sqrt(1-$a));
    $dist = EARTH_RADIUS * $c;

    return $dist;
}

The first line inside this function is defining a constant for the radius of the Earth. This is important for a couple reasons: the Earth radius is (relatively) constant so we don’t want to run the risk of accidentally assigning this some other value, and 2) the units you put for this radius will also tell you what units you’ll get your resulting return in as well. So, if you want miles between points, use miles. If you want feet, use feet (20902231.64). A simple Google conversion should help you here.

Next we need to convert these coordinates which are in degrees into radians. We can see that we’re taking the second latitude and subtracting the first and the same with the longitude.

Note: don’t name your longitude variables as “long” because in many systems that’s a reserved keyword. In general it’s bad practice.

I won’t get into the somewhat complicated math that happens next but basically we’re taking the various conversions and coordinates we already have and performing geometric arithmetic to them in the form of sine and cosine and doing some other additions and multiplications and such. From this we come up with $a.

Next we do some more geometric arithmetic in the form of an arc tangent and some square roots involving $a which gives us $c. Then all we have to do is multiply $c with the EARTH_RADIUS constant we defined before to get our distance.

Pin It

You must be logged in to post a comment.