2012-06-04 48 views
7

我有一个用户位置(蓝点)和注释mapView。当选择注释时,我将文本设置为distLabel - “距离点4.0%m的距离”。如何在用户移动时更新该文本标签?如何计算用户移动时从用户位置到注释的距离

didSelectAnnotationView:

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view 
{ 

    CLLocation *pinLocation = 
     [[CLLocation alloc] initWithLatitude: 
         [(MyAnnotation*)[view annotation] coordinate].latitude 
           longitude: 
         [(MyAnnotation*)[view annotation] coordinate].longitude]; 
    CLLocation *userLocation = 
     [[CLLocation alloc] initWithLatitude: 
          self.mapView.userLocation.coordinate.latitude    
           longitude: 
           self.mapView.userLocation.coordinate.longitude];   
    CLLocationDistance distance = [pinLocation distanceFromLocation:userLocation]; 

    [distLabel setText: [NSString stringWithFormat:@"Distance to point %4.0f m.",  
                distance]]; 
} 

我知道有一个功能didUpdateToLocation,但我怎么能与didSelectAnnotationView使用它呢?

- (void)locationManager:(CLLocationManager *)manager 
    didUpdateToLocation:(CLLocation *)newLocation 
      fromLocation:(CLLocation *)oldLocation 
{ 
    //Did update to location 
} 

回答

15

地图视图具有selectedAnnotations属性,您可以在didUpdateToLocation方法用来告诉从中获取其标注的距离。

(顺便说一下,如果你正在使用的地图视图的userLocation,您可能需要使用地图视图的didUpdateUserLocation委托方法,而不是didUpdateToLocation这是一个CLLocationManager委托方法。)

在委托方法,你可以检查是否有任何当前选定的注释,如果是,则显示与该注释的距离(否则称为“未选择注释”)。

您可能需要编写一个可从didSelectAnnotationViewdidUpdateUserLocation中调用的常用方法以减少代码重复。

例如:

-(void)updateDistanceToAnnotation:(id<MKAnnotation>)annotation 
{ 
    if (annotation == nil) 
    { 
     distLabel.text = @"No annotation selected"; 
     return; 
    } 

    if (mapView.userLocation.location == nil) 
    { 
     distLabel.text = @"User location is unknown"; 
     return; 
    } 

    CLLocation *pinLocation = [[CLLocation alloc] 
     initWithLatitude:annotation.coordinate.latitude 
       longitude:annotation.coordinate.longitude]; 

    CLLocation *userLocation = [[CLLocation alloc] 
     initWithLatitude:mapView.userLocation.coordinate.latitude 
       longitude:mapView.userLocation.coordinate.longitude]; 

    CLLocationDistance distance = [pinLocation distanceFromLocation:userLocation]; 

    [distLabel setText: [NSString stringWithFormat:@"Distance to point %4.0f m.", distance]]; 
} 

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation 
{ 
    if (mapView.selectedAnnotations.count == 0) 
     //no annotation is currently selected 
     [self updateDistanceToAnnotation:nil]; 
    else 
     //first object in array is currently selected annotation 
     [self updateDistanceToAnnotation:[mapView.selectedAnnotations objectAtIndex:0]]; 
} 

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view 
{  
    [self updateDistanceToAnnotation:view.annotation]; 
} 
+0

从你非常回答一如既往!谢谢! –