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:

14
 
1
lat1 = 34.1 
2
lat2 = 40.7 
3
lng1 = -118.25
4
lng2 = -74.02 
5
6
drawmap((lat1+lat2)/2,(lng1+lng2)/2,3)
7
setmarker(lat1,lng1)
8
setmarker(lat2,lng2)
9
10
torad = math.pi/180
11
lat1 = lat1 * torad
12
lat2 = lat2 * torad
13
lng1 = lng1 * torad
14
lng2 = lng2 * torad

See your results here: