event handling for overlapping polygons in google maps

17 views Asked by At

Using Google Maps API, I am wondering if it is possible to get events to fire for each of multiple, overlapping polygons. As far as I have been able to determine, the google maps API only fires an event for the top-most polygon - it does not fire for polygons with lower zIndex. Is this the case, or is it somehow possible to propogate events such that they fire for all overlapping polygons?

In the example below, mouse events in the overlapping area only fire for the blue polygon. Interestingly, a mouse move from the red polygon into the overlapping area fires a "mouseout" for the red polygon - this seems to confirm that Google no longer considers the mouse to be over the red polygon (and therefore it does not fire any click events while mouse is in overlapping area).

https://jsfiddle.net/2b4tx8s1/1/

Ideally, I would love to do this via the API and supported methodology - does it exist? I suppose an alternative is to implement my own checking for where the mouse is, but I would love to avoid that.

let myLatLng = new google.maps.LatLng(0,0);
let myOptions = {
            zoom: 6,
            center: myLatLng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        
 let map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);


let polygonA = new google.maps.Polygon({
    fillColor: "blue",
    strokeColor: "blue",
    fillOpacity: .5,
    clickable: true,
    zIndex : 6,
    map: map,
    paths: [
        {lat:1,lng:1},
      {lat:-1, lng:1},
      {lat:-1,lng:-1},
      {lat:1,lng:-1}]
  });
  
let polygonB = new google.maps.Polygon({
    fillColor: "red",
    strokeColor: "red",
    fillOpacity: .5,
    clickable: true,
    zIndex : 5,
    map: map,
    paths: [
        {lat:.5,lng:.5},
      {lat:-1.5, lng:.5},
      {lat:-1.5,lng:-1.5},
      {lat:.5,lng:-1.5}]
  });

 polygonA.addListener("mousedown", (e) => {
      console.log("BLUE mousedown");
 });
 polygonA.addListener("mouseup", (e) => {
      console.log("BLUE mouseup");
 });
 polygonA.addListener("mouseout", (e) => {
      console.log("BLUE mouseout");
 });
 
 polygonB.addListener("mousedown", (e) => {
      console.log("RED mousedown");
 });
 polygonB.addListener("mouseup", (e) => {
      console.log("RED mouseup");
 });
 polygonB.addListener("mouseout", (e) => {
      console.log("RED mouseout");
 });
 
}

0

There are 0 answers