提供获取当前速度的简单方法(实现速度计)

Ily*_*lya 3 core-location swift

你能给我举个例子如何计算当前的“速度”,我正在开发我的第一个简单的应用程序 ala 速度计?

我想出使用 didUpdateToLocation

我还发现我需要使用公式 speed = distance / duration

这样对吗?如何计算持续时间?

Mar*_*sey 6

您需要执行的基本步骤如下所示:

  1. 创建一个 CLLocationmanager 实例
  2. 使用适当的回调方法分配委托
  3. 检查回调中的 CLLocation 是否设置了“速度”,如果是 - 这就是你的速度
  4. (可选)如果未设置“速度”,请尝试根据上次更新和当前更新之间的距离除以时间戳的差异来计算它

    import CoreLocation
    
    class locationDelegate: NSObject, CLLocationManagerDelegate {
        var last:CLLocation?
        override init() {
          super.init()
        }
        func processLocation(_ current:CLLocation) {
            guard last != nil else {
                last = current
                return
            }
            var speed = current.speed
            if (speed > 0) {
                print(speed) // or whatever
            } else {
                speed = last!.distance(from: current) / (current.timestamp.timeIntervalSince(last!.timestamp))
                print(speed)
            }
            last = current
        }
        func locationManager(_ manager: CLLocationManager,
                     didUpdateLocations locations: [CLLocation]) {
            for location in locations {
                processLocation(location)
            }
        }
    }
    
    var del = locationDelegate()
    var lm = CLLocationManager();
    lm.delegate = del
    lm.startUpdatingLocation()
    
    Run Code Online (Sandbox Code Playgroud)