Events on Google Maps

Zoom when the marker is clicked

We still use the map from the previous page: a map centered on London, UK.

Now, we want to zoom when the user clicks on the marker (we attach an event handler to the marker so that the map zooms when clicked).

This is the code added:

Example

// Zoom to 9 when the marker is clicked
google.maps.event.addListener(marker,'click',function() {
  map.setZoom(9);
  map.setCenter(marker.getPosition());
});

We use the addListener() event handler to register event notifications. The parameters accepted by this method are:

  • An object
  • An event to listen to
  • A function called when a specified event occurs

Pan back to the marker

Here, we save the zoom change and pan the map after 3 seconds:

Example

google.maps.event.addListener(marker,'click',function() {
  var pos = map.getZoom();
  map.setZoom(9);
  map.setCenter(marker.getPosition());
  window.setTimeout(function() {map.setZoom(pos);},3000);
});

Open an info window when the marker is clicked

An info window containing text will be displayed when the marker is clicked:

Example

var infowindow = new google.maps.InfoWindow({
  content: "Hello World!"
});
google.maps.event.addListener(marker, 'click', function() {
  infowindow.open(map, marker);
});

Set the marker and open an info window for each marker

The function runs when the user clicks on the map.

The placeMarker() function will place a marker at the user's click location and display an info window containing the latitude and longitude of the marker:

Example

google.maps.event.addListener(map, 'click', function(event) {
  placeMarker(map, event.latLng);
});
function placeMarker(map, location) {
  var marker = new google.maps.Marker({
    position: location,
    map: map
  });
  var infowindow = new google.maps.InfoWindow({
    content: 'Latitude: ' + location.lat() +
    '<br>Longitude: ' + location.lng()
  });
  infowindow.open(map, marker);
{}