iosobjective-ccllocationdistance

Trouble while getting distance between two points


In my iOS app I've to track the distance from a a start point to my current location. I implemented this code:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *currentLocation = [locations lastObject];
    CLLocation *startLocation = [locations firstObject];
    [coordArray addObject:currentLocation];
    float speed = currentLocation.speed * 3.6;
    if (speed > 0) {
        self.labelSpeed.text = [NSString stringWithFormat:@"%.2f Km/h", speed];
        [speedArray addObject:[NSNumber numberWithFloat:speed]];
    }
    CLLocationDistance distance = [startLocation distanceFromLocation:currentLocation];
}

But when I try to use the app it doesn't get a distance. I need the distance to show it in a label and with distance I will calculate the number of steps by using this equation:

steps = distance / length of human step

I know that it's not accurate, but I can't use accelerometer, because it doesn't work while the display of the iPhone is not active. A person suggested me this solution. Why my code doesn't give me a distance?


Solution

  • The callback

    - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
    

    does give you at least one location, and locations array hold sonly multiple objects if the location update was deferred before. To get the walking/driving distance, you have to store the initial location in a class variable or property. Then, when you want to calculate a distance, do as in your code above, but with the class variable that holds the initial location.