Maps API V3 Overlays

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 callingsetIcon() 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 passingnull 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.

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 myOptions = {
    zoom
: 4,
    center
: myLatlng,
    mapTypeId
: google.maps.MapTypeId.ROADMAP,
 
}
 
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
   
 
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)

Icons

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 myOptions = {
    zoom
: 4,
    center
: myLatlng,
    mapTypeId
: google.maps.MapTypeId.ROADMAP
 
}
 
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

 
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 specifed 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 myOptions = {
    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"),
                                myOptions
);

  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)

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.

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 myOptions = {
    zoom
: 3,
    center
: myLatLng,
    mapTypeId
: google.maps.MapTypeId.TERRAIN
 
};

 
var map = new google.maps.Map(document.getElementById("map_canvas"),
      myOptions
);
 
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 pathCoordinates = [];
var poly;
var map;

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

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

 
// We create pathCoordinates as an MVCArray so we can
 
// manipulate it using the insertAt() method
  pathCoordinates
= new google.maps.MVCArray();

 
var polyOptions = {
    path
: pathCoordinates,
    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);
}

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
.insertAt(pathCoordinates.length, event.latLng);

 
var marker = new google.maps.Marker({
    position
: event.latLng,
    map
: map
 
});
  marker
.setTitle("#" + pathCoordinates.length);
}

View example (polyline-complex.html)

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.

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


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

 
var bermudaTriangle;

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

 
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 myOptions = {
    zoom
: 5,
    center
: myLatLng,
    mapTypeId
: google.maps.MapTypeId.TERRAIN
 
};

 
var bermudaTriangle;

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

 
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)

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 InfoWindowobjects 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 myOptions = {
  zoom
: 4,
  center
: myLatlng,
  mapTypeId
: google.maps.MapTypeId.ROADMAP
}

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

var contentString = '<div id="content">'+
   
'<div id="siteNotice">'+
   
'</div>'+
   
'<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
   
'<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)

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 myOptions = {
    zoom
: 11,
    center
: myLatLng,
    mapTypeId
: google.maps.MapTypeId.SATELLITE
 
};

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

 
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 theUSGSOverlay 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 = "0px solid none";
  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
.overlayImage.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'smap 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)