## Posted By

tylerhall on 04/24/07

## Who likes this?

64 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.

`function distance(\$lat1, \$lng1, \$lat2, \$lng2, \$miles = true){	\$pi80 = M_PI / 180;	\$lat1 *= \$pi80;	\$lng1 *= \$pi80;	\$lat2 *= \$pi80;	\$lng2 *= \$pi80; 	\$r = 6372.797; // mean radius of Earth in km	\$dlat = \$lat2 - \$lat1;	\$dlng = \$lng2 - \$lng1;	\$a = sin(\$dlat / 2) * sin(\$dlat / 2) + cos(\$lat1) * cos(\$lat2) * sin(\$dlng / 2) * sin(\$dlng / 2);	\$c = 2 * atan2(sqrt(\$a), sqrt(1 - \$a));	\$km = \$r * \$c; 	return (\$miles ? (\$km * 0.621371192) : \$km);}`

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

Posted By: dorinebaker on April 16, 2018

very useful information. I also had difficulties with this. Tell me please, do you write technical documentation if you don't it - devmyresume helps you.