Skip to content

Instantly share code, notes, and snippets.

@pathikrit
Last active September 24, 2019 19:06
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 pathikrit/56cfb9994299bd78de6b107800a2384e to your computer and use it in GitHub Desktop.
Save pathikrit/56cfb9994299bd78de6b107800a2384e to your computer and use it in GitHub Desktop.
Distance calculator between 2 coordinates on a planet
/** Distance between 2 coordinates (in degrees) */
def dist(
p1: (Double, Double), // Coordinate 1 (in degrees)
p2: (Double, Double), // Coordinate 2 (in degrees)
manhattanDist: Boolean = false, // If true, calculate Manhattan distance on the sphere :)
diameter: Double = 7917.5 // Diameter of Earth in miles; set this to whatever planet/units you want
): Double = {
import Math._
def haversine(theta: Double) = (1 - cos(theta))/2
def archaversine(delta: Double) = asin(sqrt(delta))
val (lat1, long1) = p1
val (lat2, long2) = p2
val x1 = lat1.toRadians
val y1 = long1.toRadians
val x2 = lat2.toRadians
val y2 = long2.toRadians
val dx = x2 - x1
val dy = y2 - y1
val a = if (manhattanDist) {
archaversine(haversine(dx)) + archaversine(haversine(dy))
} else {
archaversine(haversine(dx) + cos(x1)*cos(x2)*haversine(dy))
}
a*diameter
}
/*********************************/
val ny = (40.7128, 74.0060)
val la = (34.0522, 118.2437)
println(dist(ny, la)) //Should be ~2446 miles between NYC and LA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment