Skip to content

Instantly share code, notes, and snippets.

@KaiserWerk
Last active April 30, 2018 13:56
Show Gist options
  • Save KaiserWerk/8cf0af153f268429b23dbc1319e6c363 to your computer and use it in GitHub Desktop.
Save KaiserWerk/8cf0af153f268429b23dbc1319e6c363 to your computer and use it in GitHub Desktop.
PHP Haversine - Calculate the distance between two points considering the curvature of earth (useful for long distances)
<?php
/*
* PHP Haversine - Calculate the distance between two points considering the curvature of earth
* Checkmate, flat-earthers!
*
* The result will be given in km. if you want meters, set $earth_radius to 6371000.
*/
function getDistance($latitude1, $longitude1, $latitude2, $longitude2) {
$earth_radius = 6371; // this is in km so the result will be in km as well
$dLat = deg2rad($latitude2 - $latitude1);
$dLon = deg2rad($longitude2 - $longitude1);
$a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($dLon/2) * sin($dLon/2);
$c = 2 * asin(sqrt($a));
$d = $earth_radius * $c;
return $d;
}
$p1lat = 47.2173788;
$p1lon = 6.7867624;
$p2lat = 51.2073988;
$p2lon = 8.7967620;
echo getDistance($p1lat, $p1lon, $p2lat, $p2lon);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment