Google Maps JavaScript API v3
Feedback on this document

Overlays

  1. Overlays Overview
    1. Adding Overlays
    2. Removing Overlays
  2. Symbols
    1. Predefined Paths
  3. Markers
    1. Marker Animations
    2. Customizing the Marker Image
      1. Simple Icons
      2. Complex Icons
      3. Vector Icons
  4. Polylines
    1. Polyline Options
    2. Polyline Arrays
    3. Symbols on Polylines
  5. Polygons
    1. Polygon Options
    2. Polygon Auto-Completion
    3. Polygon Arrays
  6. Circles and Rectangles
    1. Circles
    2. Rectangles
  7. User-Editable Shapes
    1. Editing Events
  8. Drawing Library
    1. DrawingManager Options
    2. Updating the Drawing Tools Control
    3. Drawing Events
  9. Info Windows
  10. Ground Overlays
  11. Custom Overlays
    1. Subclassing an Overlay
    2. Initializing a Custom Overlay
    3. Drawing a Custom Overlay
    4. Removing a Custom Overlay
    5. Hiding and Showing a Custom Overlay

Overlays Overview

Overlays are objects on the map that are tied to latitude/longitude coordinates, so they move when you drag or zoom the map. Overlays reflect objects that you "add" to the map to designate points, lines, areas, or collections of objects.

The Maps API has several types of overlays:

  • Single locations on the map are displayed using markers. Markers may sometimes display custom icon images, in which case they are usually referred to as "icons." Markers and icons are objects of type Marker. (For more information, see Markers and Icons below.)
  • Lines on the map are displayed using polylines (representing an ordered sequence of locations). Lines are objects of type Polyline. (For more information, see Polylines.)
  • Areas of arbitrary shape on the map are displayed using polygons, which are similar to polylines. Like polylines, polygons are an ordered sequence of locations; unlike polylines, polygons define a region which they enclose. (For more information, see Polygons below.)
  • Map layers may be displayed using overlay map types. You can create your own set of tiles by creating custom map types which either replace base map tile sets, or display on top of existing base map tile sets as overlays. (For more information, see Custom Map Types.)
  • The info window is also a special kind of overlay for displaying content (usually text or images) within a popup balloon on top of a map at a given location. (For more information, see Info Windows.)
  • You may also implement your own custom overlays. These custom overlays implement the OverlayView interface. (For more information, see Custom Overlays.)

Adding Overlays

Overlays are often added to the map upon their construction; all overlays define an Options object for use in construction that allows you to designate the map on which they should appear. You may also add an overlay to the map directly by using the overlay's setMap() method, passing it the map on which to add the overlay.

var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
  zoom: 4,
  center: myLatlng,
  mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

var marker = new google.maps.Marker({
    position: myLatlng,
    title:"Hello World!"
});

// To add the marker to the map, call setMap();
marker.setMap(map);

Removing Overlays

To remove an overlay from a map, call the overlay's setMap() method, passing null. Note that calling this method does not delete the overlay; it simply removes the overlay from the map. If instead you wish to delete the overlay, you should remove it from the map, and then set the overlay itself to null.

If you wish to manage a set of overlays, you should create an array to hold the overlays. Using this array, you can then call setMap() on each overlay in the array when you need to remove them. (Note that unlike in V2, no clearOverlays() method exists; you are responsible for keeping track of your overlays and removing them from the map when not needed.) You can delete the overlays by removing them from the map and then setting the array's length to 0, which removes all references to the overlays.

The following example places markers on a map when clicked on the map, and places them within an array. The overlays can then be later cleared, shown, or deleted:

var map;
var markersArray = [];

function initialize() {
  var haightAshbury = new google.maps.LatLng(37.7699298, -122.4469157);
  var mapOptions = {
    zoom: 12,
    center: haightAshbury,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };
  map =  new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

  google.maps.event.addListener(map, 'click', function(event) {
    addMarker(event.latLng);
  });
}

function addMarker(location) {
  marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markersArray.push(marker);
}

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }
}

// Shows any overlays currently in the array
function showOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(map);
    }
  }
}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }
}

View example (overlay-remove.html)

Symbols

A Symbol is a vector based image that can be displayed on either a Marker or a Polyline object. Symbols are defined by a path — using SVG path notation — and options controlling how the symbol will be displayed. Several predefined symbols are available via the SymbolPath class. While path is the only required property, the Symbol class supports a variety of properties allowing you to customize visual aspects, such as the stroke and fill color and weight.

See the documentation for symbols on a polyline to learn more about how to display or animate symbols on a line. To learn more about using a symbol as a marker image, see the documentation for Vector Images below.

The Symbol class supports the following properties. Note that the default behavior of a Symbol varies slightly depending upon whether it appears on a marker or a polyline.

  • path (Required) the path defining the shape of the symbol. You can use one of the predefined paths in google.maps.SymbolPath or define a custom path using SVG path notation. Note: Vector paths on a polyline must fall within a 22x22px square. If your path includes points outside of this square, then you must adjust the scale property to a fractional value, such as 0.2, such that the result of the scaled points falls within that square.
  • anchor the position of the symbol relative to the marker or polyline. The coordinates of the symbol's path are translated left and up by the anchor's x and y coordinates respectively. By default, a symbol is anchored at (0, 0). The position is expressed in the same coordinate system as the symbol's path.
  • fillColor The symbol's fill color. All CSS3 colors are supported except for extended named colors. For symbol markers, this defaults to 'black'. For symbols on polylines, this defaults to the stroke color of the corresponding polyline.
  • fillOpacity the opacity of the symbol's fill, represented as a number between 0 and 1. Defaults to 0.
  • rotation the angle by which to rotate the symbol, expressed clockwise in degrees. By default, a symbol marker has a rotation of 0, and a symbol on a PolyLine is rotated by the angle of the edge on which it lies. Setting the rotation of a symbol on a polyline will fix the rotation of the symbol such that it will no longer follow the curve of the line.
  • scale the amount by which the symbol is scaled in size. For symbol markers, this defaults to 1; after scaling the symbol may be of any size. For symbols on a polyline, this defaults to the stroke weight of the polyline; after scaling, the symbol must lie inside a 22x22px square, centered at the symbol's anchor.
  • strokeColor the symbol's stroke color. All CSS3 colors are supported except for extended named colors. For symbol markers, this defaults to 'black'. For symbols on a polyline, this defaults to the stroke color of the polyline.
  • strokeOpacity the opacity of a symbol's stroke, represented as a number between 0 and 1. For symbol markers, this defaults to 1. For symbols on a polyline, this defaults to the stroke opacity of the polyline.
  • strokeWeight the symbol's stroke weight. Defaults to the scale of the symbol.

The below example creates a star shaped symbol, with a pale yellow fill and a thick yellow border.

var goldStar = {
  path: 'M 125,5 155,90 245,90 175,145 200,230 125,180 50,230 75,145 5,90 95,90 z',
  fillColor: "yellow",
  fillOpacity: 0.8,
  scale: 1,
  strokeColor: "gold",
  strokeWeight: 14
};

var marker = new google.maps.Marker({
  position: new google.maps.LatLng(-25.363, 131.044),
  icon: goldStar,
  map: map
});

Predefined Paths

The Google Maps JavaScript API provides some built-in symbols that can be displayed on markers or polylines. The default symbols include a circle, and two types of arrows. Because the orientation of a symbol on a polyline is fixed, both forward and backward facing arrows are available. Forward is considered to be in the direction of the terminus of the polyline. The included symbols are:

Name Description Example
google.maps.SymbolPath.CIRCLE A circle.
google.maps.SymbolPath.BACKWARD_CLOSED_ARROW A backward-pointing arrow that is closed on all sides.
google.maps.SymbolPath.FORWARD_CLOSED_ARROW A forward-pointing arrow that is closed on all sides.
google.maps.SymbolPath.BACKWARD_OPEN_ARROW A backward-pointing arrow that is open on one side.
google.maps.SymbolPath.FORWARD_OPEN_ARROW A forward-pointing arrow that is open on one side.

You can modify the stroke or fill of the predefined symbols using any of the default symbol options.

Markers

Markers identify locations on the map. By default, they use a standard icon, though you can set a custom icon within the marker's constructor or by calling setIcon() on the marker. The google.maps.Marker constructor takes a single Marker options object literal specifying the initial properties of the marker. The following fields are particularly important and commonly set when constructing your marker:

  • position (required) specifies a LatLng identifying the initial location of the marker.
  • map (optional) specifies the Map object on which to place the marker.

Note that within the Marker constructor, you should specify the map on which to add the marker. If you do not specify this argument, the marker is created but is not attached (or displayed) on the map. You may add the marker later by calling the marker's setMap() method. To remove a marker, call the setMap() method passing null as the argument.

Markers are designed to be interactive. By default, they receive 'click' events, for example, and are often used within event listeners to bring up info windows. Setting a marker's draggable property to true makes the marker user-editable on the map.

The following example adds a simple marker to a map at Uluru, in the center of Australia:

  var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
  var mapOptions = {
    zoom: 4,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title:"Hello World!"
  });

This Marker title will show up as a tooltip.

If you do not wish to pass any Marker options in the marker's constructor, instead pass an empty object {} in the last argument of the constructor.

View example (marker-simple.html)

Animations

You may also animate markers so that they exhibit dynamic movement in a variety of different circumstances. The way a marker is animated is specified within the marker's animation property, of type google.maps.Animation. The following Animation values are currently supported:

  • DROP indicates that the marker should drop from the top of the map to its final location when first placed on the map. Animation will cease once the marker comes to rest and animation will revert to null. This type of animation is usually specified during creation of the Marker.
  • BOUNCE indicates that the marker should "bounce" in place. A bouncing marker will continue bouncing until its animation property is explicitly set to null.

You may initiate an animation on an existing marker by calling setAnimation() on the Marker object.

The following example creates a marker in Stockholm, Sweden using a DROP animation. Clicking on the marker toggles the marker between a BOUNCE animation or no animation:

var stockholm = new google.maps.LatLng(59.32522, 18.07002);
var parliament = new google.maps.LatLng(59.327383, 18.06747);
var marker;
var map;

function initialize() {
  var mapOptions = {
    zoom: 13,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: stockholm
  };

  map = new google.maps.Map(document.getElementById("map_canvas"),
      mapOptions);

  marker = new google.maps.Marker({
    map:map,
    draggable:true,
    animation: google.maps.Animation.DROP,
    position: parliament
  });
  google.maps.event.addListener(marker, 'click', toggleBounce);
}

function toggleBounce() {

  if (marker.getAnimation() != null) {
    marker.setAnimation(null);
  } else {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}

View example (marker-animations.html)

Note: if you have many markers, you might not want to drop them all at once on the map. You can make use of setTimeout() to space your markers' animations apart using a pattern like that shown below:

function drop() {
  for (var i =0; i < markerArray.length; i++) {
    setTimeout(function() {
      addMarkerMethod();
    }, i * 200);
  }
}

View example (marker-animations-iteration.html)

Customizing the Marker Image

Markers may define an icon to show in place of the default icon. Defining an icon involves setting a number of properties that define the visual behavior of the marker.

Simple Icons

In the most basic case, an icon can simply indicate an image to use instead of the default Google Maps pushpin icon by setting the marker's icon property to the URL of an image. The Google Maps API will size the icon automatically in this case.

In the example below, we create an icon to signify the position of Bondi Beach in Sydney, Australia:

function initialize() {
  var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
  var mapOptions = {
    zoom: 4,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

  var image = 'beachflag.png';
  var myLatLng = new google.maps.LatLng(-33.890542, 151.274856);
  var beachMarker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      icon: image
  });
}

View example (icon-simple.html)

Complex Icons

More complex icons will want to specify complex shapes (which indicate regions that are clickable), add shadow images, and specify the "stack order" of how they should display relative to other overlays. Icons specified in this manner should set their icon and shadow properties to an object of type MarkerImage.

Shadow images should generally be created at a 45 degree angle (upward and to the right) from the main image, and the bottom left corner of the shadow image should align with the bottom-left corner of the icon image. Shadow images should be 24-bit PNG images with alpha transparency so that image boundaries appear correctly on the map.

MarkerImage objects not only define an image, but also define the size of the icon, the origin of the icon (if the image you want is part of a larger image in a sprite, for example), and the anchor where the icon's hotspot should be located (which is based on the origin).

The following example creates complex markers to signify beaches near Sydney, NSW, Australia. Note that the anchor is set to (0,32) to correspond to the base of the flagpole.

function initialize() {
  var mapOptions = {
    zoom: 10,
    center: new google.maps.LatLng(-33.9, 151.2),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"),
                                mapOptions);

  setMarkers(map, beaches);
}

/**
 * Data for the markers consisting of a name, a LatLng and a zIndex for
 * the order in which these markers should display on top of each
 * other.
 */
var beaches = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

function setMarkers(map, locations) {
  // Add markers to the map

  // Marker sizes are expressed as a Size of X,Y
  // where the origin of the image (0,0) is located
  // in the top left of the image.

  // Origins, anchor positions and coordinates of the marker
  // increase in the X direction to the right and in
  // the Y direction down.
  var image = new google.maps.MarkerImage('images/beachflag.png',
      // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(20, 32),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(0, 32));
  var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',
      // The shadow image is larger in the horizontal dimension
      // while the position and offset are the same as for the main image.
      new google.maps.Size(37, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 32));
      // Shapes define the clickable region of the icon.
      // The type defines an HTML <area> element 'poly' which
      // traces out a polygon as a series of X,Y points. The final
      // coordinate closes the poly by connecting to the first
      // coordinate.
  var shape = {
      coord: [1, 1, 1, 20, 18, 20, 18 , 1],
      type: 'poly'
  };
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        shadow: shadow,
        icon: image,
        shape: shape,
        title: beach[0],
        zIndex: beach[3]
    });
  }
}

View example (icon-complex.html)

Vector Icons

A marker supports the display of both raster images and vector paths, called Symbols. To display a vector path, pass a Symbol object literal with the desired path to the marker's icon property. You can use one of the predefined paths in google.maps.SymbolPath or define a custom path using SVG path notation.

For more information on vector images in the Google Maps JavaScript API, see the documentation for symbols.

The below example creates a icon using one of the predefined vector paths. For more detailed examples, see the documentation for Symbols.

marker = new google.maps.Marker({
  position: new google.maps.LatLng(-25.363882, 131.044922),
  icon: {
    path: google.maps.SymbolPath.CIRCLE,
    scale: 10
  },
  draggable: true,
  map: map
});

Polylines

The Polyline class defines a linear overlay of connected line segments on the map. A Polyline object consists of an array of LatLng locations, and creates a series of line segments that connect those locations in an ordered sequence.

Polyline Options

The Polyline constructor takes a set of Polyline options specifying the LatLng coordinates of the line and a set of styles to adjust the polyline's visual behavior.

Polylines are drawn as a series of straight segments on the map. You can specify custom colors, weights, and opacities for the stroke of the line within a Polyline options object used when constructing your line, or change those properties after construction. A polyline supports the following stroke styles:

  • strokeColor specifies a hexadecimal HTML color of the format "#FFFFFF". The Polyline class does not support named colors.
  • strokeOpacity specifies a numerical fractional value between 0.0 and 1.0 (default) of the opacity of the line's color.
  • strokeWeight specifies the weight of the line's stroke in pixels.

Additionally, a polyline's editable property defines whether this shape is editable by users on the map.

The following code snippet creates a 2-pixel-wide red polyline connecting the path of William Kingsford Smith's first trans-Pacific flight between Oakland, CA and Brisbane, Australia:


