Calculate distance between 2 address using latitude and longitude

To calculate the distance between two locations using their latitude and longitude coordinates, you can use the Haversine formula. The Haversine formula is commonly used to calculate the great-circle distance between two points on the surface of a sphere (such as the Earth) given their latitude and longitude.

Here’s a PHP function that implements the Haversine formula to calculate the distance between two sets of latitude and longitude coordinates:

function calculate_distance($lat1, $lon1, $lat2, $lon2, $unit = 'km') {
    $earth_radius = ($unit === 'km') ? 6371.009 : 3958.761; // Earth's radius 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;
}

Usage example:

// Latitude and Longitude of Location 1
$lat1 = 51.5074; // Example latitude for Location 1 (London)
$lon1 = -0.1278; // Example longitude for Location 1 (London)

// Latitude and Longitude of Location 2
$lat2 = 40.7128; // Example latitude for Location 2 (New York)
$lon2 = -74.0060; // Example longitude for Location 2 (New York)

// Calculate distance in kilometers
$distance_km = calculate_distance($lat1, $lon1, $lat2, $lon2, 'km');

// Calculate distance in miles
$distance_miles = calculate_distance($lat1, $lon1, $lat2, $lon2, 'miles');

// Output the results
echo "Distance between London and New York: " . $distance_km . " km (" . $distance_miles . " miles)";

Make sure to replace the example latitude and longitude values with the actual latitude and longitude coordinates of the locations you want to calculate the distance between. The function will return the distance in kilometers or miles, depending on the unit specified.

Keep in mind that the Haversine formula provides an approximation and assumes a perfect sphere for the Earth. In reality, the Earth is not a perfect sphere, but the Haversine formula is accurate enough for most practical purposes involving distances on the Earth’s surface.

Leave a Comment

Your email address will not be published. Required fields are marked *