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
One way to detect the browser zoom level is to use the window. devicePixelRatio property. When we zoom in or out, the resize event will be triggered.
If you are using a mouse, you can hold down the keyboard Ctrl key and use the mouse wheel to zoom in or out. When you do this, you will see an icon on the right side of the address bar, indicating the zoom level has deviated from the default.
Currently there is no way to detect the zoom level with Javascript reliably.
min-width: 100%; This will freeze the width, you can do the same for height too.
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)) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With