function initialize() {
  var myLatLng = new google.maps.LatLng(0, -180);
  var mapOptions = {
    zoom: 3,
    center: myLatLng,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var map = new google.maps.Map(document.getElementById("map_canvas"),
      mapOptions);
  var flightPlanCoordinates = [
    new google.maps.LatLng(37.772323, -122.214897),
    new google.maps.LatLng(21.291982, -157.821856),
    new google.maps.LatLng(-18.142599, 178.431),
    new google.maps.LatLng(-27.46758, 153.027892)
  ];
  var flightPath = new google.maps.Polyline({
    path: flightPlanCoordinates,
    strokeColor: "#FF0000",
    strokeOpacity: 1.0,
    strokeWeight: 2
  });

  flightPath.setMap(map);
}

View example (polyline-simple.html)

Polyline Arrays

A polyline specifies a series of coordinates as an array of LatLng objects. To retrieve these coordinates, call the Polyline's getPath(), which will return an array of type MVCArray. As such, you can manipulate and inspect the array using the following operations:

  • getAt() returns the LatLng at a given zero-based index value.
  • insertAt() inserts a passed LatLng at a given zero-based index value. Note that any existing coordinates at that index value are moved forward.
  • removeAt() removes a LatLng at a given zero-based index value.

Note: you cannot simply retrieve the ith element of an array by using the syntax mvcArray[i]; you must use mvcArray.getAt(i).

The following code creates an interactive map which constructs a polyline based on user clicks. Note that the polyline only appears once its path property contains two LatLng coordinates.


var poly;
var map;

function initialize() {
  var chicago = new google.maps.LatLng(41.879535, -87.624333);
  var mapOptions = {
    zoom: 7,
    center: chicago,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

  var polyOptions = {
    strokeColor: '#000000',
    strokeOpacity: 1.0,
    strokeWeight: 3
  }
  poly = new google.maps.Polyline(polyOptions);
  poly.setMap(map);

  // Add a listener for the click event
  google.maps.event.addListener(map, 'click', addLatLng);
}

/**
 * Handles click events on a map, and adds a new point to the Polyline.
 * @param {MouseEvent} mouseEvent
 */
function addLatLng(event) {

  var path = poly.getPath();

  // Because path is an MVCArray, we can simply append a new coordinate
  // and it will automatically appear
  path.push(event.latLng);

  // Add a new marker at the new plotted point on the polyline.
  var marker = new google.maps.Marker({
    position: event.latLng,
    title: '#' + path.getLength(),
    map: map
  });
}

View example (polyline-complex.html)

Symbols on Polylines

You can add vector based images to a polyline in the form of a Symbol. To display symbols on a polyline, set the icons[] property of the PolylineOptions object. The icons[] array takes one or more IconSequence object literals, defined as:

  • icon (Required) the icon to render on the line. See the documentation for Symbols for more information about how to customize a symbol.
  • offset the distance from the start of the line at which an icon is to be rendered. This distance may be expressed as a percentage of line's length (e.g. '50%') or in pixels (e.g. '50px'). Defaults to '100%'.
  • repeat the distance between consecutive icons on the line. This distance may be expressed as a percentage of the line's length (e.g. '50%') or in pixels (e.g. '50px'). To disable repeating of the icon, specify '0'. Defaults to '0'.

If your polyline is geodesic, then the distances specified for both offset and repeat are calculated in meters by default. Setting either offset or repeat to a pixel value will cause the distances to be calculated in pixels on the screen.

With a combination of symbols and the PolylineOptions class, you have a lot of control over the look and feel of polylines on your map. Below are some examples of customizations you can apply.

Arrows

Use the IconSequence.offset property to add arrows to the start, or end, of your polyline. In this example, setting the offset to 100% places the arrow at the terminus of the line.

JS
var lineCoordinates = [
  new google.maps.LatLng(22.291, 153.027),
  new google.maps.LatLng(18.291, 153.027)
];

var lineSymbol = {
  path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};

var line = new google.maps.Polyline({
  path: lineCoordinates,
  icons: [{
    icon: lineSymbol,
    offset: '100%'
  }],
  map: map
});
Demo

Dashed Lines

You can achieve a dashed line effect by by setting the opacity of your polyline to 0%, and drawing an opaque symbol at a regular interval.

JS
var lineCoordinates = [
  new google.maps.LatLng(22.291, 153.027),
  new google.maps.LatLng(18.291, 153.027)
];

var lineSymbol = {
  path: 'M 0,-1 0,1',
  strokeOpacity: 1,
  scale: 4
};

var line = new google.maps.Polyline({
  path: lineCoordinates,
  strokeOpacity: 0,
  icons: [{
    icon: lineSymbol,
    offset: '0',
    repeat: '20px'
  }],
  map: map
});
Demo

Custom Paths

Custom symbols allow you to add many different shapes to a polyline.

JS
var lineCoordinates = [
  new google.maps.LatLng(22.291, 153.027),
  new google.maps.LatLng(18.291, 153.027)
];

var symbolOne = {
  path: 'M -2,0 0,-2 2,0 0,2 z',
  strokeColor: '#F00',
  fillColor: '#F00',
  fillOpacity: 1
};

var symbolTwo = {
  path: 'M -2,-2 2,2 M 2,-2 -2,2',
  strokeColor: '#292',
  strokeWeight: 4
};

var symbolThree = {
  path: 'M -1,0 A 1,1 0 0 0 -3,0 1,1 0 0 0 -1,0M 1,0 A 1,1 0 0 0 3,0 1,1 0 0 0 1,0M -3,3 Q 0,5 3,3',
  strokeColor: '#00F',
  rotation: 0
};

var line = new google.maps.Polyline({
  path: lineCoordinates,
  icons: [{
    icon: symbolOne,
    offset: '0%'
    },{
      icon: symbolTwo,
      offset: '50%'
    },{
      icon: symbolThree,
      offset: '100%'
    }
  ],
  map: map
});
Demo

Animating Symbols

Symbols can be animated along a path by using a setTimeout() function to change the offset of a symbol at fixed intervals.

JS
var line;

function initialize() {
  var mapOptions = {
    center: new google.maps.LatLng(20.291, 153.027),
    zoom: 6,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  
  var map = new google.maps.Map(document.getElementById("map_canvas"),
      mapOptions);
      
  var lineCoordinates = [
    new google.maps.LatLng(22.291, 153.027),
    new google.maps.LatLng(18.291, 153.027)
  ];

  var lineSymbol = {
    path: google.maps.SymbolPath.CIRCLE,
    scale: 8,
    strokeColor: '#393'
  };

  line = new google.maps.Polyline({
    path: lineCoordinates,
    icons: [{
      icon: lineSymbol,
      offset: '100%'
    }],
    map: map
  });
}

function animateCircle() {
    var count = 0;
    offsetId = window.setInterval(function() {
      count = (count + 1) % 200;

      var icons = line.get('icons');
      icons[0].offset = (count / 2) + '%';
      line.set('icons', icons);
  }, 20);
}
Demo

Polygons

Polygon objects are similar to Polyline objects in that they consist of a series of coordinates in an ordered sequence. However, instead of being open-ended, polygons are designed to define regions within a closed loop. Similar to polylines, they allow you to define a stroke, which affects the outline of the polygon; unlike polylines, they also allow you to define a fill region inside the polygon.

Additionally, Polygons may potentially exhibit complex shapes, including discontinuities (multiple polygons defined as one polygon), "donuts" (where polygonal areas appear inside the polygon as "islands") and intersections of one or more polygons. For this reason, a single polygon may specify multiple paths.

Polygon Options

As with polylines, you can define custom colors, weights, and opacities for the edge of the polygon (the "stroke") and custom colors and opacities for the area within the enclosed region (the "fill"). Colors should be indicated in hexadecimal numeric HTML style.

Because a polygonal area may include several separate paths, the Polygon object's paths property specifies an "array of arrays," (each of type MVCArray) where each array defines a separate sequence of ordered LatLng coordinates.

However, for simple polygons consisting of only one path, you may construct a Polygon using a single array of LatLng coordinates as a convenience. The Google Maps API will convert this simple array into an "array of arrays" upon construction when storing it within the Polygon's paths property. As well, the API provides a simple getPath() methods for simple polygons consisting of one path.

Note: if you construct a polygon in this manner, you will still need to retrieve values from the polygon by manipulating the path as an MVCArray.

Additionally, a polygon's editable property defines whether this shape is editable by users on the map.

The following code snippet creates a polygon representing the Bermuda Triangle:


function initialize() {
  var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875);
  var mapOptions = {
    zoom: 5,
    center: myLatLng,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var bermudaTriangle;

  var map = new google.maps.Map(document.getElementById("map_canvas"),
      mapOptions);

  var triangleCoords = [
    new google.maps.LatLng(25.774252, -80.190262),
    new google.maps.LatLng(18.466465, -66.118292),
    new google.maps.LatLng(32.321384, -64.75737),
    new google.maps.LatLng(25.774252, -80.190262)
  ];

  // Construct the polygon
  // Note that we don't specify an array or arrays, but instead just
  // a simple array of LatLngs in the paths property
  bermudaTriangle = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: "#FF0000",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#FF0000",
    fillOpacity: 0.35
  });

  bermudaTriangle.setMap(map);
}

View example (polygon-simple.html)

Polygon Auto-Completion

The Polygon in the example above consists of four coordinates, but notice that the first and last coordinate are the same location, which defines the loop. In practice, however, since polygons define closed areas, you don't need to define this last coordinate. The Maps API will automatically "close" any polygons by drawing a stroke connecting the last coordinate back to the first coordinate for any given paths.

The following example is identical to the first example except that the last coordinate is omitted.

View example (polygon-autoclose.html)

Polygon Arrays

A polygon specifies its series of coordinates as an array of arrays, where each array is of type MVCArray. Each "leaf" array is an array of LatLng coordinates specifying a single path. To retrieve these coordinates, call the Polygon's getPaths() method. Since the array is an MVCArray you will need to manipulate and inspect it using the following operations:

  • getAt() returns the LatLng at a given zero-based index value.
  • insertAt() inserts a passed LatLng at a given zero-based index value. Note that any existing coordinates at that index value are moved forward.
  • removeAt() removes a LatLng at a given zero-based index value.

Note: you cannot simply retrieve the ith element of an array by using the syntax mvcArray[i]; you must use mvcArray.getAt(i).

The following code handles click events on the polygon by displaying information on the polygon's coordinates:


var map;
var infoWindow;

function initialize() {
  var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875);
  var mapOptions = {
    zoom: 5,
    center: myLatLng,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var bermudaTriangle;

  map = new google.maps.Map(document.getElementById("map_canvas"),
      mapOptions);

  var triangleCoords = [
    new google.maps.LatLng(25.774252, -80.190262),
    new google.maps.LatLng(18.466465, -66.118292),
    new google.maps.LatLng(32.321384, -64.75737)
  ];

  bermudaTriangle = new google.maps.Polygon({
    paths: triangleCoords,
    strokeColor: "#FF0000",
    strokeOpacity: 0.8,
    strokeWeight: 3,
    fillColor: "#FF0000",
    fillOpacity: 0.35
  });

  bermudaTriangle.setMap(map);

  // Add a listener for the click event
  google.maps.event.addListener(bermudaTriangle, 'click', showArrays);

  infowindow = new google.maps.InfoWindow();
}

function showArrays(event) {

  // Since this Polygon only has one path, we can call getPath()
  // to return the MVCArray of LatLngs
  var vertices = this.getPath();

  var contentString = "<b>Bermuda Triangle Polygon</b><br />";
  contentString += "Clicked Location: <br />" + event.latLng.lat() + "," + event.latLng.lng() + "<br />";

  // Iterate over the vertices.
  for (var i =0; i < vertices.length; i++) {
    var xy = vertices.getAt(i);
    contentString += "<br />" + "Coordinate: " + i + "<br />" + xy.lat() +"," + xy.lng();
  }

  // Replace our Info Window's content and position
  infowindow.setContent(contentString);
  infowindow.setPosition(event.latLng);

  infowindow.open(map);
}

View example (polygon-arrays.html)

Circles and Rectangles

In addition to a generic Polygon class, the Javascript Maps API also includes specific classes for Circle and Rectangle to simplify their construction.

Circles

A Circle is similar to a Polygon in that you can define custom colors, weights, and opacities for the edge of the circle (the "stroke") and custom colors and opacities for the area within the enclosed region (the "fill"). Colors should be indicated in hexadecimal numeric HTML style.

Unlike a Polygon, you do not define paths for a Circle; instead, a circle has two additional properties which define its shape:

  • center specifies the google.maps.LatLng of the center of this circle.
  • radius specifies the radius of the circle, in meters.

Additionally, a circle's editable property defines whether this shape is editable by users on the map.

The following code snippet creates circles representing populations in the United States:


// Create an object containing LatLng, population.
var citymap = {};
citymap['chicago'] = {
  center: new google.maps.LatLng(41.878113, -87.629798),
  population: 2842518
};
citymap['newyork'] = {
  center: new google.maps.LatLng(40.714352, -74.005973),
  population: 8143197
};
citymap['losangeles'] = {
  center: new google.maps.LatLng(34.052234, -118.243684),
  population: 3844829
}
var cityCircle;

function initialize() {
  var mapOptions = {
    zoom: 4,
    center: new google.maps.LatLng(37.09024, -95.712891),
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var map = new google.maps.Map(document.getElementById("map_canvas"),
      mapOptions);

  for (var city in citymap) {
    // Construct the circle for each value in citymap. We scale population by 20.
    var populationOptions = {
      strokeColor: "#FF0000",
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: "#FF0000",
      fillOpacity: 0.35,
      map: map,
      center: citymap[city].center,
      radius: citymap[city].population / 20
    };
    cityCircle = new google.maps.Circle(populationOptions);
  }
}

View example (circle-simple.html)

Rectangles

A Rectangle is similar to a Polygon in that you can define custom colors, weights, and opacities for the edge of the rectangle (the "stroke") and custom colors and opacities for the area within the enclosed region (the "fill"). Colors should be indicated in hexadecimal numeric HTML style.

Unlike a Polygon, you do not define paths for a Rectangle; instead, a rectangle has a bounds property which defines its shape:

  • bounds specifies the google.maps.LatLngBounds of this rectangle.

Additionally, a rectangle's editable property defines whether this shape is editable by users on the map.

The following example creates a rectangle based on the previous viewport on any 'zoom_changed' event:


function initialize() {

  var coachella = new google.maps.LatLng(33.6803003, -116.173894);
  var rectangle;

  var mapOptions = {
    zoom: 11,
    center: coachella,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };

  var map = new google.maps.Map(document.getElementById("map_canvas"),
      mapOptions);

  rectangle = new google.maps.Rectangle();

  google.maps.event.addListener(map, 'zoom_changed', function() {

    // Get the current bounds, which reflect the bounds before the zoom.
    var rectOptions = {
      strokeColor: "#FF0000",
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: "#FF0000",
      fillOpacity: 0.35,
      map: map,
      bounds: map.getBounds()
    };
    rectangle.setOptions(rectOptions);
  });
}

View example (rectangle-simple.html)

User-Editable Shapes

Any shape overlay (polylines, polygons, circles, and rectangles) can be set as user-editable, by setting editable to true in the shape's options.

To set markers as draggable, set draggable to true in the marker options.

var circleOptions = {
  center: new google.maps.LatLng(-34.397, 150.644),
  radius: 25000,
  map: map,
  editable: true
};
var circle = new google.maps.Circle(circleOptions);

Making a shape overlay editable adds 'handles' to the shape, allowing users to reposition, reshape, and/or resize it directly on the map.

View example (user-editable-shapes.html)

User-made changes to the object do not persist between sessions. If you'd like to save polygon edits, you must capture and store the information yourself.

Editing Events

When a shape is edited, an event is fired upon completion of the edit. These are listed below.

Shape Events
Circle radius_changed
center_changed
Polygon insert_at
remove_at
set_at

The listener must be set on the polygon's path. If the polygon has multiple paths, a listener must be set on each path.

Polyline insert_at
remove_at
set_at

The listener must be set on the polyline's path.

Rectangle bounds_changed
google.maps.event.addListener(circle, 'radius_changed', function() {
  radius = circle.getRadius();
});

google.maps.event.addListener(outerPath, 'set_at', function() {
  print('Vertex moved on outer path.');
});

google.maps.event.addListener(innerPath, 'insert_at', function() {
  print('Vertex removed from inner path.');
});

Drawing Library

The concepts within this document refer to features only available within the google.maps.drawing library. This library is not loaded by default when you load the Maps Javascript API but must be explicitly specified through use of a libraries bootstrap parameter:

http://maps.googleapis.com/maps/api/js?sensor=false&libraries=drawing

See Libraries in the V3 Maps API for more information.

The DrawingManager class provides a graphical interface for users to draw polygons, rectangles, polylines, circles, and markers on the map. A DrawingManager object is created as follows:

var drawingManager = new google.maps.drawing.DrawingManager();
drawingManager.setMap(map);

DrawingManager Options

The DrawingManager constructor takes a set of options that define the set of controls to display, the position of the control, and the initial drawing state.

  • The drawingMode property of the DrawingManager defines the initial drawing state of the DrawingManager. It accepts a google.maps.drawing.OverlayType constant. Default is null, in which case the cursor is in a non-drawing mode when the DrawingManager is initialized.
  • The drawingControl property of the DrawingManager defines the visibility of the drawing tools selection interface on the map. It accepts a boolean value.
  • You can also define the position of the control, and the types of overlays that should be represented in the control, using the drawingControlOptions property of the DrawingManager.
    • position defines the position of the drawing control on the map, and accepts a google.maps.ControlPosition constant.
    • drawingModes is an array of google.maps.drawing.OverlayType constants, and defines the overlay types to include in the drawing control shape picker. The hand icon will always be present, allowing the user to interact with the map without drawing. The order of the tools in the control will match the order in which they occur in the array.
  • Each type of overlay can be assigned a set of default properties, that define the appearance of the overlay when first created. These are defined in that overlay's {overlay}Options property (where {overlay} represents the overlay type). For example, a circle's fill properties, stroke properties, zIndex, and clickability can be defined with the circleOptions property. If any size, location, or map values are passed, they are ignored. For full details of which properties can be set, refer to the API Reference documentation.

    Tip: to make a shape user-editable after it has been created, set its editable property to true.

var drawingManager = new google.maps.drawing.DrawingManager({
  drawingMode: google.maps.drawing.OverlayType.MARKER,
  drawingControl: true,
  drawingControlOptions: {
    position: google.maps.ControlPosition.TOP_CENTER,
    drawingModes: [
      google.maps.drawing.OverlayType.MARKER,
      google.maps.drawing.OverlayType.CIRCLE,
      google.maps.drawing.OverlayType.POLYGON,
      google.maps.drawing.OverlayType.POLYLINE,
      google.maps.drawing.OverlayType.RECTANGLE
    ]
  },
  markerOptions: {
    icon: new google.maps.MarkerImage('http://www.example.com/icon.png')
  },
  circleOptions: {
    fillColor: '#ffff00',
    fillOpacity: 1,
    strokeWeight: 5,
    clickable: false,
    zIndex: 1,
    editable: true
  }
});
drawingManager.setMap(map);

View example (drawing-tools.html)

Updating the Drawing Tools Control

Once the DrawingManager object has been created, you can update it by calling setOptions() and passing new values.

drawingManager.setOptions({
  drawingControlOptions: {
    position: google.maps.ControlPosition.BOTTOM_LEFT,
    drawingModes: [google.maps.drawing.OverlayType.MARKER]
  }
});

To hide or show the drawing tools control:

// To hide:
drawingManager.setOptions({
  drawingControl: false
});

// To show:
drawingManager.setOptions({
  drawingControl: true
});

To remove the drawing tools control from the map object:

drawingManager.setMap(null);

Hiding the drawing control causes the drawing tools control to not display, but all of the functionality of the DrawingManager class is still available. In this way, you can implement your own control, if desired. Removing the DrawingManager from the map object disables all drawing functionality; it must be reattached to the map with drawingManager.setMap(map), or a new DrawingManager object constructed, if drawing features are to be restored.

Drawing Events

When a shape overlay is created, two events are fired:

  • An {overlay}complete event (where {overlay} represents the overlay type, such as circlecomplete, polygoncomplete, etc). A reference to the overlay is passed as an argument.
  • An overlaycomplete event. An object literal, containing the OverlayType and a reference to the overlay, is passed as an argument.
google.maps.event.addListener(drawingManager, 'circlecomplete', function(circle) {
  var radius = circle.getRadius();
});

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
  if (event.type == google.maps.drawing.OverlayType.CIRCLE) {
    var radius = event.overlay.getRadius();
  }
});

