Created
September 23, 2015 18:20
-
-
Save maddiesch/d22792336ba24486bcb1 to your computer and use it in GitHub Desktop.
Calculate the distance between 2 coordinates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Float { | |
var radians: Float { | |
get { | |
return self * Float(M_PI / 180.0) | |
} | |
} | |
} | |
struct Location { | |
let radius: Float = 3961.0 | |
let latitude: Float | |
let longitude: Float | |
init(lat: Float, long: Float) { | |
latitude = lat | |
longitude = long | |
} | |
func distance(location: Location) -> Float { | |
let lat_1 = latitude.radians | |
let lat_2 = location.latitude.radians | |
let lng_1 = longitude.radians | |
let lng_2 = location.longitude.radians | |
let dlon = lng_2 - lng_1 | |
let dlat = lat_2 - lat_1 | |
let a = pow(sin(dlat / 2.0), 2.0) + cos(lat_1) * cos(lat_2) * pow(sin(dlon / 2.0), 2.0) | |
let c = 2.0 * atan2(sqrt(a), sqrt(1.0 - a)) | |
return radius * c | |
} | |
} | |
let loc_1 = Location(lat: 33.942536, long: -118.408075) | |
let loc_2 = Location(lat: 32.733556, long: -117.189667) | |
loc_1.distance(loc_2) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment