by Oliver
18. September 2015 18:55
Here's a simple scenario using Google Maps Javascript API v3 that until today I could not get to work properly:
Open a custom map popup window after clicking on a map marker, and close it when clicking anywhere on the map or the rest of the surrounding page.
The code I tried
to open the map on click of a marker:
- google.maps.event.addListener(marker, "click", function() {
- showPopup(marker);
- });
to close any open marker on clicking anywhere outside the map popup:
- $(document).on("click.mappopup.offmap", function() {
- closeAllMarkers(markers);
- });
The problem I was facing was that the click event that was triggered on the marker would bubble all the way up to the document and the map popup would barely show up when it was already being closed again.
Looking for a solution on the web I stumbled upon this old thread on Google code in which several attempts were made to fix the issue and a maps API team member even announced the bug as fixed, but no-one seemed to actually have actually solved the problem.
Things I've tried according to the above thread
- google.maps.event.addListener(marker, "click", function(ev) {
- showPopup(marker);
-
- // does not do a thing
- ev.cancelBubble = true;
-
- // does not exist on the passed in event object
- ev.stopPropagation && ev.stopPropagation();
-
- // does not exist on the passed in event object
- ev.preventDefault && ev.preventDefault();
-
- // what Google devs proposed but also did not work
- ev.stop();
- });
But then I stumbled upon this answer on stackoverflow in which the author mentions: Keep in mind that if you pass "event" as an argument to the handler function you will get a custom Google maps click event which does not have stopPropagation method. And that brought me on the right track!
So I removed the ev parameter from the handler and used the global event object to try and stop it from bubbling up. After trying a few combinations of the above code I settled with this one:
The Working Code
- google.maps.event.addListener(marker, "click", function() {
- showPopup(marker);
-
- // actually stops the event from bubbling up to the map or the document
- event.preventDefault();
- });
And that was it! I couldn't believe that the solution was so simple.