9

I am developing GPS application. Do you know about how to detect speed of mobile device ?

Actually, I need to detect the speed every 2 seconds.

I know didUpdateToLocation method is called when location changed.

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

But I think this method is not suitable for my issue.

So, Do I need to check speed of [CLLocationManager location] in 2 seconds ?

Any suggestion ?

Thanks in advance.

Kshitiz Ghimire
  • 1,716
  • 3
  • 18
  • 37
Ferdinand
  • 1,193
  • 4
  • 23
  • 43

2 Answers2

27

How about the code below which works from the delegate method. Alternatively, if you did want to poll, then keep your previous location and check the distance changed from the last poll and use the manual method (also shown below) to calculate the speed.

Speed is calculated/provided in m/s so multiply by 3.6 for kmph or 2.23693629 for mph.

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
   //simply get the speed provided by the phone from newLocation
    double gpsSpeed = newLocation.speed;

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

    }   
}
Sam B
  • 27,273
  • 15
  • 84
  • 121
RR.
  • 679
  • 4
  • 8
  • 6
    Out of interest which is the better of the two options (in terms of accuracy)? –  Oct 08 '11 at 18:10
  • 1
    getDistanceFrom was depreciated. Replace CLLocationDistance distanceChange = [newLocation getDistanceFrom:oldLocation]; with CLLocationDistance distanceChange = [newLocation distanceFromLocation:oldLocation]; – Wes Apr 16 '13 at 01:27
0

You can only really use the delegate method you have suggested in your question.

Even if you access the [CLLocationManager location] every 2 seconds, you will only receive the coordinate you last received in the delegate method above.

Why the need to poll every two seconds? The iphone can update it's coordinates in less time on some cases.

HTH

RR.
  • 679
  • 4
  • 8