How to Compute the Distance Between Two Locations Using Coordinates
When you need to find the distance between two locations, using their geographical coordinates (latitude and longitude) is the most precise method. The Haversine formula is an essential tool for calculating the great-circle distance between two points on Earth. This method helps in determining the distance between two locations on the globe, considering the curvature of the Earth.
PHP Code to Calculate Distance Using the Haversine Formula
Here’s a PHP function that applies the Haversine formula to calculate the distance between two sets of coordinates:
function haversine_distance($lat1, $lon1, $lat2, $lon2, $unit = 'km') { $earth_radius = ($unit === 'km') ? 6371.009 : 3958.761; // Radius of Earth in km or miles $lat1 = deg2rad($lat1); $lon1 = deg2rad($lon1); $lat2 = deg2rad($lat2); $lon2 = deg2rad($lon2); $delta_lat = $lat2 - $lat1; $delta_lon = $lon2 - $lon1; $angle = 2 * asin(sqrt(pow(sin($delta_lat / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($delta_lon / 2), 2))); return $angle * $earth_radius; }
Example Usage
Below is an example that demonstrates how to use the haversine_distance
function to calculate the distance between two locations using their latitude and longitude:
// Location 1 coordinates (Latitude, Longitude) $lat1 = 34.0522; // Example latitude for Los Angeles $lon1 = -118.2437; // Example longitude for Los Angeles // Location 2 coordinates (Latitude, Longitude) $lat2 = 40.7128; // Example latitude for New York City $lon2 = -74.0060; // Example longitude for New York City // Calculate distance in kilometers $distance_km = haversine_distance($lat1, $lon1, $lat2, $lon2, 'km'); // Calculate distance in miles $distance_miles = haversine_distance($lat1, $lon1, $lat2, $lon2, 'miles'); // Display the result echo "The distance between Los Angeles and New York is " . $distance_km . " km (" . $distance_miles . " miles).";
Make sure to substitute the latitude and longitude values in the example with the actual coordinates for the locations you want to measure. The function will return the distance either in kilometers or miles, depending on the unit you choose.
Key Notes
While the Haversine formula is a commonly used method for distance calculation, keep in mind that it assumes the Earth is a perfect sphere. This approximation may introduce slight errors in the calculation for longer distances, especially in locations near the poles. However, for most practical uses, the results from the Haversine formula are sufficiently accurate.