Skip to content

Instantly share code, notes, and snippets.

@erica
Last active Jan 12, 2016
Embed
What would you like to do?
import Darwin
postfix operator ° {}
postfix func °(degrees: Double) -> Double {return degrees * M_PI / 180.0}
public struct Coordinate {
public let latitude: Double, longitude: Double
public enum EarthUnits: Double {case ImperialRadius = 3961.0, MetricRadius = 6373.0}
public func distanceFrom(coordinate: Coordinate, radius: EarthUnits = .ImperialRadius) -> Double {
let (dLat, dLon) = (latitude - coordinate.latitude, longitude - coordinate.longitude)
let (sqSinLat, sqSinLon) = (pow(sin(dLat° / 2.0), 2.0), pow(sin(dLon° / 2.0), 2.0))
let α = sqSinLat + sqSinLon * cos(latitude°) * cos(coordinate.latitude°)
return 2.0 * radius.rawValue * atan2(sqrt(α), sqrt(1.0 - α))
}
}
let whitehouse = Coordinate(latitude: 38.898556, longitude: -77.037852)
let fstreet = Coordinate(latitude: 38.897147, longitude: -77.043934)
whitehouse.distanceFrom(fstreet)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment