find MKCoordinateRegion with multiple annotations


/ Published in: Objective C
Save to your folder(s)



Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.