<?php /** * Calculate the great-circle distance between two points using the Haversine formula. * * @param float $lat1 Latitude of the first point. * @param float $lon1 Longitude of the first point. * @param float $lat2 Latitude of the second point. * @param float $lon2 Longitude of the second point. * @param bool $inMiles If true, the distance will be returned in miles; otherwise, in kilometers. * @return float Distance between the two points. */ function haversineDistance($lat1, $lon1, $lat2, $lon2, $inMiles = false) { // Earth radius in kilometers. For miles, you could use 3958.8. $earthRadius = $inMiles ? 3958.8 : 6371.0; // Convert degrees to radians. $lat1 = deg2rad($lat1); $lon1 = deg2rad($lon1); $lat2 = deg2rad($lat2); $lon2 = deg2rad($lon2); // Haversine formula $dLat = $lat2 - $lat1; // Delta latitude $dLon = $lon2 - $lon1; // Delta longitude $a = sin($dLat / 2) * sin($dLat / 2) + cos($lat1) * cos($lat2) * sin($dLon / 2) * sin($dLon / 2); $c = 2 * atan2(sqrt($a), sqrt(1 - $a)); // Calculate the distance $distance = $earthRadius * $c; return $distance; } // Example usage $lat1 = 40.7128; // New York City latitude $lon1 = -74.0060; // New York City longitude $lat2 = 34.0522; // Los Angeles latitude $lon2 = -118.2437; // Los Angeles longitude echo "Distance in kilometers: " . haversineDistance($lat1, $lon1, $lat2, $lon2) . " km\n"; echo "Distance in miles: " . haversineDistance($lat1, $lon1, $lat2, $lon2, true) . " miles\n"; ?>