[英]Cumulative distance travelled SwiftUI
有一些關於這個主題的問答,例如這里和這里,但我試圖在 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
function 計算它們之間的距離。 這不適用於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)
這是我的 function 用於獲取 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)
}
非常感謝幫助! 在收到另一個問題的一些反饋后,我嘗試仔細格式化我的問題和代碼,但請告訴我我做錯了什么或者可以讓它變得更容易!
您收到有關不明確表達式的錯誤的原因是因為您傳遞的 arguments 與 function 中的 arguments 的類型不匹配。 locations[i]
是CLLocation
而您 function 想要CLLocationCoordinate2D
。
您的 function 無論如何都會創建CLLocation
,因此您只需修復 function 的參數類型即可。
然而,你有一個更大的問題。 您依賴於傳遞給委托 function 的locations
數組。 盡管在由於某種原因位置更新被推遲的情況下,這可能包含多個位置,但實際上它只會包含一個位置更新。
您將需要創建自己的位置數組以保留歷史記錄以進行計算。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.