Event Handling in Google Maps
Each Google Maps API object includes named events.
These events are grouped into two categories:
- User events. These are the things the user does, such as clicking or dragging in the window.
- State change notifications. These reflect changes in Maps API objects.
addListener()
method. Here's how:
- Start with the following basic Google Map. Make sure to replace
YOUR_API_KEY
in thescript
tag with your API key that you got from https://developers.google.com/maps. - Create a variable to hold the location of the marker.
- Create a marker object, and pass the location into the
position
property. - Use
addListen()
to listen for click events on the marker. - Inside the callback function, use the
setZoom()
andsetCenter()
methods to zoom the map and center it on the marker. - Open your web page in a browser.
- Click on the marker to see the results.
Your final code should look like the following:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>A Basic Map</title>
<style>
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
function initMap() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(37, -116),
mapTypeId: 'satellite'
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
</script>
</head>
<body>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
In this how-to, I'll add a marker to a map that will re-center and zoom the map when the user clicks on it.
var zoomMarker = {lat:37.629562, lng:-116.849556};
var marker = new google.maps.Marker({
position: zoomMarker,
map: map,
title: 'Click to Zoom'
});
marker.addListener('click', function() {
});
marker.addListener('click', function() {
map.setZoom(10);
map.setCenter(marker.getPosition());
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>A Basic Map</title>
<style>
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
function initMap() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(37, -116),
mapTypeId: 'satellite'
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var zoomMarker = {lat:37.629562, lng:-116.849556};
var marker = new google.maps.Marker({
position: zoomMarker,
map: map,
title: 'Click to Zoom'
});
marker.addListener('click', function() {
map.setZoom(16);
map.setCenter(zoomMarker);
});
}
</script>
</head>
<body>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDTM5RKrtCLpZAj5HU3K3cTvFNB240NsBg&callback=initMap">
</script>
</body>
</html>