iOSfind平均速度

我已经有东西显示我目前的速度和最高速度(下面的代码中的最大速度)现在我想做的东西,计算我的核心位置的平均速度。 怎么样? 谢谢。

- (void)locationUpdate:(CLLocation *)location { speedLabel.text = [NSString stringWithFormat:@"%.2f", [location speed]*2.236936284]; 

这是最高速度的浮子

  float currentSpeed = [location speed]*2.236936284; if(currentSpeed - maxSpeed >= 0.01){ maxSpeed = currentSpeed; maxspeedlabel.text = [NSString stringWithFormat: @"%.2f", maxSpeed]; } 

声明variables是你的* .m类

 @implementation your_class { CLLocationDistance _distance; CLLocation *_lastLocation; NSDate *_startDate; } 

在你的initviewDidLoad方法中,将它们设置为初始值

 _distance = 0; _lastLocation = nil; _startDate = nil; 

更改locationUpdate:

 - (void)locationUpdate:(CLLocation *)location { speedLabel.text = [NSString stringWithFormat:@"%.2f", [location speed]*2.236936284]; if (_startDate == nil) // first update! { _startDate = location.timestamp; _distance = 0; } else { _distance += [location distanceFromLocation:_lastLocation]; _lastLocation = location; NSTimeInterval travelTime = [location.timestamp timeIntervalSinceDate:_startDate]; if (travelTime > 0) { double avgSpeed = _distance / travelTime; AVGspeedlabel.text = [NSString stringWithFormat: @"%.2f", avgSpeed]; NSLog(@"Average speed %.2f", avgSpeed); } } } 

重置平均速度

 _startDate = nil; _distance = 0; 

记住你和时间在一起的第一个地点。 然后计算

 CLLocationDistance dist = [location distanceFromLocation:initialLocation]; NSTimeInterval time = [location.timestamp timeIntervalSinceDate:initialDate]; double averageSpeed = dist/time; // If you want it in miles per hour: // double averageSpeed = dist/time * 2.236936284;