1
votes

I'm trying to add the distance from the user's position to a selected annotation's subtitle in a mapview. The mechanics of it are working, but the actual callout gets messed up the first time it's displayed. There appears to be a redraw problem.

mapView annotation redraw problem

Subsequent taps on the pin show the correct layout.

Here's the relevant code:

// called when selecting annotations

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

MKPointAnnotation *selectedAnnotation = view.annotation;

//attempt to add distance on annotation
CLLocation *pointALocation = [[CLLocation alloc] 
                              initWithLatitude:selectedAnnotation.coordinate.latitude 
                              longitude:selectedAnnotation.coordinate.longitude];
float distanceMeters = [pointALocation distanceFromLocation:locationManager.location];

//for sending info to detail
myPinTitle = selectedAnnotation.title;

[selectedAnnotation setSubtitle:[NSString stringWithFormat:@"%.2f miles away", (distanceMeters / 1609.344)]];

} I've tried calling [view setNeedsDisplay], but to no avail.

Thanks in advance for your help.


The Solution that Worked

Here's the solution I finally came up with. It seems to work.

I edited out the duplicate code from the didSelectAnnotationView method, above, and came up with:

//called when user location changes

- (void)updatePinsDistance
{
for (int x=0; x< [[mapView annotations]count]; x++) {
    MKPointAnnotation *thisPin =[[mapView annotations] objectAtIndex:x];

    //attempt to add distance on annotation
    CLLocation *pointALocation = [[CLLocation alloc] 
                                 initWithLatitude:thisPin.coordinate.latitude 
                                 longitude:thisPin.coordinate.longitude];
    float distanceMeters = [pointALocation distanceFromLocation:locationManager.location];
    NSString *distanceMiles = [NSString stringWithFormat:@"%.2f miles from you",
                                                    (distanceMeters / 1609.344)];

    [thisPin setSubtitle:distanceMiles];
    }
}
1

1 Answers

3
votes

You should set your subtitle in another place than didSelectAnnotationView. Actually all annotationViews should have their title and subtitle set before they are returned by the mapView:viewForAnnotation: method.

The fact that you set a long subtitle certainly explains that the callout is not the right size. The size must be calculated before the didSelectAnnotationView is called.