Calculating bearing between two CLLocationCoordinate2Ds

前端 未结 4 1671
遇见更好的自我
遇见更好的自我 2020-11-27 13:07

Very \"simple\" problem: given two CLLocationCoordinate2Ds, how can I get the bearing (as radians) from the first to the second? I\'ve done a lot of research and studying on

4条回答
  •  清歌不尽
    2020-11-27 13:49

    Swift 3:

    extension CLLocationCoordinate2D {
        func bearing(to point: CLLocationCoordinate2D) -> Double {
            func degreesToRadians(_ degrees: Double) -> Double { return degrees * Double.pi / 180.0 }
            func radiansToDegrees(_ radians: Double) -> Double { return radians * 180.0 / Double.pi }
    
            let lat1 = degreesToRadians(latitude)
            let lon1 = degreesToRadians(longitude)
    
            let lat2 = degreesToRadians(point.latitude);
            let lon2 = degreesToRadians(point.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);
    
            return radiansToDegrees(radiansBearing)
        }
    }
    

提交回复
热议问题