【发布时间】:2021-07-24 05:10:31
【问题描述】:
有一些关于这个主题的 Q/A,例如here 和 here 但我正在尝试在 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