Pawan Kumawat

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

WooCommerce: Display Regular & Sale Price @ Cart Table

Learn how to enhance your WooCommerce cart table by displaying both the regular and sale prices. Implement this functionality using WordPress hooks and filters to provide clear and appealing pricing information to your customers, encouraging sales and improving the shopping experience.

How to hide particular category product on shop

To hide a particular category on the shop page using the `woocommerce_product_query` hook, you can modify the query parameters to exclude the category you want to hide. This approach allows you to customize the product query directly without modifying the main query.