Calculating Distance from GPS Coordinates
When working with coordinates, you will often need to determine the distance between two places. Here is how to do it.
For a long time, we used a simple formula spiced up with a magic constant for this:
dist = sqrt( (lat1 - lat2) ^ 2 + (lng1 - lng2) ^ 2 ) * 0.012
where lat1, lat2, lng1, lng2 are the coordinates of the points whose distance we want to determine, and 0.012 is a magic constant that, at our latitudes, adjusts the result so that it gives the distance in kilometers.
Unfortunately, the previous sentence is not entirely true: the result only approximates the real distance, sometimes more closely, sometimes less. It depends on the direction in which the points lie from each other and on the latitude we are at. When we needed a more precise calculation, we had to change the formula.
The problem with the formula is probably obvious to everyone. Unfortunately, we don't live on a flat disc but on a sphere (roughly), so planar geometry and the Pythagorean theorem are not enough – we have to work with spherical geometry. We don't need the straight-line distance between the points (unless you are a mole digging a tunnel). What we are interested in is the distance between the points along the circumference of a circle whose radius is the radius of the Earth.
For this case, you can derive the so-called haversine formula, which can be simplified with only a small error to the following expression:
dist = acos (sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lng1 - lng2) ) * 6371
where lat1, lat2, lng1, lng2 are the coordinates of the points and 6371 is the Earth's radius in km; the result is the distance in kilometers. Note: we assume the calculation is done in degrees. For a calculation in radians, the Earth's radius constant must be adjusted accordingly (to 6371 / 360 * 2 * Pi = 111.19).
Since coordinates are most often given in degrees, they also have to be converted to radians first. The resulting PHP function for calculating the distance is as follows:
function distance($lat1, $lng1, $lat2, $lng2)
{
$theta = $lng1 - $lng2;
$dist = acos(
sin(deg2rad($lat1)) * sin(deg2rad($lat2))
+ cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta))
);
return $dist * 111.19;
}