Question

prior to iOS 7 i used to calculate speed as below

-(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); 
     }  
 }  

since this method is deprecated ,. please suggest me another way to calculate speed using iOS7 using CoreLocation.

Was it helpful?

Solution

You can do the following:

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

OTHER TIPS

1st Approach:Saving the oldLocation from previous call. .For more accuracy kCLLocationAccuracyBestForNavigation. This might give you inaccurate result in some scenarios.(like stopped or missed to report one location etc).

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

2nd Approach is to use speed property.using this property you will get the current speed of the vehicle(moving speed).which will give speed in m/s. To convert it to km/hr use

location.speed * 3.6

use kCLLocationAccuracyBestForNavigation

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

The method "getDistanceFrom:" is simply renamed to "distanceFromLocation:" - you can use that.

CLLocationDistance distanceChange = [newLocation distanceFromLocation:oldLocation];

Other solution in 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];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top