Hover Functions on Google Map
Markers are small red icons that mark important locations on Google maps. Clicking a marker often opens a window that reveals helpful information about the location beneath the marker. If your Web application uses Google's Application Programming Interface to display maps, you can create a function that makes an information window appear when a mouse hovers over any marker.
-
Adding a Marker
-
Markers on a Google map move along with the map when you drag it to view different locations. The following code creates a LatLng object that allows you to add a marker to map: named map1:
var LatLng1 = new google.maps.LatLng(37.97, 121.81);
The numbers 37.97 and 121.81 represent the latitude and longitude of the location where you wish to place the marker. The code shown below creates a marker at that location.
var marker1 = new google.maps.Marker({
position:LatLng1,
title:"Marker1!"
});marker1.setMap(map1);
If the variable that holds a reference to your map has a different name, replace "map1" with that name.
Mouseover Events
-
Event listeners make it possible for objects on a Web page to respond when actions occur. Move your mouse over an image on a regular Web page, for example, and a mouseover event may cause the image to enlarge. The Google Application Programming Interface comes wtih GEvent.addDomListener, an event listener that allows you to add hover capabilities to your maps. To get a marker to display its information window, create an information window and attach a mouseover event listener to the marker.
-
Event Listener Code
-
The code shown here creates a new information window object named infowindow1. Its dimensions, which you can change, are 60 pixels wide and 70 pixels tall. The code shown creates a new information window object named infowindow1, whose width is 60 pixels and height is 70 pixels.
var infowindow1 = new google.maps.InfoWindow(
{ content: "Marker1 Info",
size: new google.maps.Size(60, 70)
});Add the following event handlers after this code, and your application is ready to display the information window when you hover your mouse over the map's marker:
google.maps.event.addListener(marker1, 'mouseover', function () {
infowindow1.open(map1, marker1);
});
google.maps.event.addListener(marker1, 'mouseout', function () {
infowindow1.close(map1, marker1);
});
Considerations
-
The last two lines of code listed in this example also create a mouseout event. This causes the information window to disappear when you move your mouse away from the marker. Add as many markers to your map as you like and set them up using these coding techniques. If your information windows are too small to hold the desired content, make them larger when you create them. When defining the latitude and longitude for your LatLng object, ensure that those coordinates lie within the map your Web page displays.
-
References
Resources
- Photo Credit Comstock/Comstock/Getty Images