Jan 16, 2010

Locate your position using GPS

For this test application you need to create a new View-Based Application project (I called it TestLocation).
Once created, open the TestLocationViewController.xib file by double clicking on it. drag over it four labels and a button to make start the update location..
After the editing the result should be like in the following image:




Save the xib file and go to the TestLocationViewController.h and add two IBOutlets to be connected to the empty labels and an action

 - (IBAction)startUpdate:(id)sender 

for the button. These labels will show the latitude and the longitude of your GPS position, while the button will start the location manager. Connect the action to the Touch Up Inside event of the button.

Now comes the location code; in your project right click on the TestLocation target and select the 'Get Info'. In the General tab add the CoreLocation.framework as linked library.

Now come back in the TestLocationViewController.h and add the inclusion of the location framework, the protocol CLLocationManagerDelegate and a member variable that define the location manager (of type CLLocationManager).
I defined the location manager as a property, so it will be instantiated only when needed.

Now switch to the .m file and implement the location protocol delegate methods: didUpdateToLocation (called on success of updating GPS position) and didFailWithError (called if an error occours, for example no GPS signal is present).

Inside the method didUpdateToLocation you have to extract the new position and update the label's text using the following code:

    CLLocationCoordinate2D loc = newLocation.coordinate;
    [lblLatitude setText:[NSString stringWithFormat:@"%f", loc.latitude]];
    [lblLongitude setText:[NSString stringWithFormat:@"%f", loc.longitude]];

then stop updating the location manager:

    [locationManager stopUpdatingLocation];

If you implemented the location manager as property, redefine the accessor method to check if it has been already created, otherwise create it, set the desired accuracy and the delegate as follows:

    locationManager = [[CLLocationManager alloc] init];
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    locationManager.delegate = self;

Now you are ready; Press the Build and Go button and when you'll press the button, the location manager will start to update the GPS position. The simulator comes with a fake GPS positions, so you'll be able to see something in the labels.
The complete project can be downloaded from here.

Enjoy and thanks for reading!