Last active
August 29, 2015 14:26
-
-
Save theo-bittencourt/39fd9cbd82fb4310a4b7 to your computer and use it in GitHub Desktop.
Swift implementation to calculate a destination location based on distance and direction from an origin location
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
import Foundation | |
import CoreLocation | |
// Calculate destination location based on origin location, distance (meters) and direction (degrees from north). | |
// Playing: myOriginLocation.destinationBy(distance: 5.0, direction: 45.0) | |
// http://www.geomidpoint.com/destination/calculation.html (Spherical earth model) | |
extension CLLocation { | |
func destinationBy(# distance: CLLocationDistance, direction: CLLocationDirection) -> CLLocation { | |
let earthRadius = 6372.7976 | |
let angularDistance = (distance / 1000) / earthRadius | |
let originLatRad = self.coordinate.latitude * (M_PI / 180) | |
let originLngRad = self.coordinate.longitude * (M_PI / 180) | |
let directionRad = direction * (M_PI / 180) | |
let destinationLatRad = asin( | |
sin(originLatRad) * cos(angularDistance) + | |
cos(originLatRad) * sin(angularDistance) * | |
cos(directionRad)) | |
let destinationLngRad = originLngRad + atan2( | |
sin(directionRad) * sin(angularDistance) * cos(originLatRad), | |
cos(angularDistance) - sin(originLatRad) * sin(destinationLatRad)) | |
let destinationLat: CLLocationDegrees = destinationLatRad * (180 / M_PI) | |
let destinationLng: CLLocationDegrees = destinationLngRad * (180 / M_PI) | |
return CLLocation(latitude: destinationLat, longitude: destinationLng) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment