In one of my projects I was looking for simple way how to compute direct distance between 2 arbitrary airports in the world. Simply, I was looking for a way to measure distance between 2 GPS points. Naturally there exist several ways how to compute such thing. After research I found that many people use algorithms derived from 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 first point on sphere * @param lon1 - longitude of first point on sphere * @param lat2 - latitude of second point on sphere * @param lon2 - longitude of second point on sphere * @param unit - units for output (miles, kilometers, nautical miles) * @return - distance in desired distance units * */ function GCdistance($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); switch ($unit) { case 'MI': return $miles; break; case 'KM': return ($miles * 1.609344); break; case 'NM': return ($miles * 0.8684); break; } }
There are 2 simple corrections how to simplifie this algorithm more. First by padding all the sub-results into one big equation. And second, by ensuring the the input units will be always the same (using numbers instead of Strings) strtoupper() function can be removed.