10

If I change the region in setRegion for an MKMapView, is there a way to set the speed, or duration, of that animation change? I've looked through the documentation and the Googles, but found nothing.

Paras Joshi
  • 20,427
  • 11
  • 57
  • 70
thekevinscott
  • 5,263
  • 10
  • 44
  • 57

2 Answers2

26

And here's an easy to use Swift extension in case someone stumbles upon this in the future

import MapKit

extension MKMapView {
    func animatedZoom(zoomRegion zoomRegion:MKCoordinateRegion, duration:NSTimeInterval) {
        MKMapView.animateWithDuration(duration, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 10, options: UIViewAnimationOptions.CurveEaseIn, animations: {
        self.setRegion(zoomRegion, animated: true)
        }, completion: nil)
    }
}

Update to Swift 5:

extension MKMapView {
    func animatedZoom(zoomRegion:MKCoordinateRegion, duration:TimeInterval) {
        MKMapView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 10, options: UIView.AnimationOptions.curveEaseIn, animations: {
            self.setRegion(zoomRegion, animated: true)
            }, completion: nil)
    }
}
kernelpanic
  • 2,876
  • 3
  • 34
  • 58
6

I was able to set the duration of the setRegion animation by editing the response to the question - Setting the zoom level for a MKMapView - as follows:

#import <MapKit/MapKit.h>

@interface MKMapView (ZoomLevel)

- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                   zoomLevel:(NSUInteger)zoomLevel
                   animated:(BOOL)animated;
@end



#import "MKMapView+ZoomLevel.h"

@implementation MKMapView (ZoomLevel)

#define ANIMATION_DURATION 0.5
- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                      zoomLevel:(NSUInteger)zoomLevel animated:(BOOL)animated {
    MKCoordinateSpan span = MKCoordinateSpanMake(0, 360/pow(2,zoomLevel)*self.frame.size.width/256);
    [MKMapView animateWithDuration:ANIMATION_DURATION animations:^{
        [self setRegion:MKCoordinateRegionMake(centerCoordinate, span) animated:YES];
    }];
}
Community
  • 1
  • 1
Josh Gafni
  • 2,831
  • 2
  • 19
  • 32