[英]Trouble while getting distance between two points
在我的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显示器不活动时不起作用。 一个人建议我这个解决方案 。 为什么我的代码没有给我一个距离?
回调
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
确实为您提供了至少一个位置,并且如果之前延迟了位置更新,则位置数组会保留多个对象。 要获得步行/行驶距离,您必须将初始位置存储在类变量或属性中。 然后,当您想要计算距离时,请按照上面的代码进行操作,但使用保存初始位置的类变量。
检查以下代码以获取距离:
- (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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.