Skip to content

Instantly share code, notes, and snippets.

@marcgeld
Created February 10, 2018 14:14
Show Gist options
  • Save marcgeld/c11d98fbb108277c7600fcba164bb4c7 to your computer and use it in GitHub Desktop.
Save marcgeld/c11d98fbb108277c7600fcba164bb4c7 to your computer and use it in GitHub Desktop.
Calculates the distance between to coordinates on the earth surface.
#! /usr/bin/env groovy
class LatLng{
/*
Latitude is written before longitude. Latitude/Longitude is written with a decimal number.
Latitude is decimal number rangeing from positive to negative (north and south of the Equator)
Longitude is decimal number rangeing from positive to negative (negative is west of Greenwich and positive is eastward of Greenwich)
Latitude is the Y axis, Longitude is the X axis.
*/
double latitude, longitude
LatLng() {}
LatLng(String val) {
def (slat, slon) = val.split(',')
latitude = slat as double
longitude = slon as double
}
String description() {
"latitude: ${latitude}, longitude: ${longitude}"
}
String toString() {
"${latitude}, ${longitude}"
}
double distanceTo(LatLng endPos) {
// https://en.wikipedia.org/wiki/Haversine_formula
//def EARTH_RAD = 6378137 // Appr. Earth radius in meters at the equator
def EARTH_RAD = 6372.8 //6372.8 km
def haversine = { lat1, lon1, lat2, lon2 ->
// In km
EARTH_RAD * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(Math.toRadians(lat2 - lat1) / 2),2)
+ Math.pow(Math.sin(Math.toRadians(lon2 - lon1) / 2),2)
* Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)))) as double
}
haversine(latitude, longitude, endPos.latitude, endPos.longitude)
}
}
// Nashville International Airport (BNA) in Nashville, TN, USA (36.12, -86.67)
// Los Angeles International Airport (LAX) in Los Angeles, CA, USA, (33.94, -118.40)
assert 2887.25995060711 == (new LatLng("36.12, -86.67").distanceTo(new LatLng("33.94, -118.40"))).round(11)
// to/from same point
assert 0 == new LatLng("0.0, 0.0").distanceTo(new LatLng("0.0, 0.0"))
// Royal Observatory in Greenwich to London city, St. Paul's Cathedral (8.5 km)
assert 7.9294298181 == (new LatLng("51.476852, -0.000500").distanceTo(new LatLng("51.513870, -0.098362"))).round(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment