Skip to content

Instantly share code, notes, and snippets.

@raunakp
Created December 5, 2018 11:31
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 raunakp/c0619acbd628a37fcc963e3556f5d883 to your computer and use it in GitHub Desktop.
Save raunakp/c0619acbd628a37fcc963e3556f5d883 to your computer and use it in GitHub Desktop.
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