Skip to content

Instantly share code, notes, and snippets.

@ricardoaugusto
Last active May 7, 2016 13:46
Show Gist options
  • Save ricardoaugusto/d3f91d93b9239c16a9c934dfc94cee66 to your computer and use it in GitHub Desktop.
Save ricardoaugusto/d3f91d93b9239c16a9c934dfc94cee66 to your computer and use it in GitHub Desktop.
Haversine Distance between two points ( latitude, longitude )
<?php
/**
* Distance between two points
*
* @param float $lat1 Latitude 1
* @param float $lng1 Longitude 1
* @param float $lat2 Latitude 2
* @param float $lng2 Longitude 2
* @param string $unit [mi|km] miles|kilometers
*
* @return float distance in mi|km. Default is miles.
*/
function harversineDistance($lat1, $lng1, $lat2, $lng2, $unit = 'mi')
{
$latd = deg2rad($lat2 - $lat1);
$lngd = deg2rad($lng2 - $lng1);
$a = sin($latd / 2) * sin($latd / 2) +
cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
sin($lngd / 2) * sin($lngd / 2);
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
$radius = ( $unit === 'km' ) ? 6371.009 : 3958.761; // miles
return round($radius * $c, 3);
}
@ricardoaugusto
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment