首页 > 解决方案 > 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 contextlet 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)
}

非常感谢帮助!在收到另一个问题的一些反馈后,我尝试仔细格式化我的问题和代码,但请告诉我我做错了什么或者可以让它变得更容易!

标签: iosswiftuicore-locationswift5

解决方案


您收到有关不明确表达式的错误的原因是因为您传递的参数与函数中参数的类型不匹配。locations[i]CLLocation一会儿你的功能想要CLLocationCoordinate2D

无论如何,您的函数都会创建CLLocations,因此您只需修复函数的参数类型。

然而,你有一个更大的问题。您依赖于locations传递给委托函数的数组。尽管在由于某种原因位置更新被推迟的情况下,这可能包含多个位置,但实际上它只会包含一个位置更新。

您将需要创建自己的位置数组以保留历史记录以进行计算。


推荐阅读