如何从Core Location返回的位置检索地址

时间:2012-02-17 09:33:45

标签: objective-c cocoa-touch mapkit core-location

有没有办法将经度/纬度位置(由核心位置返回)转换为地址(街道和城市)?

2 个答案:

答案 0 :(得分:8)

最好的方法是使用CLGeocoder类中提供的反向地理编码。要从地理位置获取人类可读的地址,您必须使用reverseGeocodeLocation方法。

以下是小样本:

-(NSString *)getAddressFromLocation:(CLLocation *)location {
    NSString *address;
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error)
     {
         if(placemarks && placemarks.count > 0)
         {
             CLPlacemark *placemark= [placemarks objectAtIndex:0];

             address = [NSString stringWithFormat:@"%@ %@,%@ %@", [placemark subThoroughfare],[placemark thoroughfare],[placemark locality], [placemark administrativeArea]];

             NSLog(@"%@",address);
         }

     }];

    [geocoder release];
    return address;
}

答案 1 :(得分:2)

使用闭包的Rough Swift 3实现:

import CoreLocation

func getAddressFrom(location: CLLocation, completion:@escaping ((String?) -> Void)) {
    let geocoder = CLGeocoder()
    geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
        if let placemark = placemarks?.first,
            let subThoroughfare = placemark.subThoroughfare,
            let thoroughfare = placemark.thoroughfare,
            let locality = placemark.locality,
            let administrativeArea = placemark.administrativeArea {
            let address = subThoroughfare + " " + thoroughfare + ", " + locality + " " + administrativeArea

            placemark.addressDictionary

            return completion(address)

        }
        completion(nil)
    }
}

用法:

getAddressFrom(location: location) { (address) in
    print(address)
}

您还可以查看placemark.addressDictionary,这是包含地址簿键和地标值的字典。这些密钥在通讯簿框架中定义。