Archive

Posts Tagged ‘wrong location IOS app’

Initial GPS fix always incorrect : Corelocation, CLLocationManager

June 28, 2011 7 comments

The Problem:

You use CLLocationManager.StartUpdatingLocation( ) to get an initial fix on the user’s location in your code. But you notice that the location is always wrong and way-off.

Analysis:

Take a look at Apple’s own documentation of CLLocationManager here : (link to documentation)

Because it can take several seconds to return an initial location, the location manager typically delivers the previously cached location data immediately and then delivers more up-to-date location data as it becomes available. Therefore it is always a good idea to check the timestamp of any location object before taking any actions. If both location services are enabled simultaneously, they deliver events using the same set of delegate methods.

Basically, IOS returns you previously cached information. This could also mean that if you used Corelocation in San Francisco today and then used the app in Dallas next, it will still report your location in San Francisco.

Solution:

In my code below, I have used two ways of making sure I have the correct location. One is to make sure horizontalAccuracy is < 100 meters and the next is the location timestamp is < 15 seconds ago. If it falls under any of these two conditions, the location is probably wrong and can be discarded. In this case I just wait for IOS to give me a fresher more accurate location fix.

Point to be noted here is that because of this, be prepared to wait for upto 10 seconds depending on how accurate the location info you want to get. More accurate = more delay especially after a cold start. Chances are, if you are not writing a GPS turn-by-turn navigation app, you don’t need pin-point location info. So, play around with it and relax the accuracy as much as possible depending on what fits your app’s scenario.

– (void) locationManager:(CLLocationManager*) manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation
{
@try
{
if(newLocation.horizontalAccuracy > 100)
{
NSLog(@”Ignoring GPS location more than 100 meters inaccurate :%f”, newLocation.horizontalAccuracy);
return;
}

NSDate* eventDate = newLocation.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 15.0)
{
NSLog(@”Ignoring GPS location more than 15 seconds old(cached) :%d”, abs(howRecent));
return;
}

[myLM stopUpdatingLocation];
}
@catch (NSException* ex)
{
[self debugMessage:ex.reason withTitle:@”Uncaught Error in didUpdateToLocation()”];
}
}

Advertisements