如何在 Swift 中使用 CoreLocation 计算总行进距离
到目前为止,我还没有找到关于如何在 Swift for iOS 8 中执行此操作的任何资源,
您如何计算自您开始跟踪您的位置以来移动的总距离?
根据我目前所读到的内容,我需要保存一个点的位置,然后计算当前点和最后一个点之间的距离,然后将该距离添加到 totalDistance 变量
我对 Objective-C 非常陌生,所以一直没能搞定 swift 语法
这是我到目前为止所做的,不确定我是否做对了。尽管 distanceFromLocation
方法返回的全是 0.0,但显然有问题
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var newLocation: CLLocation = locations[0] as CLLocation
oldLocationArray.append(newLocation)
var totalDistance = CLLocationDistance()
var oldLocation = oldLocationArray.last
var distanceTraveled = newLocation.distanceFromLocation(oldLocation)
totalDistance += distanceTraveled
println(distanceTraveled)
}
最佳答案
更新:Xcode 8.3.2 • Swift 3.1
问题是因为您总是一遍又一遍地获得相同的位置。像这样尝试:
import UIKit
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
var startLocation: CLLocation!
var lastLocation: CLLocation!
var startDate: Date!
var traveledDistance: Double = 0
override func viewDidLoad() {
super.viewDidLoad()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
locationManager.distanceFilter = 10
mapView.showsUserLocation = true
mapView.userTrackingMode = .follow
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if startDate == nil {
startDate = Date()
} else {
print("elapsedTime:", String(format: "%.0fs", Date().timeIntervalSince(startDate)))
}
if startLocation == nil {
startLocation = locations.first
} else if let location = locations.last {
traveledDistance += lastLocation.distance(from: location)
print("Traveled Distance:", traveledDistance)
print("Straight Distance:", startLocation.distance(from: locations.last!))
}
lastLocation = locations.last
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
if (error as? CLError)?.code == .denied {
manager.stopUpdatingLocation()
manager.stopMonitoringSignificantLocationChanges()
}
}
}
关于ios - 计算总行驶距离 iOS Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28952747/