Skip to content

Instantly share code, notes, and snippets.

@ttsubono
Created June 25, 2012 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ttsubono/2988074 to your computer and use it in GitHub Desktop.
Save ttsubono/2988074 to your computer and use it in GitHub Desktop.
MKMapViewの地図をピン(annotation)が全て表示される大きさに調整する
//
// initでannotationクラスのcoordinateプロパティにINVALID_COORDINATEをセットしておき、
// coordinateプロパティがまだセットされていない状態であることを示す。
//
// if (CLLocationCoordinate2DIsValid(coordinate))で検証する
//
#define INVALID_LOCATION_DEGREE -1000
#define INVALID_COORDINATE CLLocationCoordinate2DMake(INVALID_LOCATION_DEGREE, INVALID_LOCATION_DEGREE)
// 最低限の地図の大きさ
#define MINIMUM_MAP_SPAN MKCoordinateSpanMake(0.002, 0.002)
- (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) {
if (CLLocationCoordinate2DIsValid(annotation.coordinate)) {
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;
// 端ギリギリにピンが立つのを避けるため少し広げる
region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1;
region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1;
// 拡大しすぎの場合は最低限の縮尺にする
region.span.latitudeDelta = fmax(MINIMUM_MAP_SPAN.latitudeDelta, region.span.latitudeDelta);
region.span.longitudeDelta = fmax(MINIMUM_MAP_SPAN.longitudeDelta, region.span.longitudeDelta);
region = [mapView regionThatFits:region];
[mapView setRegion:region animated:YES];
}