Source Code:
(back to article)
<?php /** * Calculate the Haversine distance between two points on the Earth's surface * * @param float $lat1 The latitude of the first point * @param float $lon1 The longitude of the first point * @param float $lat2 The latitude of the second point * @param float $lon2 The longitude of the second point * @return float The distance between the two points, in kilometers */ function haversine_distance($lat1, $lon1, $lat2, $lon2) { $radius = 6371; // Earth's radius in kilometers // Calculate the differences in latitude and longitude $delta_lat = $lat2 - $lat1; $delta_lon = $lon2 - $lon1; // Calculate the central angles between the two points $alpha = $delta_lat / 2; $beta = $delta_lon / 2; // Use the Haversine formula to calculate the distance $a = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin(deg2rad($beta)) * sin(deg2rad($beta)); $c = asin(min(1, sqrt($a))); $distance = 2 * $radius * $c; // Round the distance to four decimal places $distance = round($distance, 4); return $distance; } // Sample usage $lat1 = 40.712776; $lon1 = -74.005974; $lat2 = 51.507351; $lon2 = -0.127758; $distance = haversine_distance($lat1, $lon1, $lat2, $lon2); echo "The distance between ($lat1, $lon1) and ($lat2, $lon2) is $distance km.";
Result:
Report an issue