我已经有一些东西可以显示我当前的速度和最高速度(下面的代码中的最大速度)现在我想制作一些计算我的核心位置的平均速度的东西。怎么样?谢谢。
- (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];
}
答案 0 :(得分:2)
记住你与时间在一起的第一个位置。然后计算
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;
答案 1 :(得分:2)
声明变量是你的* .m类
@implementation your_class
{
CLLocationDistance _distance;
CLLocation *_lastLocation;
NSDate *_startDate;
}
在init
或viewDidLoad
方法中将它们设置为初始值
_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;