Geocoding

The term geocoding refers to the translation of an address to a coordinate and vice versa. Geocoding functionality is encapsulated in the CLGeocoder class; to use it, you’ll need to link to CoreLocation.framework. Geocoding takes time and might not succeed at all, as it depends upon network and server availability; moreover, results may be more or less uncertain. Therefore, all geocoding methods take a completion handler which will eventually be called with two arguments:

NSArray* placemark
An NSArray of CLPlacemark objects. If things went really well, the array will contain exactly one CLPlacemark; if there are multiple placemark objects, the first one is the best guess. If nil, something went wrong.
NSError* error
If the placemark array was nil, this argument reports the reason things went wrong.

A CLPlacemark can be used to initialize an MKPlacemark, a CLPlacemark subclass that adopts the MKAnnotation protocol, and is therefore suitable to be handed directly over to an MKMapView for display. Here is an (unbelievably simple-minded) example that allows the user to enter an address in a UISearchBar (Chapter 25) to be displayed in an MKMapView:

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { NSString* s = searchBar.text; [searchBar resignFirstResponder]; CLGeocoder* geo = [CLGeocoder new]; [geo geocodeAddressString:s completionHandler:^(NSArray *placemarks, NSError *error) { if (nil == placemarks) { NSLog(@"%@", error.localizedDescription); return; } CLPlacemark* ...

Get Programming iOS 6, 3rd Edition 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.