7.8. Converting Longitude and Latitude to a Meaningful Address

Problem

You have the latitude and longitude of a spatial location and you want to retrieve the address of this location.

Solution

Retrieving a meaningful address using spatial x and y coordinates is called reverse geocoding. To do this, create and use an instance of the CLGeocoder class and provide a completion block object, making sure that the block object has no return value and accepts two parameters:

  1. A placemarks array (of type NSArray), which will be set to the locations which matched your search.

  2. An error (of type NSError), which will get set to an error code if the reverse geocoding fails.

After instantiating an object of type CLGeocoder, we will use its reverseGeocodeLocation:completionHandler: method to do the reverse geocoding.

The .h file of a simple view controller for this purpose is defined like so:

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface
  Converting_Longitude_and_Latitude_to_a_Meaningful_AddressViewController
   : UIViewController

@property (nonatomic, strong) CLGeocoder *myGeocoder;

@end

You can do the reverse geocoding when your view loads:

- (void)viewDidLoad{
  [super viewDidLoad];

  CLLocation *location = [[CLLocation alloc]
                          initWithLatitude:+38.4112810
                          longitude:-122.8409780f];

  self.myGeocoder = [[CLGeocoder alloc] init];

  [self.myGeocoder
   reverseGeocodeLocation:location
   completionHandler:^(NSArray *placemarks, NSError *error) {

     if (error == nil &&
         [placemarks count] > 0){

       CLPlacemark ...

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.