Google Maps Tutorials

Customizing Google Maps: Adding a Custom Legend

Overview

This lesson teaches you to:

  • Add custom controls to the map.
  • Create a legend.

Description

Icons can indicate what a particular map marker represents, but often they are insufficient. Map legends have been used for many years to explicitly describe symbols on the map.

To place the legend on the map, we'll use the positioning feature of custom controls. Custom controls are simply HTML div elements with an absolute position on the map - they don't move as the map moves.

Try it out

Creating the container

To add a custom control, we'll first create an HTML DIV to hold the content. Once created, it's moved to the right-bottom of the map. Other control positions are available.

<div id="legend">
  My first legend!
</div>

map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(
  document.getElementById('legend'));

The control can then be styled, using CSS:

<style>
  #legend {
    background: white;
    padding: 10px;
  }
</style>

Adding the content

Finally, we can use the existing marker styles definition to populate the legend:

var legend = document.getElementById('legend');
for (var style in styles) {
  var name = style.name;
  var icon = style.icon;
  var div = document.createElement('div');
  div.innerHTML = '<img src="' + icon + '"> ' + name;
  legend.appendChild(div);
}

See the final code here. You can view the source to see the completed code.

Next chapter: Conclusion

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.