如何使用coreLocation框架计算ios 7中的速度

时间:2014-01-22 13:54:40

标签: ios objective-c performance ios7 core-location

在iOS 7之前,我用来计算速度,如下所示

-(void)locationManager:(CLLocationManager *)manager 
   didUpdateToLocation:(CLLocation *)newLocation
          fromLocation:(CLLocation *)oldLocation
{

      double speed = newLocation.speed;
      NSLog(@"Speed of Device is %f",newLocation.speed); 

      // manual method
      if(oldLocation != nil)
      {
           CLLocationDistance distanceChange = [newLocation getDistanceFrom:oldLocation];
           NSTimeInterval sinceLastUpdate = [newLocation.timestamp 
           timeIntervalSinceDate:oldLocation.timestamp];
           double calculatedSpeed = distanceChange / sinceLastUpdate;

           NSLog(@"Speed of Device is %f",calculatedSpeed); 
     }  
 }  

因为不推荐使用此方法。请建议我使用CoreLocation使用iOS7计算速度的另一种方法。

4 个答案:

答案 0 :(得分:4)

您可以执行以下操作:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *loc = locations.lastObject;
    double speed = loc.speed;
    NSLog(@"%f", speed);
}

答案 1 :(得分:4)

第一种方法:保存旧呼叫中的旧位置。 。为了更准确kCLLocationAccuracyBestForNavigation。 在某些情况下,这可能会给您不准确的结果。(例如停止或错过报告一个位置等)。

CLLocationDistance distanceChange = [newLocation distanceFromLocation:oldLocation];
NSTimeInterval sinceLastUpdate = [newLocation.timestamp timeIntervalSinceDate:oldLocation.timestamp];
double calculatedSpeed = distanceChange / sinceLastUpdate;
NSLog(@"calculatedSpeed using old location:%.1f",calculatedSpeed);

第二种方法是使用速度属性。使用此属性,您将获得当前车辆速度(移动速度)。这将给出速度< / strong> m / s 。要将其转换为 km / hr ,请使用

location.speed * 3.6

使用kCLLocationAccuracyBestForNavigation

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *location = locations.lastObject;
    double speed = location.speed*3.6;
    NSLog(@"%f", speed);
}

答案 2 :(得分:2)

“getDistanceFrom:”方法简单地重命名为“distanceFromLocation:” - 您可以使用它。

CLLocationDistance distanceChange = [newLocation distanceFromLocation:oldLocation];

答案 3 :(得分:0)

以km / h为单位的其他解决方案。

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [self.locationManager location];

        double speedCalculada = location.speed * 3.6;
        self.lblVelocidad.text = (location.speed<0)?@"-- km/h":[NSString stringWithFormat:@"%d          Km/h", (int) speedCalculada];
}