Because the Earth is a sphere (approximately), you cannot just use the flat Pythagorean theorem ($\sqrt{\Delta x^2 + \Delta y^2}$). Instead, the shortest distance between two points across the curved surface of a sphere is along a great circle, calculated using the mathematical Haversine formula:
$$d = 2 R \arcsin\left(\sqrt{\sin^2\left(\frac{\Delta \phi}{2}\right) + \cos(\phi_1)\cos(\phi_2)\sin^2\left(\frac{\Delta \lambda}{2}\right)}\right)$$
where $R \approx 6{,}371\text{ km}$ is Earth's mean radius, $\phi$ represents latitude in radians, and $\lambda$ represents longitude in radians.
We've built this formula directly into CodeByMath:
distance(lat1, lon1, lat2, lon2)
It returns the great-circle distance directly in kilometers!
In this lesson, we will calculate the distance between London, UK ($51.5074^\circ\text{ N}, -0.1278^\circ\text{ W}$) and Tokyo, Japan ($35.6762^\circ\text{ N}, 139.6503^\circ\text{ E}$), plot both cities on our OpenStreetMap, and convert kilometers to miles ($1\text{ km} \approx 0.621371\text{ miles}$).
km = distance(lat1,lon1,lat2,lon2) miles = km * 0.621371
Move the mouse over a dotted box for more information.
Notice how long-distance travel on a sphere curves towards the poles—a path called a great-circle route.
Now you try. Try computing the distance between your hometown and Paris or Sydney!
Type your code here:
See your results here:
To complete this lesson:
1. Look at line 10 where km = 0.
2. Call the built-in function: km = distance(lat1, lon1, lat2, lon2).
3. Click Run to calculate the distance (~9,560 km or ~5,940 miles) and view both cities on the world map!
Share your code
Show a friend, family member, or teacher what you've done!