Creating a Tooltip for Google Maps JavaScript API V3
February 3, 2012 § 23 Comments
In this tutorial, I’m going to guide you through the process of creating a customized Tooltip, using Google Maps JavaScript API V3. You can use a Tooltip to display a short message when the user hover over a marker in the map. To create a Tooltip class, I’m going create a custom layover.
Disclaimer: This Tutorial is based on the example provided in the Google Maps API docs on creating a custom layover, available here.
To see a working example, click here. You can get the source file from github here.
The final result will look like this on mouse over:
Load the API and create a map
This tutorial is for people who are familiar with Google Maps JavaScript API V3, and of course, object-oriented programming concepts in general.
The first thing we need to do is load the API, and create a map, let’s set the center to Chicago:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<!-- include the API -->
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
function createMap() {
var mapDiv = document.getElementById("map_canvas");
var map;
// Set center to point to chicago
var latlng =new google.maps.LatLng(41.881944, -87.627778);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapDiv, myOptions);
}
</script>
</head>
<body>
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
If everything is fine, when you open the page in your browser, you should see something like this:
Place a marker on the map
Now let’s add a marker for Chicago, IL and an infowindow that opens on click event, to do this add the following to the end of our function createMap() :
// Add a marker for Chicago, IL
var chMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(41.881944, -87.627778)
});
var chHtml ="<h3><a href='http://en.wikipedia.org/wiki/Chicago,_Illinois'"
+" target='_blank'>Chicago, Illinois</a></h3><div>"
+"<img src='http://upload.wikimedia.org/wikipedia/commons/thumb/0/06/20070909_"
+"Chicago_Half_Marathon.JPG/220px-20070909_Chicago_Half_Marathon.JPG'"
+" width='220' hieght='174' />"
+"</div><div>Chicago is the largest city in the U.S. state of Illinois.</div>";
// add an infowindow
var chInfoWindow = new google.maps.InfoWindow({
content: chHtml,
maxWidth:250
});
//open infowindow on click event on marker.
google.maps.event.addListener(chMarker, 'click', function() {
chInfoWindow.open(map, chMarker);
});
Create the tooltip
The Google Maps API V3 provides an OverlayView class for creating your own custom overlays, our class will take one argument options, which is an object literal containing the following fields:
- marker contains the marker that the tooltip will be associated with.
- content contains a string of text to display within the tooltip when it is opened.
- cssClass is a CSS class, used to style the tooltip.
We need to extend the google.maps.OverlayView() by setting the custom object’s prototype to a new instance of google.maps.OverlayView().
Add the following lines in a script tag, after including the API in your page:
// create a constructor
function Tooltip(options) {
// Now initialize all properties.
this.marker_ = options.marker;
this.content_ = options.content;
this.map_ = options.marker.get('map');
this.cssClass_ = options.cssClass||null;
// We define a property to hold the content's
// div. We'll actually create this div
// upon receipt of the add() method so we'll
// leave it null for now.
this.div_ = null;
//Explicitly call setMap on this overlay
this.setMap(this.map_);
var me = this;
// Show tooltip on mouseover event.
google.maps.event.addListener(me.marker_, 'mouseover', function() {
me.show();
});
// Hide tooltip on mouseout event.
google.maps.event.addListener(me.marker_, 'mouseout', function() {
me.hide();
});
}
// Now we extend google.maps.OverlayView()
Tooltip.prototype = new google.maps.OverlayView();
We must implement three functions: onAdd, draw and onRemove, add the following lines:
// onAdd is one of the functions that we must implement,
// it will be called when the map is ready for the overlay to be attached.
Tooltip.prototype.onAdd = function() {
// Create the DIV and set some basic attributes.
var div = document.createElement('DIV');
div.style.position = "absolute";
// Hide tooltip
div.style.visibility = "hidden";
if(this.cssClass_)
div.className += " "+this.cssClass_;
//Attach content to the DIV.
div.innerHTML = this.content_;
// Set the overlay's div_ property to this DIV
this.div_ = div;
// We add an overlay to a map via one of the map's panes.
// We'll add this overlay to the floatPane pane.
var panes = this.getPanes();
panes.floatPane.appendChild(this.div_);
}
// We here implement draw
Tooltip.prototype.draw = function() {
// Position the overlay. We use the position of the marker
// to peg it to the correct position, just northeast of the marker.
// We need to retrieve the projection from this overlay to do this.
var overlayProjection = this.getProjection();
// Retrieve the coordinates of the marker
// in latlngs and convert them to pixels coordinates.
// We'll use these coordinates to place the DIV.
var ne = overlayProjection.fromLatLngToDivPixel(this.marker_.getPosition());
// Position the DIV.
var div = this.div_;
div.style.left = ne.x + 'px';
div.style.top = ne.y + 'px';
}
// We here implement onRemove
Tooltip.prototype.onRemove = function() {
this.div_.parentNode.removeChild(this.div_);
}
// Note that the visibility property must be a string enclosed in quotes
Tooltip.prototype.hide = function() {
if (this.div_) {
this.div_.style.visibility = "hidden";
}
}
Tooltip.prototype.show = function() {
if (this.div_) {
this.div_.style.visibility = "visible";
}
}
that’s it, the tooltip class is ready to be used.
Using the class
To use the class, we create an object by passing an options object like I described above, add the following line to our function createMap(), just before the closing curly bracket:
//create an options object
var chTooltipHtml ="<h3>Chicago, Illinois</h3><div>Population:2.7m</div>Click for more..";
var tooltipOptions={ marker:chMarker, content:chTooltipHtml, cssClass:'tooltip' // name of a css class to apply to tooltip };
// create the tooltip
var tooltip = new Tooltip(tooltipOptions);
Finally, let’s give some basic styling to our tooltip, add the following to your CSS:
.tooltip{
border:thin 1px #eee;
background-color:#FFFBF0;
padding:5px;
width:200px;
}
That’s all, don’t forget to leave your comments and/or suggestions below.
Update: I renamed one of the parameters from class to cssClass, since the word class is a reserved word, thanks to Martin for noticing that.
Thanks for this tutorial. I had a problem with your example code. You can’t have a parameter with the name “class”, so you need to change this to “cssclass” or something else.
Thanks, Martin, you are right, using the word class as a variable name is not a good idea, I should have tested more(Only tested against Chrome and IE9), I will make sure I update the code.
Great Tutorial, I was looking to create a tooltip in V3, this works fine for me, can you make the tooltip moves as the mouse does? like what Google has in Map search?
Very cool, thank you very much. Just what I needed!
It’s difficult to read the code on this page without indenting. There must be some way to make WordPress indent the code.
Hi, there is a small issue in this example. Say you drag the map at the end of your screen and then hover your mouse over the marker, it does not show the marker properly. The marker tooltip gets cutoff /hidden.
thank you ! 🙂
I am facing a peculiar problem. Say i am hiding one marker on click of another marker , the problem is that on mouse over the clicked marker the tool tip for the hidden marker is also shown along with the tool tip of the clicked marker.
Thank you!
thank you, very Great Tutorial. now is simple. hi from italy 🙂
how about several thousand markers?
Yes, it would require many markers but they can all be found here…
https://support.google.com/fusiontables/answer/1182141?hl=en
You can download each state’s CSV file and just copy and past the markers for each county. 🙂
I mean it is stupid to create tooltip for each marker. It should be only one tooltip for all markers, no matter how many.
Yes, that is what I mean. Do you know to do this?
Yes, I know how to do it.
You can see here: http://holden.pro/avia/routes/
There is one tooltip and 5K markers on the map.
For this work I get $30 🙂
Can you help me add rollovers to this map? http://mattbyrnes.com/maptest/
I just need the rollover to display the county name.
No, I don’t how to work with Fusion Tables Layers. But I think you’re doing something wrong. Your map slow because you query data from server when user click on map. I think you should load all data you need when page load and then add listeners to polygons – click and mouseover/mouseout. (in drawMap). You have drawMap in your code but you don’t use it.
This is great work Mohamed. Could I apply these functions to polygons, so I could make a county map with rollovers?
Is there any reason that I only get one tooltip to show? Each marker shows a tooltip on mouseover, but it is always the tooltip of the last marker in the array in the exact same position every time.
Great tutorial!!
In the end I used a library that came with examples to mount tooltips on the “markers” of google maps, with some very cool effects.
But this tutorial helped me to understand. Thank you!
The library, in case anybody’s interested:
http://jqeasytooltip.j3dlab.com/
Very useful tutorial, thanks!
Hey Mohamed, just wanted to say thanks man!
Very useful. Exactly meets my requirement..