2011-08-15 41 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:说:“支持拖动的注释应实现此方法来更新注释的位置。”所以看起来这是该方法的唯一目的是支持拖动引脚。

尝试在更改坐标之前从地图视图中移除注释,然后将其添加回地图视图。