Info Windows

InfoWindows displays content in a floating window above the map. The info window looks a little like a comic-book word balloon; it has a content area and a tapered stem, where the tip of the stem is at a specified location on the map. You can see the info window in action by clicking business markers on Google Maps.

The InfoWindow constructor takes an InfoWindow options object, which specifies a set of initial parameters for display of the info window. Upon creation, an info window is not added to the map. To make the info window visible, you need to call the open() method on the InfoWindow, passing it the Map on which to open, and optionally, the Marker with which to anchor it. (If no marker is provided, the info window will open at its position property.)

The InfoWindow options object is an object literal containing the following fields:

  • content contains either a string of text or DOM node to display within the info window when it is opened.
  • pixelOffset contains an offset from the tip of the info window to the location on which the info window is anchored. In practice, you should not need to modify this field.
  • position contains the LatLng at which this info window is anchored. Note that opening an info window on a marker will automatically update this value with a new position.
  • maxWidth specifies the maximum width in pixels of the info window. By default, an info window expands to fit its content, and auto-wraps text if the info window expands to fill the map. If you implement a maxWidth the info window will auto-wrap to enforce the pixel width. Once it reaches the maximum width, the info window may still expand vertically if screen real estate is available.

The InfoWindow's content may contain either a string of text, a snippet of HTML, or a DOM element itself. To set this content, either pass it within the InfoWindow options constructor or call setContent() on the InfoWindow explicitly. If you wish to explicitly size the content, you may use <div>s to do so, and enable scrolling if you wish. Note that if you do not enable scrolling and the content exceeds the space available in an info window, the content may "spill" out of the info window.

