views:

62

answers:

1

Hello

I trying to calculate the total distance travelled and output it to the View Controller, but the results are not as expected. Code is as follows:

MyCLController.m

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{       
    validLocation = YES;

    if (!newLocation) 
    {
        validLocation = NO;
    }

    if (newLocation.horizontalAccuracy < 0)
    {
        validLocation = NO;
    }

    // Filter out points that are out of order
    NSTimeInterval secondsSinceLastPoint = -[newLocation.timestamp timeIntervalSinceNow];
    if (secondsSinceLastPoint < 0)
    {
        validLocation = NO;
    }

    if (validLocation == YES)
    {
        [self.delegate locationChange:newLocation :oldLocation];
    }

NewWorkoutViewController.m

-(void)locationChange:(CLLocation *)newLocation:(CLLocation *)oldLocation
{       

    CLLocationDistance meters = [newLocation distanceFromLocation:oldLocation];

    currentSpeed = ([newLocation speed] * 3600) / 1000;
    totalDistance = (totalDistance + meters) / 1000;
    totalDistanceMeters =  totalDistanceMeters + meters;
    avgSpeed = totalDistance / counterInt;

    [speedLbl1 setText:[NSString stringWithFormat:@"%.3f", currentSpeed]];
    [distanceLbl1 setText:[NSString stringWithFormat:@"%.3f", totalDistance]];

}

The problem is with my totalDistance, it doesn't appear to be adding to it each time, its as if its overwriting it, when I test in the car I can see values of 10 / 20 meters between coordinates, so this indicates that distanceFromLocation appears to be working.

Anyone any thoughts ?

Regards, Stephen

+2  A: 

Try this :

totalDistance = totalDistance + (meters / 1000);

instead of this

totalDistance = (totalDistance + meters) / 1000;

The way you had it, totalDistance was being divided by 1000 each time i.e. if you're travelling 10m each time :

totalDistance = (0+10) / 1000 = 0.01;
totalDistance = (0.01+10) / 1000 = 0.01001 //!< You expected this to be 0.02!
totalDistance = (0.01001+10) / 1000 = 0.01001001 //!< You expected this to be 0.03!
deanWombourne