Posted By

mlecho on 04/25/11


Tagged

mapping


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

mlecho
vaishnavi
Tintenklecks


find MKCoordinateRegion with multiple annotations


 / Published in: Objective C
 

  1. -(void)zoomToFitMapAnnotations:(MKMapView*)mapView
  2. {
  3. if([mapView.annotations count] == 0)
  4. return;
  5.  
  6. CLLocationCoordinate2D topLeftCoord;
  7. topLeftCoord.latitude = -90;
  8. topLeftCoord.longitude = 180;
  9.  
  10. CLLocationCoordinate2D bottomRightCoord;
  11. bottomRightCoord.latitude = 90;
  12. bottomRightCoord.longitude = -180;
  13.  
  14. for(MapAnnotation* annotation in mapView.annotations)
  15. {
  16. topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
  17. topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
  18.  
  19. bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
  20. bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
  21. }
  22.  
  23. MKCoordinateRegion region;
  24. region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
  25. region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
  26. region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; // Add a little extra space on the sides
  27. region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1; // Add a little extra space on the sides
  28.  
  29. region = [mapView regionThatFits:region];
  30. [mapView setRegion:region animated:YES];
  31. }

Report this snippet  

You need to login to post a comment.