# How to compute distance between 2 GPS points?

When working on projects involving geographical calculations, such as determining the direct distance between two airports on a global scale, developers often seek efficient methods to compute such distances accurately. One common approach involves utilizing algorithms derived from the Great Circle distance method, which considers the curvature of the Earth’s surface.

In this article, we explore a PHP implementation of this method and propose two simplifications to enhance its efficiency and readability.

## Introduction

In one of my projects, I was looking for a simple way to compute the direct distance between 2 arbitrary airports in the world.

I was looking for a way to measure the distance between 2 GPS points. Naturally, there are several ways to compute such distances.

After research, I found that many people use algorithms derived from the Great circle distance method [wiki].

Here is a PHP code:

``````/**
* Great Circle distance algorithm
*
* Notes:
* - South and West locations are negative, North and East are positive.
* - Automatically transfer degrees to radians
* - https://en.wikipedia.org/wiki/Great-circle_distance
*
* @param lat1 - latitude of the first point on the sphere
* @param lon1 - longitude of the first point on the sphere
* @param lat2 - latitude of the second point on the sphere
* @param lon2 - longitude of the second point on the sphere
* @param unit - units for output (miles, kilometers, nautical miles)
* @return - distance in desired distance units
*
*/
function GreatCircleDistance(\$lat1, \$lon1, \$lat2, \$lon2, \$unit) {
\$theta = \$lon1 - \$lon2;
\$dist = acos(\$dist);
\$miles = \$dist * 60 * 1.1515;
\$unit = strtoupper(\$unit);

switch (\$unit) {
case 'MI':
return \$miles;
break;
case 'KM':
return (\$miles * 1.609344);
break;
case 'NM':
return (\$miles * 0.8684);
break;
}
}``````

There are two simple corrections to simplify this algorithm.

First by padding all the sub-results into one big equation.

Second, by ensuring the input units will always be the same (using numbers instead of Strings), the `strtoupper()` function can be removed.

## Conclusion

In conclusion, by streamlining the implementation of the Great Circle distance algorithm in PHP, developers can achieve enhanced efficiency and readability in their geographical computations. These simplifications make the code more concise and ensure consistent input handling, contributing to a smoother development process.

This entry was posted in Solutions and tagged , , , , , , , . Bookmark the permalink.

This site uses Akismet to reduce spam. Learn how your comment data is processed.