iOS

Calculating Speed from Coordinates in iOS

Nivetha Sri

11 Jul 2016

Calculating Speed from Coordinates in iOS

In one of our apps, we had a requirement to display Current Latitude, Current Longitude, Current Speed, Current direction in which mobile is pointing, Top Speed and Current Time. Also, all the data points should be automatically refreshed.

Everything was done quickly except the speed calculation. We are sharing our thoughts on how to calculate the speed at which you are traveling using location co-ordinates.

For Calculating speed, we have got the formula

Speed = Distance Travelled / Time taken

We can calculate the speed in two different Delegate methods

1. didUpdateToLocation

2. didUpdateLocation

1.didUpdateToLocation

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
 
 {
 
  
 
  NSTimeInterval timeElapsed;
 
  CLLocationDistance distance;
 
  float speed;
 
  
 
  CLLocation *locA = [[CLLocation alloc] initWithLatitude:oldLocation.coordinate.latitude longitude:oldLocation.coordinate.longitude];
 
  
 
  CLLocation *locB = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];
 
  distance = [locA distanceFromLocation:locB];
 
  NSLog(@"%f",distance);
 
  timeElapsed = [newLocation.timestamp timeIntervalSinceDate:oldLocation.timestamp];
 
  speed =distance/timeElapsed;
 
  NSLog(@"%f",speed);
 
  
 
 }

Here we will get the new location and old location directly.We can find the distance & time with the help of two coordinates.

But didUpdateTolocation is deprecated, which we can’t use.So I tried with the next method didUpdateLocation.

2. didUpdateLocation

After trying out many tutorials we found an easy way of speed calculation, which we can get directly from the CLLocationManager delegate method.

Check out the code snippet

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
 
 {
 
  CLLocation *updatelocation = locations.lastObject;
 
  double speed = updatelocation.speed;
 
  speed = speed * 1.94384; //converting speed from m/s to knots(unit)
 
  NSLog(@"Speed %f",speed);
 
 }

Based on our internal QA and client’s real scenario testing, it is working fine.

                                   screen shot speed

This above code is enough for calculating the speed in any of the Location update application in iOS.

NOTE: CLLocation manager will provide the speed in m/s , So we can make a conversion in whichever unit we need.