Google Map's Double Click Event Propagation

Morrowind789 picture Morrowind789 · Jun 28, 2013 · Viewed 9.6k times · Source

This question is asked often, but never really answered well. Let's see if we can remedy it!

Event Propagation

Google allows you to bind to events in a Google Map View via their API using event handlers.

Sometimes you may bind your event handler to an event that Google itself is already bound to. Thus, when your event fires and does whatever you told it to do you may find Google also doing its own little thing at the same time.

Hmm, can I handle the event so my code runs, but stop the event from continuing on and firing Google's event handler?

You sure can! Welcome to Event Propagation (aka Event Bubbling).

Take a look at this code

Here I bind an event handler to double clicking on the Google Map:

var aListener = google.maps.event.addListener(map, 'dblclick', function(event) {
    // Try to prevent event propagation to the map
    event.stop();
    event.cancelBubble = true;
    if (event.stopPropagation) {
        event.stopPropagation();
    }
    if (event.preventDefault) {
        event.preventDefault(); 
    } else {
        event.returnValue = false;  
    }
});

Here map is a Google Map object to bind to.

This doesn't work. The event bubbles, and the map zooms in. I don't know why.

You ask, have you read the documentation?

Indeed. The documentation says to use event.stop();

I have looked at what others are saying. This issue is exactly my problem. It was marked as fixed, but the solution does not work.

Ideas?

Workaround

A possible workaround for the doubleclick event is to disable Google's default behavior when you need it to not fire, and then re-enable it later.

You do this with the disableDoubleClickZoom argument. See the documentation here.

Here is some code to disable:

map.set("disableDoubleClickZoom", true);

Now to re-Enable:

map.set("disableDoubleClickZoom", false);

Of course, you can set the property in the MapOptions argument for when the map object is created in the first place.

Answer

Oliver picture Oliver · Sep 18, 2015

UPDATE: Unfortunately, I had to find out that Firefox does not make the current event accessible via window.event thus this code won't work there. I haven't found a workaround for that, yet.


It turns out the fix to your code is minimal: just remove the event parameter from your event handler function, thus accessing the global window.event object inside the handler.

The following example code worked for me in IE and Chrome, but not Firefox:

google.maps.event.addListener(map, "dblclick", function(googleMapsEvent) {
    console.debug("caught double click");
    // reference the global event object
    // ignore the googleMapsEvent passed in by Google Maps!
    event.preventDefault();
});

This answer put me on the right track!