2011-08-15 44 views
1

我正在實現一個mapView,當用戶搜索地址時將放置註釋。但不知何故,註釋有時不會移動並更新到新座標。只有在縮放地圖時纔會更新到新位置。小標題確實得到了更新。爲什麼我的地圖註記沒有移動?

- (void)searchBarSearchButtonClicked:(UISearchBar *)theSearchBar { 
    SVGeocoder *geocodeRequest = [[SVGeocoder alloc] initWithAddress:searchBar.text inRegion:@"sg"]; 
    [geocodeRequest setDelegate:self]; 
    [geocodeRequest startAsynchronous]; 
} 

- (void)geocoder:(SVGeocoder *)geocoder didFindPlacemark:(SVPlacemark *)placemark { 
     if (annotation) { 
      [annotation moveAnnotation:placemark.coordinate]; 
      annotation.subtitle = [NSString 
            stringWithFormat:@"%@", placemark.formattedAddress]; 
     } 
     else { 
      annotation = [[MyAnnotation alloc] 
          initWithCoordinate:placemark.coordinate 
          title:@"Tap arrow to use address" 
          subtitle:[NSString 
            stringWithFormat:@"%@", placemark.formattedAddress]]; 
      [mapView addAnnotation:annotation]; 
     } 
    MKCoordinateSpan span; 
    span.latitudeDelta = .001; 
    span.longitudeDelta = .001; 
    MKCoordinateRegion region; 
    region.center = placemark.coordinate; 
    region.span = span; 
    [mapView setRegion:region animated:TRUE]; 

    [searchBar resignFirstResponder]; 
} 

回答

1

你的代碼中沒有任何東西(你已經顯示)告訴mapView註解的位置已經改變。註釋本身可能無法在-moveAnnotation中執行,因爲註釋通常不知道它們已添加到的地圖或地圖(它們也不應該)。

移動註解的正確方法是從使用它的MKMapView中移除它,更新它的位置,然後將它添加回地圖。您不能僅僅在註釋添加到地圖後更改註釋的位置,因爲地圖可能會很好地緩存位置或根據其位置對註釋進行排序,並且MKMapView中沒有方法告訴地圖位置已更改。

我想你的條件更改爲類似這樣:

if (annotation == nil) { 
    annotation = [[MyAnnotation alloc] init]; 
    annotation.title = @"Tap arrow to use address"; 
} 
[mapView removeAnnotation:annotation]; 
[annotation moveAnnotation:placemark.coordinate]; 
annotation.subtitle = placemark.formattedAddress; 
[mapView addAnnotation:annotation]; 

這是假定它是安全地調用-init代替-initWithCoordinate:title:subtitle:;如果沒有,你會想改變它。

2

我不認爲MKMapView會得到關於註釋位置更改的通知。 MKAnnotation的文檔setCoordinate:說:「支持拖動的註釋應實現此方法來更新註釋的位置。」所以看起來這是該方法的唯一目的是支持拖動引腳。

嘗試在更改座標之前從地圖視圖中移除註釋,然後將其添加回地圖視圖。