Skip to content

Instantly share code, notes, and snippets.

@softwarerero
Created March 3, 2014 13:23
Show Gist options
  • Save softwarerero/9324827 to your computer and use it in GitHub Desktop.
Save softwarerero/9324827 to your computer and use it in GitHub Desktop.
Calculate the distance between 2 points in km
class Geo
@radiusInMiles: 3956.0
@radiusInKilometers: 6367.0
@toRadian: (v) ->
v * (Math.PI / 180)
@diffRadian: (v1, v2) ->
@toRadian(v2) - @toRadian(v1)
# Calculate the distance between 2 points in km
# http://pietschsoft.com/post/2008/02/Calculate-Distance-Between-Geocodes-in-C-and-JavaScript.aspx
@calcDistance: (lat1, lng1, lat2, lng2, radius) ->
radius * 2 * Math.asin( Math.min(1, Math.sqrt( ( Math.pow(Math.sin((@diffRadian(lat1, lat2)) / 2.0), 2.0) + Math.cos(@toRadian(lat1)) * Math.cos(@toRadian(lat2)) * Math.pow(Math.sin((@diffRadian(lng1, lng2)) / 2.0), 2.0) ) ) ) )
@distanceKmFormatted: (lat1, lng1, lat2, lng2) ->
distance = @calcDistance(lat1, lng1, lat2, lng2, @radiusInKilometers)
distance.toFixed(2) + " km"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment