能否请您举例说明如何计算当前“速度”,我正在开发我的第一个简单应用程序 ala speedometer?
我想出使用 didUpdateToLocation
我还发现我需要使用公式 speed = distance/duration
是吗?如何计算持续时间?
最佳答案
您需要完成的基本步骤如下所示:
- 创建一个 CLLocationmanager 实例
- 指派一名代表 适当的回调方法
- 检查是否在回调中的 CLLocation 上设置了“速度”,如果是 - 这是您的速度
(可选)如果“速度”不是 设置,尝试从上次更新之间的距离计算它 和当前,除以时间戳的差值
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()
关于swift - 提供获取当前速度的简单方法(实现速度计),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38512443/