## Posted By

tylerhall on 04/24/07

## Who likes this?

62 people have marked this snippet as a favorite

# Calculate the Distance Between Two Coordinates (latitude, longitude)

/ Published in: PHP

This PHP function calculates the distance between to pairs of latitude longitude coordinates. Returns the distance in miles or kilometers.

1. function distance(\$lat1, \$lng1, \$lat2, \$lng2, \$miles = true)
2. {
3. \$pi80 = M_PI / 180;
4. \$lat1 *= \$pi80;
5. \$lng1 *= \$pi80;
6. \$lat2 *= \$pi80;
7. \$lng2 *= \$pi80;
8.
9. \$r = 6372.797; // mean radius of Earth in km
10. \$dlat = \$lat2 - \$lat1;
11. \$dlng = \$lng2 - \$lng1;
12. \$a = sin(\$dlat / 2) * sin(\$dlat / 2) + cos(\$lat1) * cos(\$lat2) * sin(\$dlng / 2) * sin(\$dlng / 2);
13. \$c = 2 * atan2(sqrt(\$a), sqrt(1 - \$a));
14. \$km = \$r * \$c;
15.
16. return (\$miles ? (\$km * 0.621371192) : \$km);
17. }

Posted By: grkkid on January 17, 2009

great work...tested it with my zipcode database and worked great

Posted By: dougdo on December 4, 2009

Thanks for the function. Was very helpful on a number of my geographic sites to show the distance of nearby points (see example)

Posted By: arucordoba on November 5, 2010

Thanks! Great job!

Posted By: carbonr on March 25, 2012

Thanks, this helped me

Posted By: richpages on August 14, 2012

Awesome, you saved me a lot of time :)

Posted By: apsm on March 13, 2013

Thanks a lot! very good work.

Posted By: juanpa1 on April 24, 2013

Great work! Unfortunately didn't match my query results:

SELECT ((ACOS(SIN(\$lat * PI() / 180) * SIN(lat * PI() / 180) + COS(\$lat * PI() / 180) * COS(lat * PI() / 180) * COS((\$lon - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance FROM members HAVING distance