How to calculate the distance between two latitude-longitude points in PHP

1 Answer

0 votes
// ------------------------------------------------------------
// Convert degrees to radians
// ------------------------------------------------------------
function degToRad(float $deg): float {
    return $deg * M_PI / 180.0;
}

// ------------------------------------------------------------
// Compute the great-circle distance between two points on Earth
// using the Haversine formula.
// lat1, lon1, lat2, lon2 are in degrees.
// The result is returned in kilometers.
// ------------------------------------------------------------
function haversine(float $lat1, float $lon1, float $lat2, float $lon2): float {

    // Earth's mean radius in kilometers
    $R = 6371.0;

    // Convert all angles to radians
    $rlat1 = degToRad($lat1);
    $rlon1 = degToRad($lon1);
    $rlat2 = degToRad($lat2);
    $rlon2 = degToRad($lon2);

    // Differences
    $dlat = $rlat2 - $rlat1;
    $dlon = $rlon2 - $rlon1;

    // Haversine formula
    // a is the Haversine of the central angle between the two points.
    $a = sin($dlat / 2) * sin($dlat / 2) +
         cos($rlat1) * cos($rlat2) *
         sin($dlon / 2) * sin($dlon / 2);

    // c is the central angle between the two points on the Earth’s surface.
    $c = 2 * asin(sqrt($a));

    // Final distance
    return $R * $c;
}

// ------------------------------------------------------------
// Main 
// ------------------------------------------------------------

// Example coordinates:
// Austin, Texas
$lat1 = 30.2672;
$lon1 = -97.7431;

// Houston, Texas
$lat2 = 29.7604;
$lon2 = -95.3698;

$distanceKm = haversine($lat1, $lon1, $lat2, $lon2);

// Convert kilometers to miles
$distanceMiles = $distanceKm * 0.621371;

echo "Distance: " . number_format($distanceKm, 3) . " km\n";
echo "Distance: " . number_format($distanceMiles, 3) . " miles\n";



/*
run:

Distance: 235.352 km
Distance: 146.241 miles

*/

 



answered Aug 7 by avibootz
edited Aug 7 by avibootz

Related questions

...