使用CLGeocoder获取邮政编码

时间:2014-12-11 12:36:36

标签: ios objective-c iphone mapkit cllocationmanager

我在使用CLGeocoder更改地图区域时尝试获取邮政编码:

CLLocation *location = [[CLLocation alloc] initWithLatitude:13.184098 longitude:77.725978];

    - (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
CLLocation *location=[[CLLocation alloc] initWithLatitude:13.184098 longitude:77.725978];
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error)
 {
     if (!(error))
     {
         CLPlacemark *placemark = [placemarks objectAtIndex:0];
         NSLog(@"placemark %@",placemark);

         NSString *Zipcode = [[NSString alloc]initWithString:placemark.postalCode];
         NSLog(@"%@",Zipcode);
     }
     else
     {
         NSLog(@"Geocode failed with error %@", error); // Error handling must required
     }
 }];
}

我得到这样的回复

{ Country = India; CountryCode = IN; FormattedAddressLines = ( Amarwara, "Madhya Pradesh", India ); Name = Amarwara; State = "Madhya Pradesh"; SubAdministrativeArea = Chhindwara; SubLocality = Amarwara; }

我第一次能够获得邮政编码。当该地区发生变化时,我会尝试对邮政编码进行地理编码。我甚至尝试明确地设置位置(第1行),它仍然返回空邮政编码。任何人都可以帮助这个奇怪的错误吗?

1 个答案:

答案 0 :(得分:0)

试试这个

CLGeocoder *geocoder = [[CLGeocoder alloc] init];

CLLocation *newLocation = [[CLLocation alloc]initWithLatitude:21.1700
                                                    longitude:72.8300];

[geocoder reverseGeocodeLocation:newLocation
               completionHandler:^(NSArray *placemarks, NSError *error) {

                   if (error) {
                       NSLog(@"Geocode failed with error: %@", error);
                       return;
                   }

                   if (placemarks && placemarks.count > 0)
                   {
                       CLPlacemark *placemark = placemarks[0];

                       NSDictionary *addressDictionary =
                       placemark.addressDictionary;

                       NSLog(@"%@ ", addressDictionary);
                       NSString *address = [addressDictionary
                                            objectForKey:(NSString *)kABPersonAddressStreetKey];
                       NSString *city = [addressDictionary
                                         objectForKey:(NSString *)kABPersonAddressCityKey];
                       NSString *state = [addressDictionary
                                          objectForKey:(NSString *)kABPersonAddressStateKey];
                       NSString *zip = [addressDictionary 
                                        objectForKey:(NSString *)kABPersonAddressZIPKey];


                       NSLog(@"%@ %@ %@ %@", address,city, state, zip);
                   }

               }];