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.

Categories

Related Blogs

How To Create A Custom Product Tab On Product Page WooCommerce

To create a custom product tab on a WooCommerce product page, you’ll need to use some custom code. WooCommerce provides hooks and filters that allow you to extend and modify its functionality. Below are the steps to create a custom product tab in WooCommerce:

How to log information, warnings, errors In wordpress

To create a custom write_log() function for WordPress, you can use the error_log() function to write messages to the error log. This function will allow you to log information, warnings, errors, or any other messages during development or debugging.