iphonemapkitmkmapviewmkannotationmkcoordinateregion

Zoom to fit region for all annotations - ending up zooming in between annotations


I have a problem with fitting all my annotations to the screen... sometimes it shows all annotations, but some other times the app is zooming in between the two annotations so that none of them are visible... I want the app to always fit the region to the annotations and not to zoom in between them... what do I do wrong?

if ([mapView.annotations count] == 2) { 
 CLLocationCoordinate2D SouthWest = location;
 CLLocationCoordinate2D NorthEast = savedPosition;

 NorthEast.latitude = MAX(NorthEast.latitude, savedPosition.latitude);
 NorthEast.longitude = MAX(NorthEast.longitude, savedPosition.longitude); 

 SouthWest.latitude = MIN(SouthWest.latitude, location.latitude);
 SouthWest.longitude = MIN(SouthWest.longitude, location.longitude);

 CLLocation *locSouthWest = [[CLLocation alloc] initWithLatitude:SouthWest.latitude longitude:SouthWest.longitude];
 CLLocation *locNorthEast = [[CLLocation alloc] initWithLatitude:NorthEast.latitude longitude:NorthEast.longitude];

 CLLocationDistance meter = [locSouthWest distanceFromLocation:locNorthEast];

 MKCoordinateRegion region;
 region.span.latitudeDelta = meter / 111319.5;
 region.span.longitudeDelta = 0.0;
 region.center.latitude = (SouthWest.latitude + NorthEast.latitude) / 2.0;
 region.center.longitude = (SouthWest.longitude + NorthEast.longitude) / 2.0;

 region = [mapView regionThatFits:region];
 [mapView setRegion:region animated:YES];

 [locSouthWest release];
 [locNorthEast release]; 
}

Any ideas?

Thanks!!


Solution

  • Instead of:

    region.span.latitudeDelta = meter / 111319.5;
     region.span.longitudeDelta = 0.0;
     region.center.latitude = (SouthWest.latitude + NorthEast.latitude) / 2.0;
     region.center.longitude = (SouthWest.longitude + NorthEast.longitude) / 2.0;
    

    Try adding:

    region.span.latitudeDelta = fabs(NorthEast.latitude - SouthWest.latitude) * 1.2; 
    region.span.longitudeDelta = fabs(SouthWest.longitude - NorthEast.longitude) * 1.2; 
    region.center.latitude = NorthEast.latitude - (NorthEast.latitude - SouthWest.latitude) * 0.5;
    region.center.longitude = NorthEast.longitude + (SouthWest.longitude - NorthEast.longitude) * 0.5;
    

    And removing:

    CLLocationDistance meter = [locSouthWest distanceFromLocation:locNorthEast];