Search code examples
javascriptgoogle-mapsgoogle-maps-api-3

How to listen for user generated zoom in Google Maps?


I want to know when a Google Maps zoom_changed event is fired specifically by a user interaction with the +/- zoom buttons. If I use a general event listener for zoom_changed, I can't tell if it is a user-generated event or a zoom change caused by something like fitBounds(). Looking for the best way to do this.

I've tried the following things, none of which seem to work:

1) Looked for event information on zoom_changed. There appears to be none.

2) Add listeners for mouseover and mouseout that let me set a flag to see if the user is in the map bounds, and check the flag on zoom_changed. This doesn't work because the map does not consider the zoom buttons as part of the map frame (in other words, hovering over zoom buttons triggers the mouseout event).

3) Add a normal (non-gMap) listener to the zoom buttons. However, I can't find a definitive CSS selector that will allow me to grab just the buttons.

4) Looked for a function in the gMaps API that would let me do something like getZoomElements(), and then I could set listeners using that.

The weird thing is I can clearly do what I want if I add a custom control to the map. It seems very odd that they would force me to do that instead of having a hook into the default zoom controls.


Solution

  • I wouldn't just hook in to the +/- buttons (or buttons on your own custom control for that matter). The user can change the zoom on the map with the mouse wheel, or by double-clicking on the map. Plus, you'd be relying on implementation detail rather than documented API, which is a major no-no.

    This really means the only reliable, documented way to detect a change in zoom is to listen to the zoom_changed event of the Map.

    If your event handler can't determine whether the event came from user action or an API call, there's two approaches:

    • Set a flag before calling an API function so that you know you can ignore this change.
    • Can you re-architect your app such that it does not matter whether a zoom change came from code or the user?