The map has a selectedAnnotations property that you can use in the didUpdateToLocation method to indicate which annotation to get the distance.
(By the way, if you use the userLocation map userLocation , you might need to use the didUpdateUserLocation delegate display method instead of didUpdateToLocation , which is the CLLocationManager delegation method.)
In the delegate method, you can check if there is any annotation currently selected, and if so, specify the distance to this annotation (otherwise specify "no annotation selected").
You might want to write a generic method that can be called from didSelectAnnotationView and didUpdateUserLocation to reduce code duplication.
For example:
-(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)
Anna
source share