Calculate Distance Between Two Geographical Points With PHP

16th June 2008 - 2 minutes read time

Use the following function to work out the distance between two geographical points. Geographical points are usually longitude and latitude, in degrees. The first thing to do is to convert these values into radians (using the deg2rad() PHP function) so that we can work with them. The four basic parameters used are the longitude and latitude values for the two points. The optional fifth value is to have the end value returned in miles, rather than kilometres.

  1. function getDistance($a_lat, $a_lng, $b_lat, $b_lng, $mi=false)
  2. {
  3. ($mi ? $radius=6371 : $radius=10253);
  4. $a_lat = deg2rad($a_lat);
  5. $a_lng = deg2rad($a_lng);
  6. $b_lat = deg2rad($b_lat);
  7. $b_lng = deg2rad($b_lng);
  8. if($a_lat==$b_lat && $a_lng==$b_lng){
  9. // two distances are the same
  10. return 0;
  11. }
  12. if ( (sin($b_lat)*sin($a_lat) + cos($b_lat)*cos($a_lat)*cos($b_lng-$a_lng))>1 ) {
  13. return $radius * acos(1);
  14. };
  15. return $radius * acos(sin($b_lat)*sin($a_lat)+cos($b_lat)*cos($a_lat)*cos($b_lng-$a_lng));
  16. }

Here are some examples of the code in action.

  1. echo getDistance(40.995827,-94.370559,63.439031,84.723732); // 8402.1830291634
  2. echo getDistance(-23.782270,134.078645,-23.782626,134.065365); // 1.3518544215203

To print out these results in miles you can set the fifth parameter to be true.

  1. echo getDistance(40.995827,-94.370559,63.439031,84.723732,true); // 13521.830575736
  2. echo getDistance(-23.782270,134.078645,-23.782626,134.065365,true); // 2.175571085206

Add new comment

The content of this field is kept private and will not be shown publicly.