Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

objective c - Reverse Geocode Current Location

Is it possible to reverse Geocode your current location on SDK 3.x? I need to simply get the zip code of the current location. The only examples I've seen use CoreLocation which I dont think was introduced until SDK 4.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use MKReverseGeocoder from 3.0 through 5.0. Since 5.0 MKReverseGeocoder is depreciated and usage of CLGeocoder is advised.

You should use CLGeocoder if available. In order to be able to extract address information you would have to include Address Book framework.

#import <AddressBookUI/AddressBookUI.h>
#import <CoreLocation/CLGeocoder.h>
#import <CoreLocation/CLPlacemark.h>

- (void)reverseGeocodeLocation:(CLLocation *)location
{ 
    CLGeocoder* reverseGeocoder = [[CLGeocoder alloc] init];
    if (reverseGeocoder) {
        [reverseGeocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
            CLPlacemark* placemark = [placemarks firstObject];
            if (placemark) {
                //Using blocks, get zip code
                NSString* zipCode = [placemark.addressDictionary objectForKey:(NSString*)kABPersonAddressZIPKey];
            }
        }];
    }else{
        MKReverseGeocoder* rev = [[MKReverseGeocoder alloc] initWithCoordinate:location.coordinate];
        rev.delegate = self;//using delegate
        [rev start];
        //[rev release]; release when appropriate
    }
    //[reverseGeocoder release];release when appropriate
}

MKReverseGeocoder delegate method:

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
    //Get zip code
    NSString* zipCode = [placemark.addressDictionary objectForKey:(NSString*)kABPersonAddressZIPKey];
}

MKReverseGeocoder and ABPersonAddressZIPKey were deprecated in iOS 9.0. Instead the postalcode property of the CLPlacemark can be used to get zip code:

NSString * zipCode = placemark.postalCode;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...