⚡ GMapsBook.com is crafted by Jozef Sorocin (🟢 Book a consulting hour) and powered by:
<aside> 🔑 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.
</aside>
Google Maps’ true power lies in exposing mouse and keyboard events for us to work with.
<aside> 🕹️ Try dragging and clicking on the map and to see which events get highlighted in blue.
[Embed courtesy of Google’s documentation](https://geo-devrel-javascript-samples.web.app/samples/map-events/app/dist/)
Embed courtesy of Google’s documentation
</aside>
When you interact with the map canvas or its artifacts (i.e. markers, info windows, or shapes), an event
is triggered.
<aside>
🔑 These events usually inherit from the google.maps.Event
class and are divided into two categories:
click
, dblclick
, rightclick
etc), as defined in the respective Google Maps class: Map
Events, Marker
Events, Polygon
Events, InfoWindow
Events etc.*property*_changed
convention
→ e.g. position_changed
, bounds_changed
, visible_changed
and so on.
</aside>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.
<aside> ⚠️ 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
.
</aside>
To listen to clicks on a traditional <button id="button">
HTML element, you have multiple options:
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">
Bind an eventListener
in JS:
const btn = document.querySelector("#button");
btn.addEventListener('click',
(evt) => {
// handle clicks
},
);