Skip to content

Google Maps - Events

The Maps JavaScript API is interactive. Users can click, drag, and zoom, and the map itself changes state. You can listen for these occurrences, known as events, and execute custom code in response.

This allows you to build dynamic applications, such as placing a marker where a user clicks, updating information when the map view changes, or responding when a user finishes dragging a marker.

The standard way to listen for events is using the addListener() method, which is available on most API objects (like Map, Marker, Polygon, InfoWindow).

const listener = object.addListener('event_name', (eventArguments) => {
// Your code to run when the event occurs
// 'eventArguments' contains data specific to the event (e.g., LatLng for clicks)
});
  • object: The API object you want to listen to (e.g., map, marker).
  • 'event_name': A string specifying the event to listen for (e.g., 'click', 'zoom_changed').
  • (eventArguments) => { ... }: The handler function (callback) that executes when the event fires. Arrow functions are commonly used for brevity and handling this context.
  • listener: The addListener method returns a MapsEventListener object, which can be used later to remove the listener.
  • click: User clicks on the map. The handler receives a MapMouseEvent containing latLng coordinates.
  • dblclick: User double-clicks on the map.
  • rightclick: User right-clicks on the map.
  • bounds_changed: The map’s viewport bounds have changed (occurs frequently during panning/zooming).
  • center_changed: The map’s center LatLng has changed.
  • zoom_changed: The map’s zoom level has changed.
  • idle: The map has become idle after panning or zooming (useful for triggering actions after movement stops).

Common Marker Events (Marker or AdvancedMarkerView)

Section titled “Common Marker Events (Marker or AdvancedMarkerView)”
  • click: User clicks on the marker.
  • dblclick: User double-clicks on the marker.
  • rightclick: User right-clicks on the marker.
  • dragstart: User starts dragging the marker (if draggable: true).
  • drag: Marker is actively being dragged.
  • dragend: User finishes dragging the marker. The handler receives an event with latLng coordinates.

Other objects like Polygons, Polylines, and InfoWindows also have relevant events (e.g., click, closeclick for InfoWindow). Check the API reference for specifics.

Let’s add a listener that logs the coordinates whenever the user clicks on the map and places a simple marker there.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Map Click Event</title>
<style>#map { height: 400px; width: 100%; } html, body { height: 100%; margin: 0; padding: 0; }</style>
</head>
<body>
<div id="map"></div>
<script>
async function initMap() {
const mapCenter = { lat: 40.7128, lng: -74.0060 }; // NYC
const { Map } = await google.maps.importLibrary("maps");
// Import Marker library if you intend to place markers on click
const { Marker } = await google.maps.importLibrary("marker");
const map = new Map(document.getElementById("map"), {
zoom: 12,
center: mapCenter,
mapId: "DEMO_MAP_ID"
});
// Add a listener for clicks on the map
map.addListener('click', (mapsMouseEvent) => {
const clickedLatLng = mapsMouseEvent.latLng;
console.log(`Map clicked at: ${clickedLatLng.lat()}, ${clickedLatLng.lng()}`);
// Optional: Place a marker at the clicked location
new Marker({
position: clickedLatLng,
map: map,
title: `Clicked at ${clickedLatLng.lat().toFixed(4)}, ${clickedLatLng.lng().toFixed(4)}`
});
// Optional: You might want to close existing InfoWindows here
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly&libraries=marker" async defer></script>
<!-- Added libraries=marker -->
</body>
</html>

Expected Output: An interactive map of NYC. Clicking anywhere on the map will print the latitude and longitude to the browser’s console and place a new marker at that location.

Example: Opening an InfoWindow on Marker Click

Section titled “Example: Opening an InfoWindow on Marker Click”

A very common pattern is to display more information when a user clicks a marker.

<!DOCTYPE html>
<!-- ... head ... -->
<body>
<div id="map"></div>
<script>
async function initMap() {
const mapCenter = { lat: 51.5074, lng: -0.1278 }; // London
const { Map } = await google.maps.importLibrary("maps");
const { Marker } = await google.maps.importLibrary("marker");
const { InfoWindow } = await google.maps.importLibrary("maps"); // InfoWindow is in 'maps'
const map = new Map(document.getElementById("map"), {
zoom: 14,
center: mapCenter,
mapId: "DEMO_MAP_ID"
});
// Create the marker
const marker = new Marker({
position: mapCenter,
map: map,
title: 'Click for details'
});
// Create an InfoWindow
const infowindow = new InfoWindow({
content: '<h3>Central London</h3><p>Near Trafalgar Square.</p>',
ariaLabel: 'Central London Details'
});
// Add a click listener to the marker
marker.addListener('click', () => {
// Close other info windows potentially? (Good practice)
infowindow.open({
anchor: marker, // Anchor the InfoWindow to our marker
map: map // Specify the map it belongs to
});
});
// Optional: Close infowindow if map is clicked elsewhere
// map.addListener('click', () => {
// infowindow.close();
// });
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly&libraries=marker,maps" async defer></script>
<!-- Added libraries=marker,maps -->
</body>
</html>

Expected Output: A map of London with a marker. Clicking the marker opens a small pop-up window (InfoWindow) with the specified HTML content.

The handler function often receives arguments containing event-specific data. The most common is the latLng property for mouse events.

marker.addListener('dragend', (event) => {
const newPosition = event.latLng;
alert(`Marker dropped at: ${newPosition.lat()}, ${newPosition.lng()}`);
});
map.addListener('zoom_changed', () => {
const newZoom = map.getZoom();
console.log('Zoom level changed to:', newZoom);
});

Consult the API reference for the specific event to see what arguments are passed to the handler.

If you no longer need an event listener (e.g., to prevent memory leaks or duplicate actions), you should remove it. Use the remove() method on the MapsEventListener object that was returned when you added the listener.

// Add the listener and store the handle
const mapClickListener = map.addListener('click', (event) => {
console.log('Map clicked!');
// Maybe only listen for the first click?
removeMapClickListener();
});
// Function to remove the listener
function removeMapClickListener() {
if (mapClickListener) {
mapClickListener.remove();
console.log('Map click listener removed.');
}
}
// Example: Remove the listener after 5 seconds
// setTimeout(removeMapClickListener, 5000);

Alternatively, the older static method google.maps.event.removeListener(listenerObject) still works.