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.