Skip to content

Instantly share code, notes, and snippets.

@ericjames
Last active April 30, 2018 15:36
Show Gist options
  • Save ericjames/ac9256872a201dda4659d71a99c0b2f7 to your computer and use it in GitHub Desktop.
Save ericjames/ac9256872a201dda4659d71a99c0b2f7 to your computer and use it in GitHub Desktop.
PHP - Distance Between Two Coordinate Sets (Triangle Distance and Earth Distance)
<?php
echo triangleDistance(44.977840, -93.258358, 44.973551, -93.265175);
echo "<br />";
echo "<br />";
echo earthDistance(44.977840, -93.258358, 44.973551, -93.265175);
function triangleDistance($startLatitude, $startLongitude, $endLatitude, $endLongitude)
{
$kmPerLat = 111.000;
function getKmPerLongAtLat($lat) {
$DE2RA = 0.01745329252;
$lat *= $DE2RA;
return 111.321 * cos($lat);
}
$theta_lat = abs($startLatitude - $endLatitude);
$theta_long = abs($startLongitude - $endLongitude);
$dist_lat = $theta_lat * $kmPerLat;
$dist_long = $theta_long * getKmPerLongAtLat($startLatitude);
$km = $dist_lat + $dist_long;
// Convert to Kilometeres
$miles = $km * 0.621371;
return $km;
}
$KM_PER_MILE = 1.609344;
function earthDistance($startLatitude, $startLongitude, $endLatitude, $endLongitude)
{
$theta = $startLongitude - $endLongitude;
$dist = sin(deg2rad($startLatitude)) * sin(deg2rad($endLatitude)) + cos(deg2rad($startLatitude)) * cos(deg2rad($endLatitude)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$distance = $miles * 1.609344;
return $distance;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment