The iPhone has GPS built-in, which makes the phone really powerful and enables developers to innovate cool and cutting edge applications!
The iPhone devcenter has some sample code explaining how the CoreLocation framework works. But, I found that example a bit hard to understand…
Here is an easier way of finding your current location from your iPhone.
Let’s start with the interface/header file.
CurrentLocationController.h
#import <CoreLocation/CoreLocation.h> @interface CurrentLocationController : NSObject <CLLocationManagerDelegate> { CLLocationManager *locationManager; } @property (nonatomic, retain) CLLocationManager *locationManager; - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation; - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error; @end
Note: Our object “implements” the CLLocationManagerDelegate protocol. We “implement” two methods, locationManager:didUpdateToLocation:fromLocation: and locationManager:didFailWithErrorfrom :, from CLLocationManagerDelegate. The first method is invoked when a new location is available and the second one if an error has occurred.
Here comes the implementation:
#import "CurrentLocationController.h" @implementation CurrentLocationController @synthesize locationManager; - (id) init { self = [super init]; if (self != nil) { self.locationManager = [[[CLLocationManager alloc] init] autorelease]; self.locationManager.delegate = self; } return self; } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSLog([newLocation description]); } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { NSLog([error description]); } - (void)dealloc { [self.locationManager release]; [super dealloc]; } @end
The only important thing to note is the line
self.locationManager.delegate = self;. Here we set our own object as the delegate, which means that all the location messages will be forwarded to CurrentLocationController.
I hope this will give you more time innovating, instead of developing Trichotillomania.
#1 by PEZ on April 9, 2009 - 07:45
[samuel thanksThatWasVeryEnlightening:[[Rose alloc] init]];
(That’s correct, Objective C is a mystery to me.)
#2 by Jon Nylander on April 9, 2009 - 18:01
Lol, nerd humour iz over 9000…
#3 by masone on May 8, 2009 - 20:38
There is a small typo in the declaration of the method locationManager:
romLocation instead of fromLocation
#4 by Samuel on May 9, 2009 - 02:44
Fixed!
Thanks for pointing out the typo.
#5 by Naren on July 8, 2009 - 08:08
Hi,
Do you people are tackling with the oldLocation,
cllocationmanagerdelegate always returns old position in the starting. if you have device then go on the road and test it properly. I have the same code and suffering because of this.
If you have managed than please let me know how ?