Lesson goal: Finding distances on a map

Previous: Draw with markers | Home | Next: Draw a trail

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:
  1. $\Delta lat=lat_2-lat_1$ and $\Delta lng=lng_2-lng_1$.

  2. $a=\sin(\Delta lat/2)^2+\cos(lat_1)\cos(lat_2)\sin(\Delta lng/2)^2$.

  3. $c=2\tan^{-1}(\frac{\sqrt{a}}{\sqrt{1-a}})$

  4. 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.

Now you try. Translate the equations above into code, and compute some distances.

Type your code here:


See your results here: