PHP Calculate Distance between 2 Longitude / Latitude Points

///PHP Calculate Distance between 2 Longitude / Latitude Points

PHP Calculate Distance between 2 Longitude / Latitude Points

Geo-location is becoming more and more popular as time passes and technology supports it better more so as there is plenty of free resources to help you get the data you need to be more GEO centric with your users. However sometimes you want to give a range from point A to point B and this is one way you can do it.\r\n\r\nYou can do the calculation in this function to return Miles (default), Nautical Miles, or Kilometers just enter the longitude/latitude of point A and do the same for point B and your good to go.\r\n\r\n
\r\nfunction distance($lat1, $lon1, $lat2, $lon2, $unit) { \r\n	$theta = $lon1 - $lon2; \r\n	$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); \r\n	$dist = acos($dist); \r\n	$dist = rad2deg($dist); \r\n	$miles = $dist * 60 * 1.1515;\r\n	$unit = strtoupper($unit);\r\n\r\n	if($unit == "K")\r\n	{\r\n		return ($miles * 1.609344); \r\n	}\r\n	elseif($unit == "N") {\r\n		return ($miles * 0.8684);\r\n	}\r\n	else\r\n	{\r\n		return $miles;\r\n	}\r\n}\r\necho distance(32.9697, -96.80322, 29.46786, -98.53506, "m") . " miles
";\r\necho distance(32.9697, -96.80322, 29.46786, -98.53506, "k") . " kilometers
";\r\necho distance(32.9697, -96.80322, 29.46786, -98.53506, "n") . " nautical miles
By | 2014-01-05T10:23:04+00:00 March 8th, 2012|Code, PHP|1 Comment

About the Author:

Not much to know about me, I'm a 35+ year old coder, geek, gamer..

One Comment

  1. Chris September 26, 2012 at 6:40 pm

    Thank you! Exactly what I was looking for!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: