Skip to content

Instantly share code, notes, and snippets.

@MichaelAstreiko
Created September 6, 2012 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelAstreiko/3656760 to your computer and use it in GitHub Desktop.
Save MichaelAstreiko/3656760 to your computer and use it in GitHub Desktop.
Haversine algorithmus
double EARTH_RADIUS = 6371
/**
* Calculate distance based on Haversine algorithmus
* (thanks to http://www.movable-type.co.uk/scripts/latlong.html)
*
* @param latitudeFrom
* @param longitudeFrom
* @param latitudeTo
* @param longitudeTo
* @return distance in Kilometers
*/
BigDecimal calculateDistance(BigDecimal latitudeFrom, BigDecimal longitudeFrom,
BigDecimal latitudeTo, BigDecimal longitudeTo) {
def dLat = Math.toRadians(latitudeFrom - latitudeTo)
def dLon = Math.toRadians(longitudeFrom - longitudeTo)
//a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
//distance = 2.EARTH_RADIUS.atan2(√a, √(1−a))
def a = Math.pow(Math.sin(dLat / 2), 2) +
Math.cos(Math.toRadians(latitudeFrom)) *
Math.cos(Math.toRadians(latitudeTo)) * Math.pow(Math.sin(dLon / 2), 2)
return 2 * EARTH_RADIUS * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment