Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
You have the latitude and longitude of a spatial location and you want to retrieve the address of this location.
The process of retrieving a meaningful address using spatial coordinates, x and y, is called reverse geocoding. Create and use an instance of the MKReverseGeocoder class and provide a delegate to this instance, making sure that the delegate object conforms to the MKReverseGeocoderDelegate protocol.
The .h file of a simple view controller for this purpose is defined like so:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface RootViewController : UIViewController <MKReverseGeocoderDelegate> {
@public
MKReverseGeocoder *myReverseGeocoder;
}
@property (nonatomic, retain) MKReverseGeocoder *myReverseGeocoder;
@end
The .m file of this view controller is as follows:
#import "RootViewController.h"
@implementation RootViewController
@synthesize myReverseGeocoder;
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder
didFindPlacemark:(MKPlacemark *)placemark{
/* We received the results */
NSLog(@"%@", placemark.country);
NSLog(@"%@", placemark.postalCode);
NSLog(@"%@", placemark.locality);
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder
didFailWithError:(NSError *)error{
/* An error has occurred. Use the [error] parameter to
determine the cause of the issue */
NSLog(@"An error occurred in the reverse geocoder");
}
- (void)viewDidLoad {
[super viewDidLoad];
CLLocationCoordinate2D location;
location.latitude = +38.4112810;
location.longitude = -122.8409780f;
MKReverseGeocoder *reverseGeocoder =
[[MKReverseGeocoder alloc] initWithCoordinate:location];
self.myReverseGeocoder = reverseGeocoder;
[reverseGeocoder release];
self.myReverseGeocoder.delegate = self;
[self.myReverseGeocoder start];
}
- (void) viewDidUnload{
[super viewDidUnload];
[self.myReverseGeocoder cancel];
self.myReverseGeocoder = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation {
/* Support all orientations */
return YES;
}
- (void)dealloc {
[myReverseGeocoder cancel];
[myReverseGeocoder release];
[super dealloc];
}
@end
The NSLog methods in the preceding code write the results shown in Figure 4-6 in the console window for the given spatial location.
Each application has a limit on the amount of reverse geocoding requests that it can make every day. To perform a reverse geocoding request, you must create an instance of the MKReverseGeocoder class. This class requires an active network connection in order to process requests successfully. The reverse geocoded values are reported to the delegate object of this class. The delegate object assigned to an instance of the MKReverseGeocoder must conform to the MKReverseGeocoderDelegate protocol.