Calculate distance between two latitude and longitude in PHP

Calculating Distance between two points is very simple using latitude and longitude of both points.

The haversine formula determines the great-circle distance (It is not a driving distance) between two points on a sphere given their longitudes and latitudes.

If you want to calculate Driving Distance between two points then you can do that with Google API

function haversineGreatCircleDistance(
  $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $radius = 6371000)
{
  // 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;
}

You will get the distance in the same unit as you pass in with the parameter $radius. The default value is 6371000 meters so the result will be in [meter] too. To get the result in miles, you could e.g. pass 3959 miles as $radius and the result would be in [mi].

function haversineGreatCircleDistance(
  $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $unit)
{
  // 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)));
  $Miles = $angle * 6371000;
  $unit = strtoupper($unit);

    if ($unit == "K") {
      return ($Miles * 1.609344);
    } else if ($unit == "N") {
      return ($Miles * 0.8684);
    } else {
      return $Miles;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *