繁体   English   中英

获取当前位置的 Zip 代码 - iPhone SDK

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM