PHP: Haversine Formula function.

This is a PHP function that implements the Haversine Formula; an equation that essentially measures the distance between two points on a sphere (in this case, that sphere is the planet that we live on). This is sometimes referred to as the “as the crow flies” distance.

The function is pretty simple to use. It takes in four parameters:

  1. The Latitude value of POINT A.
  2. The Longitude value of POINT A.
  3. The Latitude value of POINT B.
  4. The Longitude value of POINT B.

Please note that this PHP function returns the distance in kilometres. If you want to return the distance in miles, simply change the earth radius variable from 6371 to 3959 (the radius of the earth in miles):

<?php

function getDistance($latitude1, $longitude1, $latitude2, $longitude2) {
    
    $earth_radius = 6371;

    $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;
    
}

Please note that the Harversine Formula has two drawbacks:

  • The earth is not a perfect sphere, which means that the results can be a little off. However; the accuracy is typically good enough for most use cases.
  • When we think of distance, we typically think of road distance. The problem with the Haversine Formula is that it will give you a geographical distance that will cut through water, fields and mountains. i.e. “As the crow flies”. You might want to use the Google Distance API if your application is attempting to provide users with the nearest location, so to speak.