Monday, April 06, 2009

Getting greater position accuracy from the iPhone

The iPhone client for Trakkus uses the CLLocationManager to obtain readings. The classic method for getting the reading is to set the location manager going and wait for it to call back your delegate, didUpdateToLocation, with a reading. At this point you can immediately turn off the location manager by calling the stopUpdatingLocation method or you can check the accuracy of the location you have to see if you like it.

The CLLocation horizontalAccuracy setting is a double value that gives an estimated distance accuracy and there are some constants such as kCLLocationAccuracyHundredMeters or kCLLocationAccuracyTenMeters that you can compare the value with or just look at the value to see if it's within your desired accuracy.

If this horizontal accuracy is negative (invalid) or larger than you like, don't turn of the location manager yet. Leave it running and get a better reading.

Here's a snippet...

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

NSDate* eventDate = newLocation.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 5.0)
{
if(!signbit(newLocation.horizontalAccuracy) && newLocation.horizontalAccuracy <= kCLLocationAccuracyHundredMeters)
{
[locationManager stopUpdatingLocation];
TUser *presentUser = [Singleton singleton].currentUser;
NSString *tlat = [NSString stringWithFormat:@"%+.6f",newLocation.coordinate.latitude];
NSString *tlong = [NSString stringWithFormat:@"%+.6f",newLocation.coordinate.longitude];
if(![tlat isEqualToString:presentUser.latitude] || ![tlong isEqualToString:presentUser.longitude])
{
presentUser.latitude = tlat;
presentUser.longitude = tlong;

[NSThread detachNewThreadSelector:@selector(submitLocation:) toTarget:self withObject:presentUser];
}
}
}

}

(hey, that's my first Cocoa code posting ;-) )

No comments: