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...
Help?
10x
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:
http://troybrant.net/blog/2010/01/mkmapview-and-zoom-levels-a-visual-guide/
Swift 3
extension MKMapView {
var zoomLevel: Int {
let maxZoom: Double = 20
let zoomScale = self.visibleMapRect.size.width / Double(self.frame.size.width)
let zoomExponent = log2(zoomScale)
return Int(maxZoom - ceil(zoomExponent))
}
}