Created
December 5, 2018 11:31
-
-
Save raunakp/c0619acbd628a37fcc963e3556f5d883 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import Foundation | |
import CoreLocation | |
extension FloatingPoint { | |
var degreesToRadians: Self { return self * .pi / 180 } | |
var radiansToDegrees: Self { return self * 180 / .pi } | |
} | |
extension CLLocationCoordinate2D { | |
func coordinate(atDistance distanceInKm: Double, atBearingDegrees bearingDegrees: Double) -> CLLocationCoordinate2D { | |
let distanceInRadians = distanceInKm / LocationUtils.meanRadiusOfEarth | |
let startLatRadians = self.latitude.degreesToRadians | |
let startLonRadians = self.longitude.degreesToRadians | |
let bearingInRadians = bearingDegrees.degreesToRadians | |
let endLatRadians = asin(sin(startLatRadians) * cos(distanceInRadians) | |
+ cos(startLatRadians) * sin(distanceInRadians) * cos(bearingInRadians)) | |
var endLonRadians = startLonRadians + | |
atan2( | |
(sin(bearingInRadians) * sin(distanceInRadians) * cos(startLatRadians)), | |
(cos(distanceInRadians) - sin(startLatRadians) * sin(endLatRadians)) | |
) | |
// adjust toLonRadians to be in the range -180 to +180... | |
endLonRadians = fmod((endLonRadians + 3 * .pi), (2 * .pi)) - .pi | |
let endLatDegrees = endLatRadians.radiansToDegrees | |
let endLonDegrees = endLonRadians.radiansToDegrees | |
let result = CLLocationCoordinate2DMake(endLatDegrees, endLonDegrees) | |
return result | |
} | |
} | |
enum LocationUtils { | |
static let meanRadiusOfEarth = 6371.0 // km | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment