Skip to content

Instantly share code, notes, and snippets.

@j05h
Created November 11, 2010 23:20
Show Gist options
  • Save j05h/673425 to your computer and use it in GitHub Desktop.
Save j05h/673425 to your computer and use it in GitHub Desktop.
class Numeric
def to_rad
self * Math::PI / 180
end
end
# http://www.movable-type.co.uk/scripts/latlong.html
# loc1 and loc2 are arrays of [latitude, longitude]
def distance loc1, loc2
lat1, lon1 = loc1
lat2, lon2 = loc2
dLat = (lat2-lat1).to_rad;
dLon = (lon2-lon1).to_rad;
a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.to_rad) * Math.cos(lat2.to_rad) *
Math.sin(dLon/2) * Math.sin(dLon/2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
d = 6371 * c; # Multiply by 6371 to get Kilometers
end
@prakashmurthy
Copy link

Thanks Josh for the example!

@maxhawkins
Copy link

Thanks, this helped me with an infovis project.

@reagent
Copy link

reagent commented Jun 18, 2014

Ended up using the Haversine gem -- same results, but easier to use on my project.

@mediocretes
Copy link

Borrowed this for an example in our server monitoring tools.

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment