Access Arguments in UI Events

Learn how to pass and access event arguments to UI events within the Maps JavaScript API.

We'll cover the following

Work with UI events

Within the Maps JavaScript API, UI events can pass event arguments that can be accessed through an event listener. These event arguments can be accessed with an event listener in the same way the properties of JavaScript objects are accessed.

For example, the click event is a UI event that passes the MouseEvent argument to the event listener. One property that the MouseEvent argument includes is latLng, which denotes the precise location where the map is clicked. The MouseEvent argument’s latLng property can be accessed with an event listener in the following way:

map.addListener("click", (MouseEvent) => {
	console.log(MouseEvent.latLng);
});

Note: The behavior mentioned above is unique to UI events since events related to state change don’t pass arguments.

An excellent example of applications that benefit from accessing latLng coordinates would be a ride-hailing applications like Uber. In ride-hailing applications, the user clicks on the map to drop their pick-up and drop-off location pins. The app then sends the coordinates of these pins and displays the corresponding markers on the assigned driver’s application.

This lesson implements a simple version of this use case in which a marker is created with every mouse click.

Code example

In the example below, a map is initialized and a marker is created anywhere the user clicks:

Console
Access arguments in UI events

Here’s a brief explanation of the JavaScript file in the above code widget:

  • Line 8: We add an event listener that listens to click events and fetches the MouseEvent argument.
  • Line 9: We access the latLng property using MouseEvent.latLng and pass it to the placeMarker() method.
  • Lines 14–19: We define the placeMarker() method. When this function is called, a new marker is created using the latLng and map parameters passed to the function.