Skip to content

Instantly share code, notes, and snippets.

@hishma
Created January 16, 2019 23:54
Show Gist options
  • Save hishma/d60465aa46f2f7407c991edeab5aaa38 to your computer and use it in GitHub Desktop.
Save hishma/d60465aa46f2f7407c991edeab5aaa38 to your computer and use it in GitHub Desktop.
Handy CorelLocation extension. Or so I think.
extension CLLocation {
/// Compass bearing from a known location
///
/// Shamelessly stolenfrom // https://stackoverflow.com/questions/26998029/calculating-bearing-between-two-cllocation-points-in-swift
///
/// - Parameter location: The `CLocation` to calculate the bearing from.
/// - Returns: The `CLLocationDirection` representing the compass bearing.
func bearing(from location: CLLocation) -> CLLocationDirection {
func degreesToRadians(degrees: CLLocationDirection) -> CLLocationDirection { return degrees * .pi / 180.0 }
func radiansToDegrees(radians: CLLocationDirection) -> CLLocationDirection { return radians * 180.0 / .pi }
let lat1 = degreesToRadians(degrees: location.coordinate.latitude)
let lon1 = degreesToRadians(degrees: location.coordinate.longitude)
let lat2 = degreesToRadians(degrees: self.coordinate.latitude)
let lon2 = degreesToRadians(degrees: self.coordinate.longitude)
let dLon = lon2 - lon1
let y = sin(dLon) * cos(lat2)
let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)
let radiansBearing = atan2(y, x)
var bearing = radiansToDegrees(radians: radiansBearing)
if bearing < 0.0 { bearing += 360.0 }
if bearing > 360.0 { bearing -= 360.0 }
return bearing
}
/// Speed travelled from a known location
///
/// - Parameter location: The `CLocation` to calculate the speed travelled from.
/// - Returns: The `CLLocationSpeed` expressed in meters per second.
func speed(from location: CLLocation) -> CLLocationSpeed {
let distance = self.distance(from: location) // meters
let timeInterval = self.timestamp.timeIntervalSince(location.timestamp) // seconds
// A distance or time interval of zero (or less) means our speed is zero by definition
guard distance > 0.0, timeInterval > 0.0 else { return 0.0 }
return distance / timeInterval // meters per second
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment