MapKit:如何平移和缩放以适合我的所有注释?

时间:2010-07-23 07:01:47

标签: iphone ios4 mapkit

所以我在地图上散布了一堆注释......一切都只是花花公子。现在我需要能够设置地图的位置和缩放,以便它们完全适合。我怎么能这样做?

2 个答案:

答案 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)