Search code examples
iosswiftcllocationmanagercllocation

Calculate travel time CLLocation Swift


I want to find travel time of moving object using swift 2.2 when user start tracking the object. I wrote locationManager function to track the moving object location and travel distance but I need to find travel time?

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    userLocations.append(locations[0] as CLLocation)

    if startLocation == nil {
        startLocation = locations.first! as CLLocation
    } else {
        let distance = startLocation.distanceFromLocation(locations.last! as CLLocation) / 1000
        let lastDistance = lastLocation.distanceFromLocation(locations.last! as CLLocation) / 1000;

        vartraveledDistance += lastDistance
        print( "\(startLocation)")
        print( "\(locations.last!)")
        print("FULL DISTANCE: \(traveledDistance)")

        print("STRAIGHT DISTANCE: \(distance)")
    }
    lastLocation = locations.last! as CLLocation
}


@IBAction func StartTrip(sender: AnyObject) {
    print("Start Trip")
    locationManager.startUpdatingLocation()
}

@IBAction func StopTrip(sender: AnyObject) {
    print("End Trip")
    locationManager.stopUpdatingLocation()
    traveledDistance.text = String(format:"%f km", self.vartraveledDistance)
}

Solution

  • You can save the startDate when you set the startLocation and use NSDate timeIntervalSinceDate method to calculate the travel elapsed time:

    First add a startDate object and a computed property to your view controller:

    var startDate: NSDate!
    var traveledTime: Double { return NSDate().timeIntervalSinceDate(startDate) }
    

    Then set the startDate after setting your startLocation:

    if startLocation == nil {
        startLocation = locations.first
        startDate = NSDate()
        // code ...
    }
    

    Create an extension to format your time using NSDateComponentsFormatter:

    extension NSTimeInterval {
        struct DateComponents {
            static let formatterPositional: NSDateComponentsFormatter = {
                let dateComponentsFormatter = NSDateComponentsFormatter()
                dateComponentsFormatter.unitsStyle = .Positional
                dateComponentsFormatter.allowedUnits = [.Hour,.Minute,.Second]
                dateComponentsFormatter.zeroFormattingBehavior = .DropLeading
                return dateComponentsFormatter
            }()
        }
        var positionalTime: String {
            return DateComponents.formatterPositional.stringFromTimeInterval(self) ?? ""
        }
    }
    

    Now you can just check the traveledTime:

    print("travel elapsed time: \(traveledTime.positionalTime)")