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)