从iOS获取反向地理编码当前位置的最简单方法

我在这里看到另一个问题: 确定iPhone用户的国家 ,可以得到iPhone的用户所在的国家 。

这对于许多用途来说相当方便。 然而,是否有可能更深入地从iOS推断出(如果有信息的话)用户所在的州或城市呢?

如果事情不可能,我认为反向地理编码服务将是下一个步骤。是否有甚至可以为您的应用程序聘用的反向地理编码服务?

我将从CLReverseGeocoder类开始。

这个stackoverflow问题得到当前的城市,可能会适应您的使用。

在iOS 5中不推荐使用MKReverseGeocoder ,现在它是CLGeocoder

 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { [self.locationManager stopUpdatingLocation]; CLGeocoder * geoCoder = [[CLGeocoder alloc] init]; [geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) { for (CLPlacemark * placemark in placemarks) { .... = [placemark locality]; } }]; } 
 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); } }]; 

结果

 { City = Surat; Country = India; CountryCode = IN; FormattedAddressLines = ( Surat, Gujarat, India ); Name = Surat; State = Gujarat; } 2012-12-20 21:33:26.284 CurAddress[4110:11603] (null) Surat Gujarat (null) 

以下代码可以很容易地检索完整的细节。

  [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) { if(placemarks.count){ placeNameLabel.text = [placemarks[0] name]; streetNumberLabel.text = [placemarks[0] subThoroughfare]; streetLabel.text = [placemarks[0] thoroughfare]; neighborhoodLabel.text = [placemarks[0] subLocality]; cityLabel.text = [placemarks[0] locality]; countyLabel.text = [placemarks[0] subAdministrativeArea]; stateLabel.text = [placemarks[0] administrativeArea]; //or province zipCodeLabel.text = [placemarks[0] postalCode]; countryLabel.text = [placemarks[0] country]; countryCodeLabel.text = [placemarks[0] ISOcountryCode]; inlandWaterLabel.text = [placemarks[0] inlandWater]; oceanLabel.text = [placemarks[0] ocean]; areasOfInterestLabel.text = [placemarks[0] areasOfInterest[0]]; } }];