How to get movement speed from iPhone/iPad device ?

How to get movement speed from iPhone/iPad device ?

Sometimes it is required to get speed from UIDevice to fulfill certain tasks. To calculate speed of iOS devices like iPhone/iPad you can use CLLocationManager delegates. To use this you should to add a few things in your application.

Here are steps to measure or calculate speed

  • Add CLLocationManagerDelegate in interface file declaration.
  • Create CLLocationManager object
  • After this you should use following lines in implementation file mainly in
    -(void)viewDidLoad method


CLLocationManager *locationManager=[[CLLocationManager alloc]init];
locationManager.delegate=self;
[loactionManager startUpdatingLocation];

Now following delegates of CLLocationManager can be used

(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation*)newLocation

fromLocation:(CLLocation *)oldLocation{
//simply get the speed provided by the phone from newLocation
double gpsSpeed = newLocation.speed;
NSLog(@"Speed of Device is %f",newLocation.speed);
// alternative manual method
if(oldLocation != nil)
{
CLLocationDistance distanceChange = [newLocation getDistanceFrom:oldLocation];
NSTimeInterval sinceLastUpdate = [newLocation.timestamp
timeIntervalSinceDate:oldLocation.timestamp];
double calculatedSpeed = distanceChange / sinceLastUpdate;
}
}

Above code works fine when device travels over a large area.

If you want calculated or measured speed in KPH then you have to multiply the measured speed by 3.6.

If you want speed in MPH then multiply it with 2.23693629 for MPH.

0 comments:

Post a Comment