2011-11-27 52 views
10

在iOS 5中,有一种转发地理编码地址的新方法(将地址转换为1美国加利福尼亚州的无限环地址为纬度/经度地址)。 More info on this is here.在iOS 5上放置一个CLPlacemark到地图上

有没有人试图把前向地理编码的CLPlacemark对象放在MKMapView上?地理编码后我有一个CLPlacemark对象,但不知道如何将它放在地图上。

我会很感激任何类型的帮助。到目前为止Google没有任何帮助。

回答

24

除了选定的答案之外,还有这种方法可将注释添加到mapView以进行前向地理编码。 CLPlacemark对象可以直接转换为MKPlacemark并添加到mapview中。 像这样:

MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:placemark]; 
[self.mapView addAnnotation:placemark]; 

这是一个完整的前向地理编码示例。

NSString *address = @"1 Infinite Loop, CA, USA"; 
CLGeocoder *geocoder = [[CLGeocoder alloc] init]; 
    [geocoder geocodeAddressString:address 
       completionHandler:^(NSArray* placemarks, NSError* error){ 
        // Check for returned placemarks 
        if (placemarks && placemarks.count > 0) { 
         CLPlacemark *topResult = [placemarks objectAtIndex:0]; 
         // Create a MLPlacemark and add it to the map view 
         MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult]; 
         [self.mapView addAnnotation:placemark]; 
         [placemark release]; 
        } 
        [geocoder release]; 
       }]; 
+2

+1忘了MKPlacemark。 – Anna

9

A CLPlacemark未实施MKAnnotation协议,因此您仍需创建自己的注释类,或者可以使用MKPointAnnotation。地标的坐标位于其location属性中。

例如:

MKPointAnnotation *pa = [[MKPointAnnotation alloc] init]; 
pa.coordinate = placemark.location.coordinate; 
pa.title = ABCreateStringWithAddressDictionary(placemark.addressDictionary, YES); 
[mapView addAnnotation:pa]; 
[pa release]; //remove if using ARC 

您可以设置从标,但一个可能希望,如本例中的title任何东西,是使用地址簿UI框架来生成一个地址字符串由地标提供的地址字典。

+0

谢谢!这非常有帮助! – Stealth

+1

我还通过今年(2011年)WWDC的视频发现了另一种方式。只是一个fyi。 – Stealth

+0

使用ABCreateStringWithAddressDictionary时,我已经看到奇怪的微小内存泄漏... 2每次发生的泄漏总数为192bytes。有其他人有这个问题吗? – AndrewPK

0

在SWIFT 3.0

let pm = placemarks! as [CLPlacemark] // this is Clpmacemark 
let placemark = MKPlacemark.init(placemark: pm) 
self.mapview.addAnnotation(placemark)