在两点之间获得距离时遇到麻烦

时间:2014-03-03 10:04:31

标签: ios objective-c cllocationdistance

在我的iOS应用程序中,我要跟踪从起点到当前位置的距离。我实现了这段代码:

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

但是当我尝试使用该应用时,它并没有得到距离。我需要距离在标签中显示它并且距离我将使用这个等式计算步数:

steps = distance / length of human step

我知道这不准确,但我不能使用加速计,因为它在iPhone显示器不活动时不起作用。一个人建议我this solution。为什么我的代码没有给我一个距离?

2 个答案:

答案 0 :(得分:2)

回调

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

确实为您提供了至少一个位置,并且如果之前延迟了位置更新,则locations数组会保留多个对象。要获得步行/行驶距离,您必须将初始位置存储在类变量或属性中。然后,当你想计算一个距离时,你可以像上面的代码一样,但是使用保存初始位置的类变量。

答案 1 :(得分:0)

检查以下代码以获取距离:

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