What are some best practices for calculating distances between locations in PHP when implementing a proximity search feature?
When implementing a proximity search feature in PHP, it is important to calculate distances between locations accurately. One common approach is to use the Haversine formula, which takes into account the curvature of the Earth when calculating distances between two points specified by their latitude and longitude coordinates.
function calculateDistance($lat1, $lon1, $lat2, $lon2) {
$earthRadius = 6371; // in kilometers
$dLat = deg2rad($lat2 - $lat1);
$dLon = deg2rad($lon2 - $lon1);
$a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon/2) * sin($dLon/2);
$c = 2 * atan2(sqrt($a), sqrt(1-$a));
$distance = $earthRadius * $c;
return $distance;
}
// Example usage
$distance = calculateDistance(40.7128, -74.0060, 34.0522, -118.2437);
echo "Distance between New York City and Los Angeles is: " . $distance . " km";