Calculate distance between two points in PHP

With the following PHP function you can calculate the distance between two locations knowing their latitudes and longitudes.

Its use is really useful if you are creating web applications with geolocation services like Google Maps.

Also, as the second input parameter you can indicate the unit in which you want the distance, be it kilometers, miles or nautical miles indicating ‘K’, ‘M’ and ‘N’ respectively.

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;
      }
}

Content

  • Examples of use to calculate the distance between two coordinates
  • Conclusion of calculating distance between coordinates in PHP

Examples of use to calculate the distance between two coordinates

Here are some examples of using the function and with the different units of measure.

$punto1 = [32.9697, -96.80322];
$punto2 = [29.46786, -98.53506];
//para millas
echo distance($punto1[0], $punto1[1], $punto2[0], $punto2[1], "M") . " Millas<br>";
//para kilómetros
echo distance($punto1[0], $punto1[1], $punto2[0], $punto2[1], "K") . " Kilómetros<br>";
//para millas náuticas
echo distance($punto1[0], $punto1[1], $punto2[0], $punto2[1], "N") . " Millas náuticas<br>";

Conclusion of calculating distance between coordinates in PHP

I hope this PHP snippet has helped you. I commonly use it for certain developments for online stores in which, for example, I want to show the closest stores to a user who shares their location.

Finally, if you found it useful (I hope so :D), I would appreciate it if you share it or give it to like to support the creation of more articles of this type.

Leave a Reply