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>');
I use this code to work with more advanced “tooltips”.
//google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/docs/examples.html
Thanks Danne, I actually have it bookmarked already but I decided against adding another dependency at this point.
Fantastic. Reduced to the max! Thanks a lot! I’m already happy with Marker tooltip. 😉