Calculate Total Traveled Distance iOS Swift

后端 未结 3 1382
[愿得一人]
[愿得一人] 2020-12-01 10:20

How can I calculate the total distance traveled use CoreLocation in Swift

I haven\'t been able to so far find any resources for how to do this in Swift for iOS 8,

3条回答
  •  借酒劲吻你
    2020-12-01 10:30

    update: Xcode 8.3.2 • Swift 3.1

    The problem there is because you are always getting the same location over and over again. Try like this:

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

    Sample Project

提交回复
热议问题