[英]Get the Zip Code of the Current Location - iPhone SDK
如何使用 mapkit 獲取當前位置的 zip 代碼,我沒有在文檔中找到任何用於獲取此代碼的 API。 我使用了 CLLocationManager 的坐標、姿態、水平、垂直、航向和速度參數,但未能獲得 zip 代碼。
誰能給我 API 或示例代碼來完成它。
是否可以使用 iphone 中的當前位置獲取 zip 代碼?
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
您可以使用緯度和經度創建MKPlacemark object ,其中包括 zip 代碼。
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)
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.