# How to calculate the distance between 2 locations using PHP?

This tutorial will demonstrate how to use PHP to get the distance between two geolocated sites using latitude and longitude. The Spherical Law of Cosines, which use trigonometry to calculate the curvature of the planet, is used in this distance computation to precisely calculate the distances on Earth.

<?php

function distance(\$lat1, \$lon1, \$lat2, \$lon2, \$unit) {

if ((\$lat1 == \$lat2) && (\$lon1 == \$lon2)) {

return 0;

}

else {

\$theta = \$lon1 - \$lon2;

\$dist = acos(\$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;

}

}

}

echo distance(32.9697, -96.80322, 29.46786, -98.53506, "M") . " Miles<br>";

echo distance(32.9697, -96.80322, 29.46786, -98.53506, "K") . " Kilometers<br>";

echo distance(32.9697, -96.80322, 29.46786, -98.53506, "N") . " Nautical Miles<br>";

?>

The distance function is created by the code above and measures the separation between two points. It suggests the straightforward spherical law of cosines, which provides accurate findings down to distances as tiny as a few meters on the surface of the Earth. The formula for the spherical law of cosines is used by the distance function.