Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

Check below code for getting distance:

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


    if ([coordArray count]>0) {

        CLLocation *currentLocation = manager.location;
        CLLocation *startLocation = [coordArray objectAtIndex:0];
        [coordArray addObject:currentLocation];
        float speed = currentLocation.speed * 3.6;
        if (speed > 0) {
            NSLog(@"\n speed:%@",[NSString stringWithFormat:@"%.2f Km/h", speed]);
        }

        CLLocationDistance distance = [startLocation distanceFromLocation:currentLocation];

        if (distance>0) {
            NSLog(@"Distance:%@",[NSString stringWithFormat:@"%lf meters",distance]);
        }

    }
    else{
        [coordArray addObject:manager.location];
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top