Rizon Rizon - 7 months ago 42
Objective-C Question

Check whether zoom level changed

I'm using MapKit on iPhone.
How can I know when the user changes the zoom level (zoom in\out the map)?

I've tried to use mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated; but that's called even when the map is only dragged.
Unfortunately, when the map is dragged the mapView.region.span changes as well...




It is pretty simple to calculate the zoom level. See the snippet below. You can get the mRect parameter from the visibleMapRect property on your MKMapView instance.

+ (NSUInteger)zoomLevelForMapRect:(MKMapRect)mRect withMapViewSizeInPixels:(CGSize)viewSizeInPixels
    NSUInteger zoomLevel = MAXIMUM_ZOOM; // MAXIMUM_ZOOM is 20 with MapKit
    MKZoomScale zoomScale = mRect.size.width / viewSizeInPixels.width; //MKZoomScale is just a CGFloat typedef
    double zoomExponent = log2(zoomScale);
    zoomLevel = (NSUInteger)(MAXIMUM_ZOOM - ceil(zoomExponent));
    return zoomLevel;

You could probably just stop at the step for calculating the zoomScale as that will tell you if the zoom has changed at all.

I figured this stuff out from reading Troy Brants excellent blog posts on the topic: