If you want to incorporate event listening in your code, consider using the google.maps.event.addListener
:
In the browser, JavaScript operates on events, meaning it responds to interactions by producing events and expects a program to pay attention to these events. There are two main types of events:
- User events (like "click" mouse events) that transfer from the DOM to the Google Maps JavaScript API. These events differ from standard DOM events.
- MVC state change notifications which reflect changes in Maps JavaScript API objects and follow a convention named
property_changed
.
Every Maps JavaScript API object provides various named events. Programs interested in specific events can register JavaScript event listeners for those events and execute relevant code when the events occur by utilizing addListener()
to attach event handlers on the object.
You may also refer to this sample code mentioned in this post:
var geocoder;
var map;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
setMarkers(map,locations);
}
google.maps.event.addDomListener(window, "load", initialize);
var locations = [
['Bondi Beach', -33.890542, 151.274856,,, 'Bondi Beach', 4],
['Coogee Beach', -33.923036, 151.259052,,,'Coogee Beach', 5],
['Cronulla Beach', -34.028249, 151.157507,,,'Cronulla Beach', 3],
['Manly Beach', -33.80010128657071, 151.28747820854187,,, 'Manly Beach', 2],
['Maroubra Beach', -33.950198, 151.259302,,,'Maroubra Beach', 1]
];
function setMarkers(map, locations) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var item = locations[i];
var myLatLng = new google.maps.LatLng(item[1], item[2]);
bounds.extend(myLatLng);
var address = item[5];
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
});
var content = address;
var infowindow = new google.maps.InfoWindow()
google.maps.event.addListener(marker, 'mouseover', (function (marker, content, infowindow) {
return function () {
infowindow.setContent(content);
infowindow.open(map, marker);
};
})(marker, content, infowindow));
google.maps.event.addListener(marker, 'mouseout', (function (marker, content, infowindow) {
return function () {
infowindow.close();
};
})(marker, content, infowindow));
}
map.fitBounds(bounds);
}
This code snippet is available on jsfiddle. It should function properly if your event listener does not clash with other listeners.
I hope this explanation proves beneficial.