Search code examples
google-maps-api-3clickevent-bubbling

Google Map API - Map click event not fired under Polygon, Circle, Rectangle?


In Google Maps API, when listening to click events from the Map object, the event will not be fired when a Polygon, Circle, Rectangle is clicked.

How to bubble up the click event to the Map object?

  const circle = new google.maps.Circle({
    center,
    radius,
    map,
  });

  // This event will not fire when clicking the circle
  map.addListener("click", (e) => {
    console.log('map click');
  })

Example: https://jsfiddle.net/rphsf32e/14/
Clicking on the map will add a marker. However, if the click is over the circle, the click event will not fire from the map. Only from the circle.


Solution

  • Simplest solution is to make the Circle (and Polygon/Rectangle) "unclickable", set the property: clickable: false in the constructor:

    const circle = new google.maps.Circle({
      center: myLatlng,
      radius: 100000,
      map,
      clickable: false
    })
    

    (or set it using the .setOptions method on those objects)

    proof of concept fiddle

    screenshot w/ markers after clicking on circle

    code snippet:

    function initMap() {
      const myLatlng = { lat: -25.363, lng: 131.044 };
      const map = new google.maps.Map(document.getElementById("map"), {
        zoom: 7,
        center: myLatlng,
      });
      
      const circle = new google.maps.Circle({
        center: myLatlng,
        radius: 100000,
        map,
        clickable: false
      })
      
      circle.addListener("click", (e) => {
        alert('inside circle');
        console.log(e)
      });
    
      map.addListener("click", (e) => {
        new google.maps.Marker({
            position: e.latLng,
            map,
            title: `${ e.latLng.lat() }, ${ e.latLng.lng() }`,
        });
      })
    }
    /* Always set the map height explicitly to define the size of the div
           * element that contains the map. */
    #map {
      height: 100%;
    }
    /* Optional: Makes the sample page fill the window. */
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <!DOCTYPE html>
    <html>
      <head>
        <title>Simple Click Events</title>
        <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
        <!-- jsFiddle will insert css and js -->
      </head>
      <body>
        <div id="map"></div>
        <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
        <script
          src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"
          async
        ></script>
      </body>
    </html>