O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

9.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 that 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 top of the .m file of a simple view controller for this purpose is defined like so:

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController ()
@property (nonatomic, strong) CLGeocoder *myGeocoder;
@end

@implementation ViewController

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 *placemark = placemarks[

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required