Marker and polygon tooltips in Google Maps v3

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>');

3 comments

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.