【问题标题】:Cumulative distance travelled SwiftUISwiftUI 累计行驶距离
【发布时间】:2021-07-24 05:10:31
【问题描述】:

有一些关于这个主题的 Q/A,例如herehere 但我正在尝试在 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 函数计算它们之间的距离。 这不适用于let distance = ... 行上的错误“Type of expression is ambiguous without more context”。

    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)
}

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

【问题讨论】:

  • 您在for 循环中使用的locations 数组是什么?它是如何声明的?如何在didUpdateLocations 委托函数中更新它?您在哪里使用 for 循环调用此代码?它在委托函数本身中吗?如果是这样,那么您的 getDistance 函数期望与您提供的参数不同(此外,每次委托触发时,locations 数组中可能只有一个元素;您需要保留历史记录你自己的数组
  • 对不起,我不是 100% 确定你的意思(我是新人),但我认为位置数组是在这里创建的...func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 需要哪些参数?

标签: ios swiftui core-location swift5


【解决方案1】:

您收到有关歧义表达式的错误的原因是您传递的参数与函数中的参数类型不匹配。 locations[i]CLLocation,而你的功能需要CLLocationCoordinate2D

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

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

您需要创建自己的位置数组来保存历史记录以供计算。

【讨论】:

  • 好的,谢谢,我会尝试重做这个,看看我能到达哪里
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多