ios - SwiftUI 累计行驶距离
问题描述
关于这个主题有一些 Q/A,例如这里和这里,但我试图在 Swift UI 中调整这些以计算运行期间连续点之间的距离数组。这个想法是最终我可以获得“每 0.2 英里行驶的距离”或类似的列表。
但我首先想要的是...位置 1 和位置 2、位置 2 和位置 3、位置 3 和位置 4 之间的距离等 - 计算跑步时的总距离。
为此,我正在尝试以下代码:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
lastSeenLocation = locations.last
fetchCountryAndCity(for: locations.last)
print (locations)
这工作正常,并将更新的位置列表打印到模拟器,但是下面的内容是为了获取添加的每个位置,将其用作起点,下一个作为终点,现在只需将每个距离打印到控制台。getDistance
然后使用下面的函数计算它们之间的距离。这不适用于在线错误“ Type of expression is ambiguous without more context
” let distance = ...
。
var total: Double = 00.00
for i in 0..<locations.count - 1 {
let start = locations[i]
let end = locations[i + 1]
let distance = getDistance(from: start,to: end)
total += distance
}
print (total)
这是我获取 2 点之间实际距离的函数,我从上面发布的其他问题/答案之一中获取。
func getDistance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance {
let from = CLLocation(latitude: from.latitude, longitude: from.longitude)
let to = CLLocation(latitude: to.latitude, longitude: to.longitude)
return from.distance(from: to)
}
非常感谢帮助!在收到另一个问题的一些反馈后,我尝试仔细格式化我的问题和代码,但请告诉我我做错了什么或者可以让它变得更容易!
解决方案
您收到有关不明确表达式的错误的原因是因为您传递的参数与函数中参数的类型不匹配。locations[i]
是CLLocation
一会儿你的功能想要CLLocationCoordinate2D
。
无论如何,您的函数都会创建CLLocation
s,因此您只需修复函数的参数类型。
然而,你有一个更大的问题。您依赖于locations
传递给委托函数的数组。尽管在由于某种原因位置更新被推迟的情况下,这可能包含多个位置,但实际上它只会包含一个位置更新。
您将需要创建自己的位置数组以保留历史记录以进行计算。
推荐阅读
- javascript - 在 *client 端使用 react 验证电子邮件帐户是否处于活动状态*
- python - 在 Heroku-16 堆栈上安装 GCC (gfortran)
- javascript - 与“扩展”游标相关的内存使用和效率与 indexedDB 中的多个事务
- php - 我无法在 django 1.11.9 中进行迁移
- java - 如何从 1jframe 链接到另一个 jframe
- javascript - 选择数组javascript的一部分
- jenkins - 压缩 Jenkins Pipeline 中的目录
- typescript - 如何使用可观察对象和/或异步生成器递归访问 Promise?
- prolog - prolog:如果两个列表相同但没有特定元素,则谓词为真
- java - 如何使用 RabbitMQ Java 从每个客户端发送/接收消息