javascriptreactjsgoogle-mapsgoogle-map-react

Handle button events inside of google.maps.infoWindow - ReactJS


I'm trying to handle the click event of a button inside a google.maps.infoWindow. I tried to pass the function name to onClick via infoWindow contents but didn't work. So, I moved to getElementById but also without success.The return of getElementById("polyButton") is null (Cannot read property 'addEventListener' of null ).

The code:


 fpolylineHandler(event) {
    console.log("handler", event);
  }

 infoPolyline(Polyline, map, maps, event) {
    var infowindow = new maps.InfoWindow({
      content: " ",
    });

    
    infowindow.setContent(
      "<div style='color: black'>" +
        "<p>Event Name: " +
        "</p>" +
        "<p>Event Type: " +
        "</p>" +
        "<p>Cause: " +
        "</p>" +
        "<p>Date: " +
        "</p>" +
        "<p>Time: " +
        "</p>" +
        "<button id='polyButton'>Click me</button>" +
        "</div>"
    );

    var btn = document.getElementById("polyButton");
    btn.addEventListener("click", this.fpolylineHandler.bind(this));

    infowindow.setPosition(event.latLng);
    infowindow.open(map, Polyline);
  }

for reference, I tried to use onClick like this:

...
 infowindow.setContent(
      "<div style='color: black'>" +
        "<p>Event Name: " +
        "</p>" +
        "<p>Event Type: " +
        "</p>" +
        "<p>Cause: " +
        "</p>" +
        "<p>Date: " +
        "</p>" +
        "<p>Time: " +
        "</p>" +
        "<button id='polyButton'onClick='this.fpolylineHandler'>Click me</button>" +
        "</div>"
    );

...

The interesting part was when using onClick='this.fpolylineHandler()' appeared an error saying that was not a function. On the example above, simply does nothing.


Solution

  • Even reading after mounted on dom, the element doesn't exists yet on maps. So, to solve this issue, we need to add a dom listener:

     maps.event.addListener(infowindow, "domready", function () {
    
          document.getElementById("polyButton").onclick=fpolylineHandler
      
        });