iOS find average speed

筅森魡賤 提交于 2019-12-01 01:31:18

Declare variable is your *.m class

@implementation your_class
{
    CLLocationDistance _distance;
    CLLocation *_lastLocation;
    NSDate *_startDate;
}

In your init or viewDidLoad method set them to initial values

_distance = 0;
_lastLocation = nil;
_startDate = nil;

Change locationUpdate: to

- (void)locationUpdate:(CLLocation *)location {
    speedLabel.text = [NSString stringWithFormat:@"%.2f", [location speed]*2.236936284];
    if (_startDate == nil) // first update!
    {
        _startDate = location.timestamp;
        _distance = 0;
    }
    else
    {
        _distance += [location distanceFromLocation:_lastLocation];
        _lastLocation = location;
        NSTimeInterval travelTime = [location.timestamp timeIntervalSinceDate:_startDate];
        if (travelTime > 0)
        {
            double avgSpeed = _distance / travelTime;
            AVGspeedlabel.text = [NSString stringWithFormat: @"%.2f", avgSpeed];
            NSLog(@"Average speed %.2f", avgSpeed);
        }
    }
}

to reset average speed

_startDate = nil;
_distance = 0;

Remember the first location that you got together with the time. Then calculate

CLLocationDistance dist = [location distanceFromLocation:initialLocation];
NSTimeInterval time = [location.timestamp timeIntervalSinceDate:initialDate];
double averageSpeed = dist/time;
// If you want it in miles per hour:
// double averageSpeed = dist/time * 2.236936284;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!