Skip to content

Instantly share code, notes, and snippets.

@jonsherrard
Created September 20, 2012 17:04
Show Gist options
  • Save jonsherrard/3757084 to your computer and use it in GitHub Desktop.
Save jonsherrard/3757084 to your computer and use it in GitHub Desktop.
Coffeescript to convert to latitudes and longitudes into a distance
distance = (lat1, lon1, lat2, lon2) ->
R = 6371 # km (change this constant to get miles)
dLat = (lat2 - lat1) * Math.PI / 180
dLon = (lon2 - lon1) * Math.PI / 180
a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2)
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
d = R * c
if d > 1
return d + "km"
else return Math.round(d * 1000) + "m" if d <= 1
d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment