Skip to content

Instantly share code, notes, and snippets.

@ichord
Last active October 29, 2019 04:32
Show Gist options
  • Save ichord/a65e66f244d8da637ef780703028799f to your computer and use it in GitHub Desktop.
Save ichord/a65e66f244d8da637ef780703028799f to your computer and use it in GitHub Desktop.
Calculate the distance of two geo points.
function distanceBetween(startPoint, endPoint) {
console.log(startPoint, endPoint)
let earthRadius = 6371.0
let startRadians = [
startPoint.latitude * Math.PI / 180,
startPoint.longitude * Math.PI / 180
]
let endRadians = [
endPoint.latitude * Math.PI / 180,
endPoint.longitude * Math.PI / 180
]
let latitudeDeltas = endRadians[0] - startRadians[0]
let longitudeDeltas = endRadians[1] - startRadians[1]
let a = Math.pow(Math.sin(latitudeDeltas / 2), 2) + Math.cos(startRadians[0]) *
Math.pow(Math.sin(longitudeDeltas / 2), 2) * Math.cos(endRadians[0])
let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
return c * earthRadius
}
// https://github.com/alexreisner/geocoder/blob/master/lib/geocoder/calculations.rb#L84
// https://en.wikipedia.org/wiki/Haversine_formula
private typealias GeoPoint = (latitude: Float, longitude: Float)
private func distanceBetween(_ startPoint: GeoPoint, _ endPoint: GeoPoint) -> Float {
let earth_radius = 6371.0
let startRadians = [
startPoint.latitude * .pi / 180,
startPoint.longitude * .pi / 180
]
let endRadians = [
endPoint.latitude * .pi / 180,
endPoint.longitude * .pi / 180
]
let latitudeDeltas = endRadians[0] - startRadians[0]
let longitudeDeltas = endRadians[1] - startRadians[1]
let a = pow(sin(latitudeDeltas / 2), 2) + cos(startRadians[0]) *
pow(sin(longitudeDeltas / 2), 2) * cos(endRadians[0])
let c = 2 * atan2(sqrt(a), sqrt(1 - a))
return c * Float(earth_radius)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment