How to detect that MKMapView is zoomed out/in?
Asked Answered
H

1

9

I am writing the following code,

- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated {
    mapRegion = mapView.region; //MKCoordinateRegion myRegion in .h
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {

      MKCoordinateRegion newRegion = mapView.region;

    if (mapRegion.span.latitudeDelta != newRegion.span.latitudeDelta ||
       mapRegion.span.longitudeDelta != newRegion.span.longitudeDelta){

        NSLog(@"The zoom has changed");        
  }
}

I want to do some operation when user either zoom-in or zoom-out the MKMapView, what should I do but by applying the above code, if condition will execute either use won't zoom-in/out but just will change map?

Hako answered 5/10, 2011 at 5:52 Comment(0)
P
22

Create MKMapView+ZoomLevel.h as

#import <MapKit/MapKit.h>

@interface MKMapView (ZoomLevel)

- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                  zoomLevel:(double)zoomLevel
                   animated:(BOOL)animated;

@end 

Create MKMapView+ZoomLevel.m as

#import "MKMapView+ZoomLevel.h"

#define MERCATOR_OFFSET 268435456
#define MERCATOR_RADIUS 85445659.44705395

@implementation MKMapView (ZoomLevel)

#pragma mark -
#pragma mark Map conversion methods

- (double)longitudeToPixelSpaceX:(double)longitude
{
    return round(MERCATOR_OFFSET + MERCATOR_RADIUS * longitude * M_PI / 180.0);
}

- (double)latitudeToPixelSpaceY:(double)latitude
{
    return round(MERCATOR_OFFSET - MERCATOR_RADIUS * logf((1 + sinf(latitude * M_PI / 180.0)) / (1 - sinf(latitude * M_PI / 180.0))) / 2.0);
}

- (double)pixelSpaceXToLongitude:(double)pixelX
{
    return ((round(pixelX) - MERCATOR_OFFSET) / MERCATOR_RADIUS) * 180.0 / M_PI;
}

- (double)pixelSpaceYToLatitude:(double)pixelY
{
    return (M_PI / 2.0 - 2.0 * atan(exp((round(pixelY) - MERCATOR_OFFSET) / MERCATOR_RADIUS))) * 180.0 / M_PI;
}

#pragma mark -
#pragma mark Helper methods

- (MKCoordinateSpan)coordinateSpanWithMapView:(MKMapView *)mapView
                             centerCoordinate:(CLLocationCoordinate2D)centerCoordinate
                                 andZoomLevel:(double)zoomLevel
{
    NSLog(@"in custom zoomlevel-->%f",zoomLevel);
    // convert center coordiate to pixel space
    double centerPixelX = [self longitudeToPixelSpaceX:centerCoordinate.longitude];
    double centerPixelY = [self latitudeToPixelSpaceY:centerCoordinate.latitude];

    // determine the scale value from the zoom level
    double zoomExponent = 20.0 - zoomLevel;
    double zoomScale = pow(2, zoomExponent);

    // scale the map’s size in pixel space
    CGSize mapSizeInPixels = mapView.bounds.size;
    double scaledMapWidth = mapSizeInPixels.width * zoomScale;
    double scaledMapHeight = mapSizeInPixels.height * zoomScale;

    // figure out the position of the top-left pixel
    double topLeftPixelX = centerPixelX - (scaledMapWidth / 2);
    double topLeftPixelY = centerPixelY - (scaledMapHeight / 2);

    // find delta between left and right longitudes
    CLLocationDegrees minLng = [self pixelSpaceXToLongitude:topLeftPixelX];
    CLLocationDegrees maxLng = [self pixelSpaceXToLongitude:topLeftPixelX + scaledMapWidth];
    CLLocationDegrees longitudeDelta = maxLng - minLng;

    // find delta between top and bottom latitudes
    CLLocationDegrees minLat = [self pixelSpaceYToLatitude:topLeftPixelY];
    CLLocationDegrees maxLat = [self pixelSpaceYToLatitude:topLeftPixelY + scaledMapHeight];
    CLLocationDegrees latitudeDelta = -1 * (maxLat - minLat);

    // create and return the lat/lng span
    MKCoordinateSpan span = MKCoordinateSpanMake(latitudeDelta, longitudeDelta);
    return span;
}

#pragma mark -
#pragma mark Public methods

- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                  zoomLevel:(double)zoomLevel
                   animated:(BOOL)animated
{
    // clamp large numbers to 28
    zoomLevel = MIN(zoomLevel, 28);

    // use the zoom level to compute the region
    MKCoordinateSpan span = [self coordinateSpanWithMapView:self centerCoordinate:centerCoordinate andZoomLevel:zoomLevel];
    MKCoordinateRegion region = MKCoordinateRegionMake(centerCoordinate, span);

    // set the region like normal
    [self setRegion:region animated:animated];
}

@end 

#import "MKMapView+ZoomLevel.h" statement in your view controller where MKMapView is taken.

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{   
    double zoomLevel = [self getZoomLevel]; 
    [lblCurrentLevel setText:[NSString stringWithFormat:@"%.2f",zoomLevel]];

    NSLog(@"zoomlevel-->%f long-->%f lat-->%f",zoomLevel,mapView.region.span.longitudeDelta,mapView.region.span.latitudeDelta);
}

- (double) getZoomLevel
{
    return 21.00 - log2(objMapView.region.span.longitudeDelta * MERCATOR_RADIUS * M_PI / (180.0 * objMapView.bounds.size.width));
}

In above methods you can get zoom levels as desired, the only thing you have to do is maintain initial zoom and compare latest zoom in/out with that and assign again to that variable.

In case of any query let me know we will work out on that :D

Edit

This source code is from Troy's Blog. Apologize for not mentioning before.

Paramagnet answered 5/10, 2011 at 6:17 Comment(6)
@thank you Jennis, I will apply it then will inform you, can I have direct contact to you?Hako
There actually is an off-by-one error in coordinateSpanWithMapView. To calculate the zoomExponent, you must subtract from 21, not 20; getZoomLevel is correct.Eldoraeldorado
The source for this code was troybrant.net/blog/2010/01/set-the-zoom-level-of-an-mkmapview. Please remember to quote the source if possible. Troy Brant also wrote an excellent guide to map coordinates and zoom levels: troybrant.net/blog/2010/01/…Chagres
Done @BjornRuud Thax for pointing it out. You could also have done so :D. Thax any way.Paramagnet
For retina devices, it's even better when you use:CGSize mapSizeInPoints = self.bounds.size; CGSize mapSizeInPixels = CGSizeMake(mapSizeInPoints.width * [UIScreen mainScreen].scale, mapSizeInPoints.height * [UIScreen mainScreen].scale);Lunn
Great answer. Thanks to Jennis for posting it and thanks to @Tony Brant for the original code and blog post. I made some edits here to account for the off-by-one mentioned by Robert Altman and the retina screen size issue mentioned by Klaas. Also, I think it makes sense that getZoomLevel should be part of the category. I moved it there as "zoomLevel".Rolle

© 2022 - 2024 — McMap. All rights reserved.