InfoWindows may be attached to either Marker objects (in which case their position is based on the marker's location) or on the map itself at a specified LatLng. If you only want one info window to display at a time (as is the behavior on Google Maps), you need only create one info window, which you can reassign to different locations or markers upon map events (such as user clicks). Unlike behavior in V2 of the Google Maps API, however, a map may now display multiple InfoWindow objects if you so choose.

To change the info window's location you may either change its position explicitly by calling setPosition() on the info window, or by attaching it to a new marker using the InfoWindow.open() method. Note that if you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindow options object.

The following code displays a marker within the center of Australia. Clicking on that marker shows the info window.

var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
  zoom: 4,
  center: myLatlng,
  mapTypeId: google.maps.MapTypeId.ROADMAP
}

var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

var contentString = '<div id="content">'+
    '<div id="siteNotice">'+
    '</div>'+
    '<h2 id="firstHeading" class="firstHeading">Uluru</h2>'+
    '<div id="bodyContent">'+
    '<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large ' +
    'sandstone rock formation in the southern part of the '+
    'Northern Territory, central Australia. It lies 335 km (208 mi) '+
    'south west of the nearest large town, Alice Springs; 450 km '+
    '(280 mi) by road. Kata Tjuta and Uluru are the two major '+
    'features of the Uluru - Kata Tjuta National Park. Uluru is '+
    'sacred to the Pitjantjatjara and Yankunytjatjara, the '+
    'Aboriginal people of the area. It has many springs, waterholes, '+
    'rock caves and ancient paintings. Uluru is listed as a World '+
    'Heritage Site.</p>'+
    '<p>Attribution: Uluru, <a href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
    'http://en.wikipedia.org/w/index.php?title=Uluru</a> (last visited June 22, 2009).</p>'+
    '</div>'+
    '</div>';

