Search code examples
objective-cmapkitmkannotationios5

Display MapKit annotation automatically


I'm trying to get a annotation that show the callout automatically. I have managed to do so, but when this is done the map zooms in on the middle of the Arctic Ocean for some reason. Anyone have an idea why that happens? Here is my current code:

- (void)viewDidLoad
{

    CLLocationCoordinate2D zoomLocation;
    zoomLocation.latitude = 59.*****;
    zoomLocation.longitude = 17.*****;
    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(zoomLocation,  0.5 * METERS_PER_MILE, 0.5 * METERS_PER_MILE);
    MKCoordinateRegion adjustedRegion = [self.mapView regionThatFits:viewRegion];
    [self.mapView setRegion:adjustedRegion animated:YES];

    self.mapView.delegate = self;

    CLLocationCoordinate2D location = CLLocationCoordinate2DMake(59.*****, 17.*****);
    MapAnnotation *annotaion = [[MapAnnotation alloc] initWithCoordinates:location title:@"*****" subTitle:@"*****"];
    [self.mapView addAnnotation:annotation];
    [super viewDidLoad];
}

- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views
{
    MKAnnotationView *annotationView = [views objectAtIndex:0];
    id <MKAnnotation> mp = [annotationView annotation];
    [mv selectAnnotation:mp animated:YES];
}

Solution

  • This seems to happen if showsUserLocation is turned on.

    When the map view adds the user location annotation view, trying to select it (with animated set to YES) makes the map zoom to the Arctic (for unknown reasons).

    Setting animated to NO in the selectAnnotation call will avoid the zoom to the Arctic but you may end up with the user location annotation selected instead of your annotation.

    Either turn showsUserLocation off or, in didAddAnnotationViews, loop through the views array until you find an annotation that is not the user location:

    for (MKAnnotationView *av in views) {
        id <MKAnnotation> mp = [av annotation];
        if (![mp isKindOfClass:[MKUserLocation class]])
        {
            [mv selectAnnotation:mp animated:YES];
            break;
        }
    }