2014-03-03 52 views
0

在我的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。为什么我的代码不能给我一个距离?

+1

它在干什么。试图获得距离后,距离的值是多少? currentLocation和startLocation的值是什么?除非你给我们提供有关它在做什么的信息,否则我们无法提供帮助。 “它不工作”不是很具描述性。 – Fogmeister

回答

2

回调

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

不给你至少一个位置,和位置阵列持有sonly多个对象,如果位置更新被推迟之前。为了获得行走/驾驶距离,您必须将初始位置存储在类变量或属性中。然后,当你想计算一个距离时,按照上面的代码进行,但使用包含初始位置的类变量。

+0

谢谢,我明白我愚蠢的错误。所以我必须通过这个代码'self.startLocation = [locations firstObject];'将开始位置存储在一个属性中,并且在我应该通过此代码计算距离之后'CLLocationDistance distance = [self.startLocation distanceFromLocation:currentLocation];'对? – lucgian841

+2

@ lucgian841:除了如果你正在寻找“距离我有多远”,而不是“我跑了多久”,我想补充一点:你不能定义startPosition和currentPosition之间的距离,你需要从pos1到pos2 +从pos2到pos3 + ... +从posx到currentPosition。否则,如果用户跑50公里,然后返回49公里,你的距离将是1公里而不是99公里。跳这个帮助 –

+0

是的,请注意@ArmandDOHM的评论 – Volker

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