var infowindow = new google.maps.InfoWindow({
    content: contentString
});

var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title:"Uluru (Ayers Rock)"
});

google.maps.event.addListener(marker, 'click', function() {
  infowindow.open(map,marker);
});

View example (infowindow-simple.html)

An example with the info window maxWidth set to 200 pixels appears below:

View example (infowindow-simple-max.html)

Ground Overlays

Polygons are useful overlays to represent arbitrarily-sized areas, but they cannot display images. If you have an image that you wish to place on a map, you can use a GroundOverlay object. The constructor for a GroundOverlay specifies a URL of an image and the LatLngBounds of the image as parameters. The image will be rendered on the map, constrained to the given bounds, and conformed using the map's projection.

The following example places an antique map of Newark, NJ on the map as an overlay:

var newark = new google.maps.LatLng(40.740, -74.18);
var imageBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(40.716216,-74.213393),
    new google.maps.LatLng(40.765641,-74.139235));

var mapOptions = {
  zoom: 13,
  center: newark,
  mapTypeId: google.maps.MapTypeId.ROADMAP
}

var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

var oldmap = new google.maps.GroundOverlay(
    "http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg",
    imageBounds);
oldmap.setMap(map);

View example (groundoverlay-simple.html)

Custom Overlays

The Google Maps API V3 provides an OverlayView class for creating your own custom overlays. The OverlayView is a base class providing several methods you must implement when creating your overlays. The class also provides a few methods that make it possible to translate between screen coordinates and locations on the map.

To create a custom overlay:

  • Set the custom object's prototype to a new instance of google.maps.OverlayView(). This will effectively "subclass" the overlay class.
  • Create a constructor for your custom overlay, and set any initialization parameters to custom properties within that constructor.
  • Implement an onAdd() method within your prototype, and attach the overlay to the map. OverlayView.onAdd() will be called when the map is ready for the overlay to be attached..
  • Implement a draw() method within your prototype, and handle the visual display of your object. OverlayView.draw() will be called when the object is first displayed as well.
  • You should also implement an onRemove() method to clean up any elements you added within the overlay.

We'll step through this explanation below.

SubClassing an Overlay

We'll use OverlayView to create a simple image overlay (similar to the GGroundOverlay within the V2 API). We'll create a USGSOverlay object which contains a USGS image of the area in question and the bounds of the image.

var overlay;

function initialize() {
  var myLatLng = new google.maps.LatLng(62.323907, -150.109291);
  var mapOptions = {
    zoom: 11,
    center: myLatLng,
    mapTypeId: google.maps.MapTypeId.SATELLITE
  };

  var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

  var swBound = new google.maps.LatLng(62.281819, -150.287132);
  var neBound = new google.maps.LatLng(62.400471, -150.005608);
  var bounds = new google.maps.LatLngBounds(swBound, neBound);

  // Photograph courtesy of the U.S. Geological Survey
  var srcImage = 'images/talkeetna.png';
  overlay = new USGSOverlay(bounds, srcImage, map);
}

