iOS find average speed

谁说我不能喝 提交于 2019-11-30 20:33:38

问题


I already have something that shows me my current speed and top speed (max speed in the code below) Now I want to make something that calculates my average speed with core location. How? thanks.

- (void)locationUpdate:(CLLocation *)location {
speedLabel.text = [NSString stringWithFormat:@"%.2f", [location speed]*2.236936284];

Here is the float for top speed

   float currentSpeed = [location speed]*2.236936284;
if(currentSpeed - maxSpeed >= 0.01){
    maxSpeed = currentSpeed;
    maxspeedlabel.text = [NSString stringWithFormat: @"%.2f", maxSpeed];

}

回答1:


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;



回答2:


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;


来源:https://stackoverflow.com/questions/22274801/ios-find-average-speed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!