Quantcast
Channel: shades of orange - JavaScript
Viewing all articles
Browse latest Browse all 4

Stop Propagation of Google Maps Marker Click Event – a Solution!

$
0
0

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:

  1. google.maps.event.addListener(marker,"click",function() {
  2.     showPopup(marker);
  3. });

to close any open marker on clicking anywhere outside the map popup:

  1. $(document).on("click.mappopup.offmap",function() {
  2.     closeAllMarkers(markers);
  3. });

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

  1. google.maps.event.addListener(marker,"click",function(ev) {
  2.     showPopup(marker);
  3.  
  4.     // does not do a thing
  5.     ev.cancelBubble=true;
  6.  
  7.     // does not exist on the passed in event object
  8.     ev.stopPropagation&& ev.stopPropagation();
  9.  
  10.     // does not exist on the passed in event object
  11.     ev.preventDefault&& ev.preventDefault();
  12.     
  13.     // what Google devs proposed but also did not work
  14.     ev.stop();
  15. });

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

  1. google.maps.event.addListener(marker,"click",function() {
  2.     showPopup(marker);
  3.  
  4.     // actually stops the event from bubbling up to the map or the document
  5.     event.preventDefault();
  6. });

And that was it! I couldn't believe that the solution was so simple.


Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images