2012-02-17 75 views

回答

7

最好的方法是使用反向地理編碼,它在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; 
} 
+0

這將返回一個無效的CFStringRef。有想法該怎麼解決這個嗎?謝謝!! – 2012-06-21 03:11:49

+0

我得到了「將塊內的變量分配給塊外的變量」的錯誤,但是我可以通過這樣做來修復它,「__block NSString * address;」 – yoshitech 2017-03-16 04:39:34

+0

爲什麼不使用完成代替塊變量? – GGirotto 2018-01-19 16:47:03

1

粗糙的斯威夫特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,這是一個包含字典地址簿鍵和地標的值。這些密鑰在地址簿框架中定義。