Distance Calculator
How it Works
Input Options
The program supports the following input formats:
- Place Name, e.g. Jakarta / Indonesia
- Country Code, e.g. ID
- Signed decimal, e.g. -6.17, 106.82
- Degrees + direction, e.g. 6.17S, 106.82E
- Degrees, minutes + direction, e.g. 6°10'S, 106°49'E
- Degrees, minutes, seconds + direction, e.g. 6°10'21'S, 106°49'44'E
In each of the 'from' and 'to' fields independently.
If a string input is detected, the Levenshtein distance metric is used to display the closest matches in a drop-down selection menu from a database of countries and capitals. The drop-down is built from scratch with divs that always display the closest matches and are hidden if empty. It is navigated using 'keydown' event listeners.
Distance Calculation
Coordinates are scraped from each input field, from either the text itself or from a database of city coordinates downloaded from Techslides, or the field is coloured red to indicate that coordinates could not be extracted.
The following simple trig functions are used over the more popular haversine formula, which is only significantly more accurate for distances of tens of meters or closer:
cos-1 ( cosφ1×cosφ2×cos(λ2-λ1) + sinφ1×sinφ2 )
Mapping Results
The world map used is a Winkel-Tripel projection, for which the geographic to cartesian coordinate conversion formulae are:
x = ax + bx( λ/π + cosφ×sin(λ/2)/sincα )
y = ay + by( φ + sinφ/sincα )
Where α = cos-1( cosφ×cos(λ/2) ) and ax, bx, ay, by are constants.
The line between the two locations is the shortest great-circle arc connecting them (or any arc in the case of antipodes) and is drawn in sections, dot-to-dot, connecting the normalisations of vectors lying between the points in 3D space. This requires a change from geographic to 3D Cartesian coordinates to find the vectors, followed by a change back to geographic, then finally a change to 2D Cartesian for plotting on the map.
Length of Code
There are around 130 lines of HTML and 70 of CSS. The core functionality (coordinate scraping, distance calculation, presentation) is 250 lines of Javascript, just over half of which is devoted to translating user-friendly data to and from raw coordinates for calculations, and the search features take around another 140 lines.
The database of Countries, Capital Cites and their coordinates is just under two thirds of the total page size.