Question

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];

}
Was it helpful?

Solution

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;

OTHER TIPS

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top