Google Maps Events
Click marker to zoom map - Events bound to Google Maps.
Click Marker to Zoom Map
We are still using the map of London, UK, from the previous article.
Implement the zoom map function when the user clicks on the marker (bind the map zoom event on marker click).
Code example:
Example
// Zoom to 9 when clicking on marker
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(9);
map.setCenter(marker.getPosition());
});
Use the addListener()
event handler to register event listeners. This method takes an object, an event to listen for, and a function that will be called when the specified event occurs.
Reset Marker
We change the 'center' property by adding an event handler to the map. The following code uses the center_changed
event to move the marker back to the center after 3 seconds:
Example
google.maps.event.addListener(map, 'center_changed', function() {
window.setTimeout(function() {
map.panTo(marker.getPosition());
}, 3000);
});
Open Info Window on Marker Click
Display some text information in an info window when the marker is clicked:
Example
Set Marker and Open Info Window for Each Marker
Execute a window when the user clicks on the map.
Place a marker at the specified location and open an info window when the user clicks on a location on the map using the placeMarker()
function:
Example
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
function placeMarker(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);
}