Positioning MKMapView to show multiple annotations at once Positioning MKMapView to show multiple annotations at once ios ios

Positioning MKMapView to show multiple annotations at once


The link posted by Jim is now dead, but i was able to find the code (which I had bookmarked somewhere). Hope this helps.

- (void)zoomToFitMapAnnotations:(MKMapView *)mapView {     if ([mapView.annotations count] == 0) return;     CLLocationCoordinate2D topLeftCoord;     topLeftCoord.latitude = -90;     topLeftCoord.longitude = 180;     CLLocationCoordinate2D bottomRightCoord;     bottomRightCoord.latitude = 90;     bottomRightCoord.longitude = -180;     for(id<MKAnnotation> annotation in mapView.annotations) {         topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);         topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);         bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);         bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);     }     MKCoordinateRegion region;     region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;     region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;          // Add a little extra space on the sides    region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1;    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1;     region = [mapView regionThatFits:region];     [mapView setRegion:region animated:YES]; }


Why so complicated?

MKCoordinateRegion coordinateRegionForCoordinates(CLLocationCoordinate2D *coords, NSUInteger coordCount) {    MKMapRect r = MKMapRectNull;    for (NSUInteger i=0; i < coordCount; ++i) {        MKMapPoint p = MKMapPointForCoordinate(coords[i]);        r = MKMapRectUnion(r, MKMapRectMake(p.x, p.y, 0, 0));    }    return MKCoordinateRegionForMapRect(r);}


As of iOS7 you can use showAnnotations:animated:

[mapView showAnnotations:annotations animated:YES];