Skip to content

Instantly share code, notes, and snippets.

@yossan
Created May 15, 2018 14:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save yossan/d1c13983f3ce9bd96905cb20c575b442 to your computer and use it in GitHub Desktop.
Save yossan/d1c13983f3ce9bd96905cb20c575b442 to your computer and use it in GitHub Desktop.
Calculates bearing between two points
import Foundation
import CoreLocation
/*
θ = atan2( sin Δλ ⋅ cos φ2 , cos φ1 ⋅ sin φ2 − sin φ1 ⋅ cos φ2 ⋅ cos Δλ )
where φ1,λ1 is the start point, φ2,λ2 the end point (Δλ is the difference in longitude)
*/
func calculateBearing(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> Double {
let x1 = from.longitude * (Double.pi / 180.0)
let y1 = from.latitude * (Double.pi / 180.0)
let x2 = to.longitude * (Double.pi / 180.0)
let y2 = to.latitude * (Double.pi / 180.0)
let dx = x2 - x1
let sita = atan2(sin(dx) * cos(y2), cos(y1) * sin(y2) - sin(y1) * cos(y2) * cos(dx))
return sita * (180.0 / Double.pi)
}
func coordinate2d(_ latitude: Double, _ longitude: Double) -> CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
let osaka = coordinate2d(34.693738, 135.502165)
let tokyo = coordinate2d(35.709026, 139.731992)
let osaka2tokyo = calculateBearing(from: osaka, to: tokyo)
print(osaka2tokyo) // 72.4176293831357
@abin0992
Copy link

Can you please check this with

let source = CLLocationCoordinate2D(latitude: -33.8392932, longitude: 151.21519799999999)
 let destination = CLLocationCoordinate2D(latitude: 39.645516999999998, longitude: -104.598724)

This is a source and destination coordinate of MKPolyline, which crosses 180th meridian. The bearing calculated is wrong as I have explained here Do you have suggestions to fix it? :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment