Creating a Tooltip for Google Maps JavaScript API V3

February 3, 2012 § 21 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.

About these ads

Tagged:

§ 21 Responses to Creating a Tooltip for Google Maps JavaScript API V3

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Creating a Tooltip for Google Maps JavaScript API V3 at Mohamed Elbou.

meta

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: