如何使用mapkit获取当前位置的邮政编码,我没有找到任何用于在文档中获取此文件的API。我使用了CLLocationManager的坐标,attitue,水平,垂直,航向和速度参数,但未能获得邮政编码。
任何人都可以给我API或示例代码来完成它。
是否可以使用iphone中的当前位置获取邮政编码?
答案 0 :(得分:9)
iPhone中的反向地理编码:
首先添加<MobileCoreServices/MobileCoreServices.h>
框架。
-(void)CurrentLocationIdentifier
{
//---- For getting current gps location
CLLocationManager *locationManager;
CLLocation *currentLocation;
locationManager = [CLLocationManager new];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
使用GPS位置获取地点详细信息的反向地理编码。
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
currentLocation = [locations objectAtIndex:0];
[locationManager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
{
if (!(error))
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"\nCurrent Location Detected\n");
NSLog(@"placemark %@",placemark);
NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
NSString *Address = [[NSString alloc]initWithString:locatedAt];
NSString *Zipcode = [[NSString alloc]initWithString:placemark.postalCode];
NSLog(@"%@",Zipcode);
}
else
{
NSLog(@"Geocode failed with error %@", error); // Error handling must required
}
}];
}
有关从gps获取的更多详细信息:
placemark.region
placemark.country
placemark.locality
placemark.name
placemark.ocean
placemark.postalCode
placemark.subLocality
placemark.location
答案 1 :(得分:1)
您可以使用纬度和经度来创建MKPlacemark object,其中包含邮政编码。
Here是一个展示如何操作的示例。
答案 2 :(得分:0)
快速版本:
func getZipCode(location: CLLocation, completion: @escaping (String?) -> Void) {
CLGeocoder().reverseGeocodeLocation(location) { placemarks, error in
if let error = error {
print("Failed getting zip code: \(error)")
completion(nil)
}
if let postalCode = placemarks?.first?.postalCode {
completion(postalCode)
} else {
print("Failed getting zip code from placemark(s): \(placemarks?.description ?? "nil")")
completion(nil)
}
}
}