DEV Community

Usaid
Usaid

Posted on

7 1

Adding a button with onclick on InfoWindow - Google Maps API

InfoWindow in google maps is a type of toast div or should I say a popover that appears when we hover over the map marker, it contains information about a specific place anything you want to show in it.

  • Let me show you the easiest way to add a button with onclick function inside the infoWindow content string if nothing else is working or if you are trying to click on 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>";

Enter fullscreen mode Exit fullscreen mode
  • Adding click event on your function:
google.maps.event.addListener(infoWindow, 'domready' () => {
 const someButton = document.getElementById('btn-click');
 if (someButton) {
   google.maps.listener.addDomListener(someButton, 'click',    
   () => {
           // show something.
           // add something.
         })
 }
});

Enter fullscreen mode Exit fullscreen mode
  • Marker Code:
google.maps.event.addListener(marker, 'mouseover', function(){
 // some code about setting content inside info window or showing up the info window however you want to show it.
});
Enter fullscreen mode Exit fullscreen mode
That's it, let me know if it worked :).

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

nextjs tutorial video

📺 Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay