Skip to content
All writing

September 20, 2021 · 1 min read

Adding a button with onClick on InfoWindow (Google Maps API)

How to inject a working button into a Google Maps InfoWindow content string and bind a click handler that fires even before the DOM is fully ready.

#javascript#google-maps

InfoWindow in Google Maps is a popover that appears over a marker — it can hold any content you want.

Let me show you the easiest way to add a button with an onClick handler inside the InfoWindow content string when nothing else is working, or when you're trying to click the button before the DOM is ready.

Content string:

let buttonName = 'any name'
let contentString = '<div>' +
                     // other divs ....
                      "<button id='btn-click'>" + buttonName +
                       '</button>' +
                     // other divs ....
                    '</div>'

Bind the click via the domready event:

google.maps.event.addListener(infoWindow, 'domready', () => {
  const someButton = document.getElementById('btn-click')
  if (someButton) {
    google.maps.event.addDomListener(someButton, 'click', () => {
      // show something
      // add something
    })
  }
})

Marker side:

google.maps.event.addListener(marker, 'mouseover', function () {
  // set content + open infoWindow
})

That's it.