Saturday, June 23, 2012

Find the distance between two GPS coordinates using PHP

I've been working on a few mobile applications lately that need to find the distance between two GPS coordinates (usually, the local user of the application and others who may or may not be within a certain distance of the local user). Since most of my mobile apps are built on top of Phonegap, I use a PHP script on the remote server to calculate the distances.

For a while now, I've been using a really cluncky method that was usually off by several hundred (and once or twice, at least a thousand) feet and I've been searching for a better way to do it. Thanks to this blog entry, I now have that better way.

Anyone even remotely familiar with PHP should be able to understand the code below and modify it for their own purposes. I'm sharing it because I hope it saves someone a bit of time.

$earth_radius = 3960.00; # in miles
$lat_1 = "47.117828";
$lon_1 = "-88.545625";
$lat_2 = "47.122223";
$lon_2 = "-88.568781";
$delta_lat = $lat_2 - $lat_1 ;
$delta_lon = $lon_2 - $lon_1 ;
# Spherical Law of Cosines
function distance_slc($lat1, $lon1, $lat2, $lon2) {
  global $earth_radius;
  global $delta_lat;
  global $delta_lon;
  $distance  = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($delta_lon)) ;
  $distance  = acos($distance);
  $distance  = rad2deg($distance);
  $distance  = $distance * 60 * 1.1515;
  $distance  = round($distance, 4);
  return $distance;

# Example Usage
$myDistance = distance_slc($lat_1, $lon_1, $lat_2, $lon_2);

No comments: