Created
May 15, 2018 14:26
-
-
Save yossan/d1c13983f3ce9bd96905cb20c575b442 to your computer and use it in GitHub Desktop.
Calculates bearing between two points
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 | |
/* | |
θ = 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you please check this with
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? :)