Calculate Distance Between Two Locations Using Coordinates

Code Snippets Custom Code Snippets Html JavaScript Jquery PHP PHP Development Plugins

Calculate Distance Between Two Locations Using Coordinates Tutorial/Guide

Calculate Distance Between Two Locations Using Coordinates

To determine the shortest distance between two locations, the Haversine formula is commonly used. This method accounts for the Earth's curvature. PHP Code for Distance Calculation Here is a PHP function to calculate the distance between two sets of geographical coordinates using the Haversine formula:

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 is an example to demonstrate how to use the function to calculate the distance between two cities, Los Angeles and New York:

// 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).";

Key Notes This formula assumes the Earth is spherical, which can introduce small errors for longer distances, but it works well for most practical purposes.  

💡 Have a Coding Problem?

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