Listeners
What if we want to make our icon clickable? Let's add a click
listener our marker to make it do stuff!
Click Listener
There are many, many different types of listeners. Some look for a keypress on a keyboard, like a keylogger. Some look for the re-sizing of a window, then perform an action. We are using the "click" listener, which fires when the selected element is clicked with a mouse. Enter this block of code after the marker object declaration:
let contentString = '<div id="content"><h2 id="firstHeading" class="firstHeading">Custom info window</h2><p>This is a cool custom info window.</p></div>';
let infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
Info Window
Let's break down what we're doing here. Our goal in this section is to make a window appear when clicking the marker. You can see in the last portion of the above code that we are adding a listener to marker, which listens specifically for click. When someone clicks the marker, we're opening infowindow
.
What is an info window? The name kind of speaks for itself, but let's check out the docs to see what it is specifically used for in this API. Per Google: An InfoWindow displays content (usually text or images) in a popup window above the map, at a given location
. Cool, so we know we can use text or images in a pop up window.
The docs also tell us how to make one:
var infowindow = new google.maps.InfoWindow({
content: contentString
});
As you can see in the above code, we just used the docs example to create an InfoWindow with information we wanted inside of it. You can change the text in the contentString
to anything you'd like.
Last updated