Search code examples
phpmathmapslatitude-longitudehaversine

PHP: Haversine formula gives HUGE (incorrect) distances


Why does the Haversine formula return HUGE distances ? From the values that I'm passing, the distance should not be more than 1 or 2 kms. But it returns 8,104 kms.

I'm aware this is a recurrent problem with PHP.

Courtesy of the code snippet here :

function haversineGreatCircleDistance(
  $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371)
{
  // convert from degrees to radians
  $latFrom = deg2rad($latitudeFrom);
  $lonFrom = deg2rad($longitudeFrom);
  $latTo = deg2rad($latitudeTo);
  $lonTo = deg2rad($longitudeTo);

  $latDelta = $latTo - $latFrom;
  $lonDelta = $lonTo - $lonFrom;

  $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
    cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
  return $angle * $earthRadius;
}

Solution

  • function haversineGreatCircleDistance(
      $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthMeanRadius = 6371)
    {
        $deltaLatitude = deg2rad($latitudeTo - $latitudeFrom);
        $deltaLongitude = deg2rad($longitudeTo - $longitudeFrom);
        $a = sin($deltaLatitude / 2) * sin($deltaLatitude / 2) +
             cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) *
             sin($deltaLongitude / 2) * sin($deltaLongitude / 2);
        $c = 2 * atan2(sqrt($a), sqrt(1-$a));
        return $earthMeanRadius * $c;
    }
    

    A value of 6371 for the $earthMeanRadius argument (which is the default) is the earth mean radius in kilometres, which means that the returned result will be in kilometres.... if you want miles instead, then call it with an $earthMeanRadius argument value of 3,958; if you want nautical miles, change it to 3440, etc.