Wednesday, August 29, 2007

Great Circle Distance in Coldfusion

I saw a question today on calculating the straight line distance between two geocoded points in the Google Maps API with CF.

Looking around on the internet I found the equations I needed at http://www.meridianworlddata.com/Distance-Calculation.asp and set to work. In the end it was much simpler than I had expected:


<!--- RADIUS OF EARTH --->
<cfset r = 3963>

<!--- DC
Latitude: 38° 57' 26" N (deg min sec), 38.9572° (decimal), 3857.43N (LORAN)
Longitude: 77° 2' 3" W (deg min sec), -77.0342° (decimal), 07702.05W (LORAN)
--->
<cfset lat1 = 38.9572>
<cfset lon1 = -77.0342>

<!--- BOSTON
Latitude: 42° 14' 7" N (deg min sec), 42.2352° (decimal), 4214.11N (LORAN)
Longitude: 71° 1' 39" W (deg min sec), -71.0275° (decimal), 07101.65W (LORAN)
--->
<cfset lat2 = 42.2352>
<cfset lon2 = -71.0275>

<!--- A GUESTIMATE OF THE DISTANCE --->
<cfset x = 69.1 * (lat2 - lat1)>
<cfset y = 69.1 * (lon2 - lon1) * cos(lat1/57.3) >

<cfset guess = sqr(x * x + y * y)>
GUESS: <cfdump var="#guess#"><br />

<!--- GREAT CIRCLE - SHOULD BE MORE ACCURATE --->
<cfset GCDistance = r * acos(sin(lat1/57.2958) * sin(lat2/57.2958) + cos(lat1/57.2958) * cos(lat2/57.2958) * cos(lon2/57.2958 -lon1/57.2958))>
GC Distance: <cfdump var="#GCDistance#"><br>


For the 'Guess' distance between Washington DC and Boston I came up with 394 and change and for the 'Great Circle Distance' I got 388 and change.

Being the Obsessive Compulsive programmer I can be I checked at http://www.wcrl.ars.usda.gov/cec/java/lat-long.htm and found they had 395 miles.

The difference comes from a slight difference in the start and end points =)

No comments: