Home > Net >  iOS How to show in correct angle destination by two location?
iOS How to show in correct angle destination by two location?

Time:03-21

last couple of days I am struggling to make it right direction angle by two location point.

I failed it to make it properly.

Here is the example about from Philippians to New Zealand

extension FloatingPoint {

    var degreesToRadians: Self { return self * .pi / 180 }
    var radiansToDegrees: Self { return self * 180 / .pi }
}

func heading(from :CLLocationCoordinate2D ,to: CLLocationCoordinate2D) -> Double {
    let lat1 = from.latitude.degreesToRadians
    let lon1 = from.longitude.degreesToRadians

    let lat2 = to.latitude.degreesToRadians
    let lon2 = to.longitude.degreesToRadians

    let dLon = lon2 - lon1
    let y = sin(dLon) * cos(lat2)
    let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)

    let headingDegrees = atan2(y, x).radiansToDegrees
    if headingDegrees >= 0 {
        return headingDegrees
    } else {
        return headingDegrees   360
    }
}

Here called with lat and long in swiftUI code:

Image(systemName: "arrow.left.circle.fill")
 .font(.system(size: 25))
 .frame(width: 30, height: 30, alignment: .center)
 .rotationEffect(.degrees(heading(from:  CLLocationCoordinate2D(latitude: 14.599512, longitude: 120.984222),to: CLLocationCoordinate2D(latitude: -36.848461, longitude: 174.763336))))

Her is my output

enter image description here

By I seem correct direction is opposite:

enter image description here

CodePudding user response:

I believe your formula is for bearing between two coordinate points. The result of that formula is the degrees/radians from the magnetic North. So when we translate that to Core Animation, zero degrees bearing-wise is now actually -90/270 degrees in Core Animation so I believe if you substract 90 degrees or pi/2 radians from your calculation you should see the arrow pointing to the right direction.

You can find a useful graphic in the Adding Arcs section. https://developer.apple.com/library/archive/documentation/2DDrawing/Conceptual/DrawingPrintingiOS/BezierPaths/BezierPaths.html

  • Related