PHP to calculate the distance between two coordinates


PHP Code to Calculate Distance Between Two Coordinates

<?php

// Function to calculate the distance between two coordinates
function distance($lat1, $lon1, $lat2, $lon2) {

  // Convert degrees to radians
  $lat1 = deg2rad($lat1);
  $lon1 = deg2rad($lon1);
  $lat2 = deg2rad($lat2);
  $lon2 = deg2rad($lon2);

  // Calculate the difference between the two latitudes and longitudes
  $lat_diff = $lat2 - $lat1;
  $lon_diff = $lon2 - $lon1;

  // Calculate the Haversine formula
  $a = pow(sin($lat_diff / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($lon_diff / 2), 2);
  $c = 2 * asin(sqrt($a));
  $earth_radius = 6371;  // Earth's radius in kilometers

  // Calculate the distance in kilometers
  $distance = $earth_radius * $c;

  // Return the distance in kilometers
  return $distance;
}

// Example usage
$lat1 = 37.7749;
$lon1 = -122.4194;
$lat2 = 37.7868;
$lon2 = -122.4006;

// Calculate the distance in kilometers
$distance = distance($lat1, $lon1, $lat2, $lon2);

// Print the distance
echo "The distance between the two coordinates is: $distance kilometers";

?>

Explanation

The code provided is a PHP function that calculates the distance between two coordinates using the Haversine formula, which is accurate for distances up to several thousand kilometers.

The function takes four parameters:

  • $lat1 and $lon1: The latitude and longitude of the first coordinate.
  • $lat2 and $lon2: The latitude and longitude of the second coordinate.

The function first converts the degrees to radians, then calculates the difference between the two latitudes and longitudes. It then uses the Haversine formula to calculate the distance, which is the arc length between the two points on a sphere. The Earth’s radius is used to convert the distance from radians to kilometers.

Finally, the function returns the distance in kilometers.

How to Implement

To implement this code, you can simply copy and paste it into your PHP file. You will need to replace the example latitude and longitude values with the actual values for the coordinates you want to calculate the distance between.

Once you have implemented the code, you can call the distance() function to calculate the distance between two coordinates. The function will return the distance in kilometers.

Conclusion

The code provided is a simple and efficient way to calculate the distance between two coordinates. It is accurate for distances up to several thousand kilometers. You can use this code to calculate the distance between any two points on the Earth’s surface.