Determine the Distance Between Two Locations Using PHP

Html JavaScript Jquery PHP PHP Debugging Theme Customization Theme Development WordPress Code Snippets

Determine the Distance Between Two Locations Using PHP Tutorial/Guide

Determine the Distance Between Two Locations Using PHP

To measure the distance between two points on the globe, you can use the Haversine formula. This calculation factors in the Earth's curvature for accurate results. PHP Code to Calculate Distance Below is a PHP function to compute the distance between two geographical locations based on their latitude and longitude:

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 Here’s an example using the coordinates of Los Angeles and New York to calculate the distance between these cities:

// Coordinates for Los Angeles
$lat1 = 34.0522; $lon1 = -118.2437;

// Coordinates for New York City
$lat2 = 40.7128; $lon2 = -74.0060;

// Calculate distance
$distance_km = haversine_distance($lat1, $lon1, $lat2, $lon2, 'km');
$distance_miles = haversine_distance($lat1, $lon1, $lat2, $lon2, 'miles');

// Output result
echo "Distance: " . $distance_km . " km (" . $distance_miles . " miles).";

Important Considerations While the Haversine formula is effective for most practical purposes, it does assume a spherical Earth, leading to slight inaccuracies for long distances.  

💡 Have a Coding Problem?

Search our archives or reach out to our team for solutions and expert advice.