所以我在地图上散布了一堆注释......一切都只是花花公子。现在我需要能够设置地图的位置和缩放,以便它们完全适合。我怎么能这样做?
答案 0 :(得分:5)
@interface MKMapView (zoomToFit)
- (void)zoomToFitOverlays; //Animation defaults to YES
- (void)zoomToFitOverlay:(id<MKOverlay>)anOverlay;
- (void)zoomToFitOverlays:(NSArray *)someOverlays;
- (void)zoomToFitOverlaysAnimated:(BOOL)animated;
- (void)zoomToFitOverlay:(id<MKOverlay>)anOverlay animated:(BOOL)animated;
- (void)zoomToFitOverlays:(NSArray *)someOverlays animated:(BOOL)animated;
- (void)zoomToFitOverlays:(NSArray *)someOverlays animated:(BOOL)animated insetProportion:(CGFloat)insetProportion; //inset 0->1, defaults in other methods to .1 (10%)
@end
@implementation MKMapView (zoomToFit)
#pragma mark -
#pragma mark Zoom to Fit
- (void)zoomToFitOverlays {
[self zoomToFitOverlaysAnimated:YES];
}
- (void)zoomToFitOverlay:(id<MKOverlay>)anOverlay {
[self zoomToFitOverlay:[NSArray arrayWithObject:anOverlay] animated:YES];
}
- (void)zoomToFitOverlays:(NSArray *)someOverlays {
[self zoomToFitOverlays:someOverlays animated:YES];
}
- (void)zoomToFitOverlaysAnimated:(BOOL)animated {
[self zoomToFitOverlays:self.overlays animated:animated];
}
- (void)zoomToFitOverlay:(id<MKOverlay>)anOverlay animated:(BOOL)animated {
[self zoomToFitOverlays:[NSArray arrayWithObject:anOverlay] animated:YES];
}
- (void)zoomToFitOverlays:(NSArray *)someOverlays animated:(BOOL)animated {
[self zoomToFitOverlays:someOverlays animated:animated insetProportion:.1];
}
- (void)zoomToFitOverlays:(NSArray *)someOverlays animated:(BOOL)animated insetProportion:(CGFloat)insetProportion {
//Check
if ( !someOverlays || !someOverlays.count ) {
return;
}
//Union
MKMapRect mapRect = MKMapRectNull;
if ( someOverlays.count == 1 ) {
mapRect = ((id<MKOverlay>)someOverlays.lastObject).boundingMapRect;
} else {
for ( id<MKOverlay> anOverlay in someOverlays ) {
mapRect = MKMapRectUnion(mapRect, anOverlay.boundingMapRect);
}
}
//Inset
CGFloat inset = (CGFloat)(mapRect.size.width*insetProportion);
mapRect = [self mapRectThatFits:MKMapRectInset(mapRect, inset, inset)];
//Set
MKCoordinateRegion region = MKCoordinateRegionForMapRect(mapRect);
[self setRegion:region animated:animated];
}
@end
答案 1 :(得分:4)