Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect GMSMapView zoom

Is there a way, to detect zoom (pinch and double tap) in this Google Map Services component?

- (void)mapView:(GMSMapView *)mapView willMove:(BOOL)gesture

Above method fire regardless of the movement made.

like image 358
Cyril Avatar asked Mar 29 '14 18:03

Cyril


1 Answers

There's an another way to detect whenever zoom (or any other property for that matter) has been changed - Key-Value-Observing (aka KVO). It's especially useful when there's no delegate method provided for us to use. From Apple docs:

Key-value observing provides a mechanism that allows objects to be notified of changes to specific properties of other objects.

Wherever you set up your map view add this snippet:

[self.mapView addObserver:self forKeyPath:@"camera.zoom" options:0 context:nil];

Now you only have to implement -observeValueForKeyPath:ofObject:change:context: method to actually receive a callback. Like so:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

if ([keyPath isEqualToString:@"camera.zoom"]) {

    // this static variable will hold the last value between invocations.
    static CGFloat lastZoom = 0;

    GMSMapView *mapView = (GMSMapView *)object;
    CGFloat currentZoom = [[mapView camera] zoom];

    if (!(fabs((lastZoom) - (currentZoom)) < FLT_EPSILON)) {

        //Zoom level has actually changed!
        NSLog(@"Zoom changed to: %.2f", [[mapView camera] zoom]);

    }

    //update last zoom level value.
    lastZoom = currentZoom;

    }
}

Don't forget to remove observer in -dealloc or -viewDidDissapear depending on your needs:

- (void)dealloc {

    [self.mapView removeObserver:self forKeyPath:@"camera.zoom"];

}

Happy coding :-)

like image 190
NKorotkov Avatar answered Sep 22 '22 01:09

NKorotkov