如何使用MapKit获取当前位置的邮政编码,我在文档中没有找到任何获取此信息的API。我已经使用CLLocationManager的coordinate、attitue、horizontal、vertical、course和speed参数,但是无法获取邮政编码。
请问是否有人可以提供API或示例代码来完成此操作。
是否可能使用iPhone上的当前位置获取邮政编码?
如何使用MapKit获取当前位置的邮政编码,我在文档中没有找到任何获取此信息的API。我已经使用CLLocationManager的coordinate、attitue、horizontal、vertical、course和speed参数,但是无法获取邮政编码。
请问是否有人可以提供API或示例代码来完成此操作。
是否可能使用iPhone上的当前位置获取邮政编码?
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
Swift 版本:
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)
}
}
}