php function to calculate the distance between co-ordinates

Just a little PHP function to calculate the distance between two coordinates. You can specify the units to be returned also.

function distance($lat1, $lon1, $lat2, $lon2, $unit) { 
  $theta = $lon1 - $lon2; 
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * 
    cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
  $dist = acos($dist); 
  $dist = rad2deg($dist); 
  $miles = $dist * 60 * 1.1515;

  $unit = strtoupper($unit);

  if ($unit == "K") {

    return ($miles * 1.609344); 

  } else if ($unit == "N") {
      return ($miles * 0.8684);
  } else {
        return $miles;
  }
}

Usage is:

echo distance(32.9697, -96.80322, 29.46786, -98.53506, "m") . " miles";

Hope that’s of some use to someone. You can co-ordinate it with a function to get the lat-long of a pair of zip codes, and then calculate shipping distance for example.

About Cameron
I'm a final year Computer Science/Information Systems major. Already finished my BA in Politics/Philosophy. I do web and software freelance on the side, while I finish studying. Hoping to be self-employed by the end of my degree, otherwise off into the real-world I go....

3 Responses to php function to calculate the distance between co-ordinates

  1. Robbie says:

    Also very cool. Again, if it’s alright with you I would like to post this in mine.

    Also, I’m looking for fellow PHP developers for my blog. It’s centered on just giving out PHP things. I just started it today when I realized I like finding helpful pieces. Would you be interested?

    – Robbie

  2. Aleksei says:

    Works great !!! on wordpress tks

Leave a comment