Custom tooltips for Google Maps in pure Javascript

Building a custom tooltip for polygons on a google map

Recently, I had to work on a solution that involved creating a custom tooltip when hovering over polygons on a google map. After a thorough review of stack overflow and other dev forums, I didn’t find a simple solution. For those of you who don’t care about my ramblings, here’s a direct link to the JSFiddle.

After thinking about this for a bit, I realized that the simplest way to make this happen would be using simple DOM manipulation (the principle that powers most web based UIs).

Here’s the basic principle:

  1. Inject an tooltip into the DOM when the polygon is hovered over
  2. Update the position of the tooltip based on the cursor position as the mouse moves over the polygon
  3. Remove the tooltip as the mouse moves out of the polygon

Now all I needed to do was intercept the mouse events as they occurred on the polygon object drawn on the google map. Let’s get started…

Create a simple google map with a polygon

That’s some basic HTML we’ll need to render our google map. Let’s define the function initialize() next.

Brief description:

  • Lines 7–11: create a simple google map, draw it on the div with id “map”
  • Lines 13–19: define some coordinates for a polygon
  • Lines 22–30: create the actual polygon object. Note that I’ve embedded some data inside this object. You can use another approach that suits your application.
  • Lines 32–44: Setup event handlers. Most important stuff for all this to work. In line with the basic approach outlined above. Each event callback, gives us an argument “e” which contains the current position of the mouse cursor. That’s why I’m passing that variable “e” into the respective functions.

Drawing, Updating and Removing the tooltip

In the previous snippet, we setup three functions to inject, update and remove the tooltip element from the DOM. Now let’s define these.

  • Line 2: create a global reference to the tooltip in the DOM
  • Lines 5–9: define an offset along X & Y. I want to position the tooltip slightly below and right of the current mouse position
  • Lines 14–35: Inject the tooltip into the DOM. I’ve purposely chosen to style the tooltip in this function. You can use a CSS class to do the same thing. Pay attention to the lines 28–30. This element has fixed position and we’ll utilize the position of the cursor to position it.
  • Lines 41–47: This is the function tied to the “mousemove” event on the google map polygon and is invoked whenever the user’s mouse cursor hovers over the polygon. For every call to this function, we recompute the position of the tooltip based on the cursor’s position.
  • Lines 53–59: Finally, when the user’s cursor leaves the polygon, we simply remove the tooltip element from the page body, thereby completing the illusion :-)

For the complete snippet, visit this JSFiddle.