Next, we'll create a constructor for this class, and initialize the passed parameters as properties of the new object. We will also need to explicitly subclass the USGSOverlay from OverlayView. We do this by setting the new class' prototype to an instance of the parent class. (We set the prototype here to an instance, rather than the parent class itself, because we do not wish to modify the parent class.)

function USGSOverlay(bounds, image, map) {

  // Now initialize all properties.
  this.bounds_ = bounds;
  this.image_ = image;
  this.map_ = map;

  // We define a property to hold the image'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(map);
}

USGSOverlay.prototype = new google.maps.OverlayView();

We can't yet attach this overlay to the map in the overlay's constructor. In specific, we need to ensure that all of the map's panes (which specify in what order objects are displayed on a map) are available. Conveniently, the API provides a helper method indicating this has occurred. We'll handle that method in the next section.

Initializing an Overlay

When the overlay is first instantiated and ready to display, we'll need to attach it to the map via the browser's DOM. The API indicates that the overlay has been added to the map by invoking the overlay's onAdd() method. We'll handle this method by creating a <div> to hold our image, add an <img> element, attach it to the <div>, and then finally attach the overlay to one of the map's panes, which are nodes within the DOM tree.

The set of panes, of type MapPanes, specify the stacking order for different layers on the map. The following panes are possible, and enumerated in the order in which they are stacked from bottom to top:

  • MapPanes.mapPane
  • MapPanes.overlayLayer
  • MapPanes.overlayShadow
  • MapPanes.overlayImage
  • MapPanes.floatShadow
  • MapPanes.overlayMouseTarget
  • MapPanes.floatPane

Because our image is a "ground overlay," we'll use the overlayLayer map pane. Once we have that pane, we'll attach our object to it as a child.

USGSOverlay.prototype.onAdd = function() {

  // Note: an overlay's receipt of onAdd() indicates that
  // the map's panes are now available for attaching
  // the overlay to the map via the DOM.

  // Create the DIV and set some basic attributes.
  var div = document.createElement('div');
  div.style.border = "none";
  div.style.borderWidth = "0px";
  div.style.position = "absolute";

  // Create an IMG element and attach it to the DIV.
  var img = document.createElement("img");
  img.src = this.image_;
  img.style.width = "100%";
  img.style.height = "100%";
  div.appendChild(img);

  // 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 overlayImage pane.
  var panes = this.getPanes();
  panes.overlayLayer.appendChild(div);
}

Drawing an Overlay

Note that we haven't actually invoked any special visual display above. The API invokes a separate draw() method on the overlay whenever it needs to draw the overlay on the map (including when first added).

We'll therefore implement this draw() method, retrieve the overlay's MapCanvasProjection using getProjection()and calculate the exact coordinates at which to anchor the object's top right and bottom left points, from which we'll resize the <div>; in turn this will resize the image to match the bounds we specified in the overlay's constructor.

USGSOverlay.prototype.draw = function() {

  // Size and position the overlay. We use a southwest and northeast
  // position of the overlay to peg it to the correct position and size.
  // We need to retrieve the projection from this overlay to do this.
  var overlayProjection = this.getProjection();

  // Retrieve the southwest and northeast coordinates of this overlay
  // in latlngs and convert them to pixels coordinates.
  // We'll use these coordinates to resize the DIV.
  var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
  var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());

  // Resize the image's DIV to fit the indicated dimensions.
  var div = this.div_;
  div.style.left = sw.x + 'px';
  div.style.top = ne.y + 'px';
  div.style.width = (ne.x - sw.x) + 'px';
  div.style.height = (sw.y - ne.y) + 'px';
}

Removing an Overlay

We'll also add an onRemove() method to cleanly remove the overlay from the map. This method will be called automatically from the API if we ever set the overlay's map property to null.

USGSOverlay.prototype.onRemove = function() {
  this.div_.parentNode.removeChild(this.div_);
  this.div_ = null;
}

View example (overlay-simple.html)

Hiding and Showing an Overlay

If you wish to hide or show an overlay rather than simply create or remove the overlay, you can implement your own hide() and show() methods to adjust the overlay's visibility. Alternatively, you may detach the overlay from the map's DOM, though this operation is slightly more expensive. Note that if you then reattach the overlay to the map's DOM, it will re-invoke the overlay's onAdd() method.

The following example adds hide() and show() methods to the overlay's prototype which toggle the container <div>'s visibility. Additionally, we add a toogleDOM() method, which attaches or detaches the overlay to the map. Note that if we set the visibility to "hidden" and then detach the map from the DOM via toggleDOM(), if we later reattach the map, it will be visible again, since the containing <div> is recreated in the overlay's onAdd() method.

// Note that the visibility property must be a string enclosed in quotes
USGSOverlay.prototype.hide = function() {
  if (this.div_) {
    this.div_.style.visibility = "hidden";
  }
}

USGSOverlay.prototype.show = function() {
  if (this.div_) {
    this.div_.style.visibility = "visible";
  }
}

USGSOverlay.prototype.toggle = function() {
  if (this.div_) {
    if (this.div_.style.visibility == "hidden") {
      this.show();
    } else {
      this.hide();
    }
  }
}

USGSOverlay.prototype.toggleDOM = function() {
  if (this.getMap()) {
    this.setMap(null);
  } else {
    this.setMap(this.map_);
  }
}
// Now we add an input button to initiate the toggle method
// on the specific overlay
<div id ="toolbar" width="100%; height:20px;" style="text-align:center">
  <input type="button" value="Toggle Visibility" onclick="overlay.toggle();"></input>
  <input type="button" value="Toggle DOM Attachment" onclick="overlay.toggleDOM();"></input>
</div>
<div id="map_canvas" style="width: 100%; height: 95%;"></div>

View example (overlay-hideshow.html)

Authentication required

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

Signing you in...

Google Developers needs your permission to do that.