Skip to content

Instantly share code, notes, and snippets.

@robmooney
Created April 16, 2011 17:07
Show Gist options
  • Save robmooney/923301 to your computer and use it in GitHub Desktop.
Save robmooney/923301 to your computer and use it in GitHub Desktop.
Get the MKCoordinateRegion that encompasses a set of MKAnnotations
// returns a MKCoordinateRegion that encompasses an array of MKAnnotations
- (MKCoordinateRegion)regionForAnnotations:(NSArray *)annotations {
CLLocationDegrees minLat = 90.0;
CLLocationDegrees maxLat = -90.0;
CLLocationDegrees minLon = 180.0;
CLLocationDegrees maxLon = -180.0;
for (id <MKAnnotation> annotation in annotations) {
if (annotation.coordinate.latitude < minLat) {
minLat = annotation.coordinate.latitude;
}
if (annotation.coordinate.longitude < minLon) {
minLon = annotation.coordinate.longitude;
}
if (annotation.coordinate.latitude > maxLat) {
maxLat = annotation.coordinate.latitude;
}
if (annotation.coordinate.longitude > maxLon) {
maxLon = annotation.coordinate.longitude;
}
}
MKCoordinateSpan span = MKCoordinateSpanMake(maxLat - minLat, maxLon - minLon);
CLLocationCoordinate2D center = CLLocationCoordinate2DMake((maxLat - span.latitudeDelta / 2), maxLon - span.longitudeDelta / 2);
return MKCoordinateRegionMake(center, span);
}
@sanju-naik-zz
Copy link

No need of this anymore, From iOS 7 We can directly use this Api to set the region so all the given annotations are visible.

self.mapView.showAnnotations(annotations, animated: true)

@BrentMifsud
Copy link

No need of this anymore, From iOS 7 We can directly use this Api to set the region so all the given annotations are visible.

self.mapView.showAnnotations(annotations, animated: true)

That fine if you want to zoom everything to fit in the center of the map. But sometimes you want to offset it (like if you have a bottom sheet that covers half the map).

You need to be able to get a region that fits the coordinates to offset it. So this is still valid code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment