π’ Interactivity & Events

The materials presented in this chapter deal with low-level APIs. If you're using a framework like React or Angular, make sure to check out the chapter on Working with Frameworks .
Try dragging and clicking on the map and to see which events get highlighted in blue.
Embed courtesy of Google's documentation
When you interact with the map canvas or its artifacts (i.e. markers, info windows, or shapes), an event
is triggered.
These events usually inherit from the google.maps.Event
class and are divided into two categories:
- User-triggered events (
click
,dblclick
,rightclick
etc), as defined in the respective Google Maps class:Map
Events ,Marker
Events ,Polygon
Events ,InfoWindow
Events etc. - State change events using a
*property*_changed
convention β e.g.position_changed
,bounds_changed
,visible_changed
and so on.
Certain traditional DOMEvents
can also bubble up from a map artifact β think clicking on some HTML content inside a custom InfoWindow
. More on this later.
Keep in mind that Google Maps doesn't expose all UI interactions. For instance, clicking on native markers (POI icons) isn't observable β you cannot listen to the click events.
Sometimes it isn't even desirable! When you place custom markers on top of the native markers and bind them to custom info windows , you don't want the native info windows to appear⦠So, to purposefully disable clicking on the native map icons, set clickableIcons: true
when initializing your Map
.
To listen to clicks on a traditional <button id="button">
HTML element, you have multiple options:
1. Add an onclick
attribute in HTML:
<!-- either as an inline function -->
<button id="button" onclick="alert('I was clicked')">
<!-- or as reference to a function -->
<button id="button" onclick="handleBtnClick">...</button>
...
</button>
2. Bind an eventListener
in JS:
const btn = document.querySelector("#button");
btn.addEventListener("click", (evt) => {
// handle clicks
});
In Google Maps, you can listen to clicks on a marker two ways:
1. Either directly on the google.maps.Marker
instance (and any MVC instance like google.maps.Polygon
, google.maps.Cirlce
etc):
marker.addListener("click", () => {
// handle clicks
});
2. Or via the event
namespace :
google.maps.event.addListener(marker, "click", () => {
// handle clicks
});
These two methods are functionally equivalent and both return a MapsEventListener
. We'll come back to storing event listeners later.
Assuming the same #button
element from above, you can programmatically trigger clicks on it in two ways:
button.click()
button.dispatchEvent(new MouseEvent("click"))
(see MDN )
In Google Maps, however, there's only one way β through the event
namespace's trigger
:
const marker = new google.maps.Marker({ ... });
google.maps.event.trigger(marker, "click");
which brings us toβ¦
Even if your map is the most prominent element on the page, it will likely not be the only element.