简体   繁体   English

计算旅行时间CLLocation Swift

[英]Calculate travel time CLLocation Swift

I want to find travel time of moving object using swift 2.2 when user start tracking the object. 我想在用户开始跟踪对象时使用swift 2.2查找移动对象的行进时间。 I wrote locationManager function to track the moving object location and travel distance but I need to find travel time? 我编写了locationManager函数来跟踪移动对象的位置和行进距离,但是我需要查找行进时间?

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

My answer will be in obj-c since I haven't learnt swift yet :). 我的答案将在obj-c中,因为我还没有学会快速:)。 But you'll get the idea. 但是你会明白的。

In this class of yours you can create 2 dates: 在您的此类课程中,您可以创建2个日期:

NSDate *startDate;
NSDate *stopDate;

And then in your startTrip method initialize the startDate: 然后在您的startTrip方法中初始化startDate:

startDate = [NSDate date]; 

and in stopTrip initialize the stopDate and calculate the travel time: 然后在stopTrip中初始化stopDate并计算行驶时间:

stopDate = [NSDate date];
NSTimeInterval interval = [startDate timeIntervalSinceDate:stopDate];
NSLog (@"Travel time = %.0f seconds", interval);

Also if you are using MKMaps, in MKDirections class there is a method 另外,如果您使用的是MKMaps,则在MKDirections类中有一个方法

-(void)calculateETAWithCompletionHandler:(MKETAHandler)completionHandler

which lets you calculate the estimated time to travel 让您计算出预计的旅行时间

You can save the startDate when you set the startLocation and use NSDate timeIntervalSinceDate method to calculate the travel elapsed time: 设置startLocation并使用NSDate timeIntervalSinceDate方法来计算旅行经过时间时,可以保存startDate:

First add a startDate object and a computed property to your view controller: 首先向您的视图控制器添加一个startDate对象和一个计算属性:

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

Then set the startDate after setting your startLocation: 然后在设置startLocation之后设置startDate:

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

Create an extension to format your time using NSDateComponentsFormatter: 使用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: 现在,您只需检查traveledTime:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM