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:
A placemarks array (of type
NSArray), which will be set to the locations that matched your search.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>@interfaceViewController()@property(nonatomic,strong)CLGeocoder*myGeocoder;@end@implementationViewController
You can do the reverse geocoding when your view loads:
-(void)viewDidLoad{[superviewDidLoad];CLLocation*location=[[CLLocationalloc]initWithLatitude:+38.4112810longitude:-122.8409780f];self.myGeocoder=[[CLGeocoderalloc]init];[self.myGeocoderreverseGeocodeLocation:locationcompletionHandler:^(NSArray*placemarks,NSError*error){if(error==nil&&placemarks.count>0){CLPlacemark*placemark=placemarks[
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access