Prevent scrolling in a MKMapView, also when zooming

Nils Munch picture Nils Munch · Aug 6, 2012 · Viewed 8.3k times · Source

The scrollEnabled seems to be breakable once the user starts pinching in a MKMapView.

You still can't scroll with one finger, but if you scroll with two fingers while zooming in and out, you can move the map.

I have tried :

  • Subclassing the MKMapKit to disable the scroll view inside it.
  • Implementing –mapView:regionWillChangeAnimated: to enforce the center.
  • Disabling scrollEnabled.

but with no luck.

Can anyone tell me a sure way to ONLY have zooming in a MKMapView, so the center point always stays in the middle ?

Answer

Felix picture Felix · Aug 14, 2012

You can try to handle the pinch gestures yourself using a UIPinchGestureRecognizer:

First set scrollEnabled and zoomEnabled to NO and create the gesture recognizer:

UIPinchGestureRecognizer* recognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self
                                                                                 action:@selector(handlePinch:)];
[self.mapView addGestureRecognizer:recognizer];

In the recognizer handler adjust the MKCoordinateSpan according to the zoom scale:

- (void)handlePinch:(UIPinchGestureRecognizer*)recognizer
{
    static MKCoordinateRegion originalRegion;
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        originalRegion = self.mapView.region;
    }    

    double latdelta = originalRegion.span.latitudeDelta / recognizer.scale;
    double londelta = originalRegion.span.longitudeDelta / recognizer.scale;

    // TODO: set these constants to appropriate values to set max/min zoomscale
    latdelta = MAX(MIN(latdelta, 80), 0.02);
    londelta = MAX(MIN(londelta, 80), 0.02);
    MKCoordinateSpan span = MKCoordinateSpanMake(latdelta, londelta);

    [self.mapView setRegion:MKCoordinateRegionMake(originalRegion.center, span) animated:YES];
}

This may not work perfectly like Apple's implementation but it should solve your issue.