我正在创建导航应用程序。我想知道我现在的航向和,比如说,东方之间有多少度。我的方法是用0角减去真实航向,以北为例,以东为例,以90度为例,依此类推。当差异达到let i: ClosedRange<Double> = 0...20时,我猜航向是面向预定方向的,在本例中,是东方。
我想知道这是否是完美的方法论。我还是不知道是否应该用方位来代替。

  //calculate the difference between two angles ( current heading and east angle, 90 degrees)

    func cal(firstAngle: Double) -> Double {
        var diff = heading - 90
        if diff < -360 {
            diff += 360
        } else if diff > 360 {
            diff -= 360
        }
        return diff
    }

// check if the difference falls in the range
let i: ClosedRange<Double> = 0...20

if !(i.contains(k)) {
    k = cal(firstAngle: b)
    } else if (i.contains(k)) {
    let message = "You are heading east"
     print(message)
      } else {return}
   }

  func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
        var heading = newHeading.trueHeading }

最佳答案

这应该能满足你的需要。代码中的注释:

func cal(heading: Double, desired: Double) -> Double {
    // compute adjustment
    var angle = desired - heading

    // put angle into -360 ... 360 range
    angle = angle.truncatingRemainder(dividingBy: 360)

    // put angle into -180 ... 180 range
    if angle < -180 {
        angle += 360
    } else if angle > 180 {
        angle -= 360
    }

    return angle
}

// some example calls
cal(heading: 90, desired: 180)  // 90
cal(heading: 180, desired: 90)  // -90
cal(heading: 350, desired: 90)  // 100
cal(heading: 30, desired: 270)  // -120

let within20degrees: ClosedRange<Double> = -20...20

let adjust = cal(heading: 105, desired: 90)
if within20degrees ~= adjust {
    print("heading in the right direction")
}

heading in the right direction

关于swift - 如何告诉用户面对北方或东方的准确程度?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57434269/

10-12 02:31