Now that you know how to draw maps, and set markers, let's do some "map math." Let's compute
the distance between two points on the map. We'll reference the two points by their
latitude and longitude, like this $(lat_1,lng_1)$ and $(lat_2,lng_2)$.

To start, let's use Los Angeles (34.1,-118.25) and New York (40.7,-74.02).

Next, you'll need the radius of the earth (in kilometers), which is 6,371 km. To find a distance, compute:

- $\Delta lat=lat_2-lat_1$ and $\Delta lng=lng_2-lng_1$.
- $a=\sin(\Delta lat/2)^2+\cos(lat_1)\cos(lat_2)\sin(\Delta lng/2)^2$.
- $c=2\tan^{-1}(\frac{\sqrt{a}}{\sqrt{1-a}})$
- The distance $d$ will be $d=R\times c$.

Remember, your latitude,longitude angles must all be in radians (radians=degrees$\times\pi/180$). As a check, the LA-NY distance is about 2,445 miles or 3,934 km.

Make a nice map application here, that accepts your two locations as easy-to-change variables, draws markers at both points, then displays the distance.

Type your code here:

See your results here:

This code should at least get you started.
Dismiss.

Does your code work? Want to run it on your iPhone?

Here's your code:

- Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.
- Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into
this page
- Then click the "Use on iPhone" button that you'll see.