Marker and polygon tooltips in Google Maps v3

September 15th, 2011 | by David |

Before I get into the details, please note that this is a quick & dirty solution using google.maps.InfoWindow. No demo, sorry, but please add your improvements in the comments!

Marker tooltip

I start with the marker, as it is the simplest implementation:

function attachMarkerInfoWindow(marker, html)
{
	marker.infoWindow = new google.maps.InfoWindow({
		content: html,
	});
	google.maps.event.addListener(marker, 'mouseover', function() {
		marker.infoWindow.open(map,marker);
	});
	google.maps.event.addListener(marker, 'mouseout', function() {
		marker.infoWindow.close();
	});
}

var marker = new google.maps.Marker({
	position: new google.maps.LatLng(56.183182,15.593239),
});

attachMarkerInfoWindow(marker, '<strong>Softhouse office</strong>');

Polygon tooltip

A polygon does not contain a single position, so where should the tooltip show? One option is to calculate the center of the polygon using getCenter() on google.maps.LatLngBounds, but I decided to use the position of the mouseover event as the position of the InfoWindow. Think about it; the center of the polygon may not actually be inside the polygon!

As a bonus I change the fill opacity while the mouse cursor is inside the polygon.

function attachPolygonInfoWindow(polygon, html)
{
	polygon.infoWindow = new google.maps.InfoWindow({
		content: html,
	});
	google.maps.event.addListener(polygon, 'mouseover', function(e) {
		var latLng = e.latLng;
		this.setOptions({fillOpacity:0.1});
		polygon.infoWindow.setPosition(latLng);
		polygon.infoWindow.open(map);
	});
	google.maps.event.addListener(polygon, 'mouseout', function() {
		this.setOptions({fillOpacity:0.35});
		polygon.infoWindow.close();
	});
}

var polygon = new google.maps.Polygon(/* omitted for brevity */);
attachPolygonInfoWindow(polygon, '<strong>Info about this area</strong>');
  1. 2 Responses to “Marker and polygon tooltips in Google Maps v3”

  2. By Danne on Sep 15, 2011 | Reply

    I use this code to work with more advanced “tooltips”.

    http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/docs/examples.html

  3. By David on Sep 15, 2011 | Reply

    Thanks Danne, I actually have it bookmarked already but I decided against adding another dependency at this point.

Post a Comment