Google Map API
Google Map API
Introduction
The fundamental element in any Google Maps V3 API application is the "map" itself. This
document discusses usage of the fundamental google.maps.Map object and the basics of map
operations. (If you've followed the Version 2 tutorial, much will look the same. However, there
are some differences, so please read this document.)
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
Even in this simple example, there are a few things to note:
1. We declare the application as HTML5 using the <DOCTYPE html>declaration.
2. We include the Maps API JavaScript using a script tag.
3. We create a div element named "map_canvas" to hold the Map.
4. We create a JavaScript object literal to hold a number of map properties.
5. We write a JavaScript function to create a "map" object.
6. We initialize the map object from the body tag's onload event.
These steps are explained below.
Declaring Your Application as HTML5
We recommend that you declare a true DOCTYPE within your web application. Within the
examples here, we've declared our applications as HTML5 using the simple HTML5 DOCTYPE as
shown below:
<!DOCTYPE html>
Most current browsers will render content that is declared with this DOCTYPE in "standards mode"
which means that your application should be more cross-browser compliant. The DOCTYPE is also
designed to degrade gracefully; browsers that don't understand it will ignore it, and use "quirks
mode" to display their content.
Note that some CSS that works within quirks mode is not valid in standards mode. In specific, all
percentage-based sizes must inherit from parent block elements, and if any of those ancestors fail
to specify a size, they are assumed to be sized at 0 x 0 pixels. For that reason, we include the
following <style> declaration:
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
This CSS declaration indicates that the map container <div> (named map_canvas) should take
up 100% of the height of the HTML body. Note that we must specifically declare those
percentages for <body> and <html> as well.
Map Options
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
To initialize a Map, we first create a Map options object to contain map initialization variables.
This object is not constructed; instead it is created as an object literal. Because we want to center
the map on a specific point, we also create a latlng value to hold this location and pass this into
the map's options. For more information on specifiying locations see Latitudes and Longitudes
below.
We also set the initial zoom level and mapTypeId to google.maps.MapTypeId.ROADMAP. The
following types are supported:
• ROADMAP displays the normal, default 2D tiles of Google Maps.
• SATELLITE displays photographic tiles.
• HYBRID displays a mix of photographic tiles and a tile layer for prominent features (roads,
city names).
• TERRAIN displays physical relief tiles for displaying elevation and water features
(mountains, rivers, etc.).
Unlike in the Google Maps V2 API, there is no default map type. You must specifically set an
initial map type to see appropriate tiles.
For more information about Map Types, see the Map Types section. For most cases, however,
using the basic types above is all you need to know.
google.maps.Map - the Elementary Object
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
The JavaScript class that represents a map is the Map class. Objects of this class define a single
map on a page. (You may create more than one instance of this class - each object will define a
separate map on the page.) We create a new instance of this class using the JavaScript new
operator.
When you create a new map instance, you specify a <div> HTML element in the page as a
container for the map. HTML nodes are children of the JavaScript document object, and we
obtain a reference to this element via the document.getElementById() method.
This code defines a variable (named map) and assigns that variable to a new Map object, also
passing in options defined within the myOptions object literal. These options will be used to
initialize the map's properties. The function Map() is known as a constructor and its definition is
shown below:
Constructor Description
google.maps.Map(opts? Creates a new map using the passed optional parameters in
) the opts parameter.
Zoom Levels
Offering a map of the entire Earth as a single image would either require an immense map, or a
small map with very low resolution. As a result, map images within Google Maps and the Maps
API are broken up into map tiles and zoom levels. At low zoom levels, individual map tiles
covers a wide area; at higher zoom levels, the tiles are of higher resolution and cover a smaller
area.
You specify the resolution at which to display a map by setting the Map's zoom property, where
zoom 0 corresponds to a map of the Earth fully zoomed out, and higher zoom levels zoom in at a
higher resolution
Map Events
You register for event notifications using the addListener() event handler. That method takes
an object, an event to listen for, and a function to call when the specified event occurs.
The following code mixes user events with state change events. We attach an event handler to a
marker that zooms the map when clicked. We also add an event handler to the map for changes
to the 'zoom' property and move the map to Darwin, Northern Territory, Australia on receipt of
the zoom_changed event:
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
function moveToDarwin() {
var darwin = new google.maps.LatLng(-12.461334, 130.841904);
map.setCenter(darwin);
}
Note: If you are trying to detect a change in the viewport, be sure to use the specific
bounds_changed event rather than constituent zoom_changed and center_changed events.
Because the Maps API fires these latter events independently, getBounds() may not report
useful results until after the viewport has authoritatively changed. If you wish to getBounds()
after such an event, be sure to listen to the bounds_changed event instead.
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
map.setCenter(location);
}
var zoomLevel;
var infowindow = new google.maps.InfoWindow(
{ content: 'Zoom Level Test',
size: new google.maps.Size(50,50),
position: myLatlng
});
infowindow.open(map);
// Map initialization
}
</script>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
Although this event is attached to the <body> element here, this event is really a window event
indicating that the DOM hierarchy below the window element has been fully built out and
rendered.
Although easy to understand, having an onload event within a <body> tag mixes content with
behavior. Generally, it is good practice to separate your content code (HTML) from your
behavioral code (Javascript) and provide your presentation code (CSS) separately as well. You
can do so by replacing the inline onload event handler with a DOM listener within your Maps
API Javascript code like so:
<script>
function initialize() {
// Map initialization
Controls Overview
The maps on Google Maps contain UI elements for allowing user interaction through the map.
These elements are known as controls and you can include variations of these controls in your
Google Maps API application. Alternatively, you can do nothing and let the Google Maps API
handle all control behavior.
The Maps API comes with a handful of built-in controls you can use in your maps:
• The Navigation control displays a large pan/zoom control as used on Google Maps. This
control appears by default in the top left corner of the map.
• The Scale control displays a map scale element. This control is not enabled by default.
• The MapType control lets the user toggle between map types (such as ROADMAP and
SATELLITE). This control appears by default in the top right corner of the map.
You don't access or modify these map controls directly. Instead, you modify the map's
MapOptions fields which affect the visibility and presentation of controls. You can adjust control
presentation upon instantiating your map (with appropriate MapOptions) or modify a map
dynamically by calling setOptions() to change the map's options.
Not all of these controls are enabled by default. To learn about default UI behavior (and how to
modify such behavior), see The Default UI below.
The Default UI
Rather than specifying and setting up individual controls, you may simply wish to specify that
your map exhibit the look and feel of the Google Maps interface, (including any new features or
controls that get added in the future). To get this behavior, you need do nothing. Your map will
show up with default controls.
The Default Control Set
The Maps API provides the following default controls:
Control Large Screens Small Screens iPhone Android
Large Pan/Zoom for Small Mini-Zoom for
Navigation sizes larger than sizes smaller than Not present "Android" control
400x350px 400x350px
Horizontal Bar for Dropdown for screens Same as Same as
MapType screens larger than smaller than 320px Large/Small Large/Small
320px wide wide Screens Screens
Scale Not present Not present Not present Not present
Additionally, keyboard handling is on by default on all devices.
Disabling the Default UI
You may instead wish to turn off the API's default UI settings. To do so, set the Map's
disableDefaultUI property (within the Map options object) to true. This property disables
any automatic UI behavior from the Google Maps API.
The following code disables the default UI entirely:
function initialize() {
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(-33, 151),
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
Control Options
Several controls are configurable, allowing you to alter their behavior or change their
appearance. The Navigation control, for example, may display as either a large control with a
full zoom control and panning controls as shown on Google Maps, or as a smaller, mini-zoom
control for smaller devices.
These controls are modified by altering appropriate control options fields within the MapOptions
object upon creation of the map. For example, options for altering the Navigation control are
indicated in the navigationControlOptions field.
The Navigation control may appear in one of the following style options:
• google.maps.NavigationControlStyle.SMALL displays a mini-zoom control,
consisting of only + and - buttons. This style is appropriate for mobile devices.
• google.maps.NavigationControlStyle.ZOOM_PAN displays the standard zoom slider
control with a panning control, as on Google Maps.
• google.maps.NavigationControlStyle.ANDROID displays the small zoom control as
used on the native Maps application on Android devices.
• google.maps.NavigationControlStyle.DEFAULT picks an appropriate navigation
control based on the map's size and the device on which the map is running.
The MapType control may appear in one of the following style options:
• google.maps.MapTypeControlStyle.HORIZONTAL_BAR displays the array of controls as
buttons in a horizontal bar as is shown on Google Maps.
• google.maps.MapTypeControlStyle.DROPDOWN_MENU displays a single button control
allowing you to select the map type via a dropdown menu.
• google.maps.MapTypeControlStyle.DEFAULT displays the "default" behavior, which
depends on screen size and may change in future versions of the API
Note that if you do modify any control options, you should explicitly enable the control as well
by setting the appropriate MapOptions value to true. For example, to set a Navigation control
to exhibit the SMALL style, use the following code within the MapOptions object:
...
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
...
The following example sets a drop-down MapType control and specifies that the Navigation
control use a small mini-zoom layout:
function initialize() {
var myOptions = {
zoom: 4,
center: new google.maps.LatLng(-33, 151),
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
Controls are typically configured upon creation of the map. However, you may alter the
presentation of controls dynamically by calling the Map's setOptions() method, passing it new
control options.
Modifying Controls
You specify a control's presentation when you create your map through fields within the map's
MapOptions object. These fields are denoted below:
• mapTypeControl enables/disables the Map Type control that lets the user toggle between
map types (such as Map and Satellite). By default, this control is visible and appears in
the top right corner of the map. The mapTypeControlOptions field additionally specifies
the MapTypeControlOptions to use for this control.
• navigationControl enables/disables the Navigation control that provides a pan/zoom
control. By default, this control is visible and appears in the top left corner of the map.
The navigationControlOptions field additionally specifies the
NavigationControlOptions to use for this control.
• scaleControl enables/disables the Scale control that provides a simple map scale. By
default, this control is not visible. When enabled, it appears in the bottom left corner of
the map. The scaleControlOptions additionally specifies the ScaleControlOptions
to use for this control.
Note that you may specify options for controls you initially disable.
Control Positioning
Each of these control options contains a position property (of type ControlPosition) which
indicates where on the map to place the control. Positioning of these controls is not absolute;
instead, the API will layout the controls intelligently by "flowing" them around existing map
elements, or other controls, within given constraints (such as the map size). Note: no guarantees
can be made that controls may not overlap given complicated layouts, though the API will
attempt to arrange them intelligently.
The following control positions are supported:
• TOP_CENTER indicates that the control should be placed along the top center of the map.
• TOP_LEFT indicates that the control should be placed along the top left of the map, with
any sub-elements of the control "flowing" towards the top center.
• TOP_RIGHT indicates that the control should be placed along the top right of the map, with
any sub-elements of the control "flowing" towards the top center.
• LEFT_TOP indicates that the control should be placed along the top left of the map, but
below any TOP_LEFT elements.
• RIGHT_TOP indicates that the control should be placed along the top right of the map, but
below any TOP_RIGHT elements.
• LEFT_CENTER indicates that the control should be placed along the left side of the map,
centered between the TOP_LEFT and BOTTOM_LEFT positions.
• RIGHT_CENTER indicates that the control should be placed along the right side of the map,
centered between the TOP_RIGHT and BOTTOM_RIGHT positions.
• LEFT_BOTTOM indicates that the control should be placed along the bottom left of the map,
but above any BOTTOM_LEFT elements.
• RIGHT_BOTTOM indicates that the control should be placed along the bottom right of the
map, but above any BOTTOM_RIGHT elements.
• BOTTOM_CENTER indicates that the control should be placed along the bottom center of the
map.
• BOTTOM_LEFT indicates that the control should be placed along the bottom left of the map,
with any sub-elements of the control "flowing" towards the bottom center.
• BOTTOM_RIGHT indicates that the control should be placed along the bottom right of the
map, with any sub-elements of the control "flowing" towards the bottom center.
Note that these positions may coincide with positions of UI elements whose placements you may
not modify (such as copyrights and the Google logo). In those cases, the controls will "flow"
according to the logic noted for each position and appear as close as possible to their indicated
position.
The following example shows a simple map with all controls enabled, in different positions.
function initialize() {
var myOptions = {
zoom: 12,
center: new google.maps.LatLng(-28.643387, 153.612224),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.BOTTOM
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN,
position: google.maps.ControlPosition.TOP_RIGHT
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
}
}
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
Custom Controls
As well as modifying the style and position of existing API controls, you can create your own
controls to handle interaction with the user. Controls are stationary widgets which float on top of
a map at absolute positions, as opposed to overlays, which move with the underlying map. More
fundamentally, a control is simply a <div> element which has an absolute position on the map,
displays some UI to the user, and handles interaction with either the user or the map, usually
through an event handler.
To create your own custom control, few "rules" are necessary. However, the following
guidelines can act as best practices:
• Define appropriate CSS for the control element(s) todisplay.
• Handle interaction with the user or the map through event handlers for either map
property changes or user events (e.g. 'click' events).
• Create a <div> element to hold the control and add this element to the Map's controls
property.
Each of these concerns is discussed below.
Drawing Custom Controls
How you draw your control is up to you. Generally, we recommend that you place all of your
control presentation within a single <div> element so that you can manipulate your control as
one unit. We will use this design pattern in the samples shown below.
Designing attractive controls requires some knowledge of CSS and DOM structure. The
following code shows how a simple control is created from a containing <div>, a <div> to hold
the button outline, and another <div> to hold the button interior.
// Create a div to hold the control.
var controlDiv = document.createElement('DIV');
/**
* The HomeControl adds a control to the map that simply
* returns the user to Chicago. This constructor takes
* the control DIV as an argument.
*/
// Setup the click event listeners: simply set the map to Chicago
google.maps.event.addDomListener(controlUI, 'click', function() {
map.setCenter(chicago)
});
}
function initialize() {
var mapDiv = document.getElementById('map_canvas');
var myOptions = {
zoom: 12,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapDiv, myOptions);
// Create the DIV to hold the control and call the HomeControl() constructor
// passing in this DIV.
var homeControlDiv = document.createElement('DIV');
var homeControl = new HomeControl(homeControlDiv, map);
homeControlDiv.index = 1;
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);
}
/**
* The HomeControl adds a control to the map that
* returns the user to the control's defined home.
*/
HomeControl.prototype.setHome = function(home) {
this.home_ = home;
}
// Get the control DIV. We'll attach our control UI to this DIV.
var controlDiv = div;
// We set up a variable for the 'this' keyword since we're adding event
// listeners later and 'this' will be out of scope.
var control = this;
function initialize() {
var mapDiv = document.getElementById('map_canvas');
var myOptions = {
zoom: 12,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapDiv, myOptions);
// Create the DIV to hold the control and call the HomeControl()
// constructor passing in this DIV.
var homeControlDiv = document.createElement('DIV');
var homeControl = new HomeControl(map, homeControlDiv, chicago);
homeControlDiv.index = 1;
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);
}
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 myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
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);
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);
}
}
}
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.
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);
function initialize() {
var mapOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: stockholm
};
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)
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);
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]
];
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
};
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 myOptions = {
zoom: 7,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
}
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
/**
* Handles click events on a map, and adds a new point to the Polyline.
* @param {MouseEvent} mouseEvent
*/
function addLatLng(event) {
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 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)
];
bermudaTriangle.setMap(map);
}
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.
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;
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.setMap(map);
// Add a listener for the click event
google.maps.event.addListener(bermudaTriangle, 'click', showArrays);
function showArrays(event) {
// Since this Polygon only has one path, we can call getPath()
// to return the MVCArray of LatLngs
var vertices = this.getPath();
infowindow.open(map);
}
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 myOptions = {
zoom: 13,
center: newark,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
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 myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
An example with the info window maxWidth set to 200 pixels appears below:
Layers Overview
Layers are objects on the map that consist of one or more separate items, but are manipulated as
a single unit. Layers generally reflect collections of objects that you add on top of the map to
designate a common association. The Maps API manages the presentation of objects within
layers by rendering their constituent items into one object (typically a tile overlay) and
displaying them as the map's viewport changes. Layers may also alter the presentation layer of
the map itself, slightly altering the base tiles in a fashion consistent with the layer. Note that most
layers, by design, may not be accessed via their individual objects, but may only be manipulated
as a unit.
To add a layer to a map, you only need to call setMap(), passing it the map object on which to
display the layer. Similarly, to hide a layer, call setMap(), passing null.
The Maps API has several types of layers:
• KmlLayer objects render KML and GeoRSS elements into a Maps API V3 tile overlay.
• FusionTablesLayer objects render data contained in Google Fusion Tables.
• The TrafficLayer object renders a layer depicting traffic conditions and overlays
representing traffic.
• The BicyclingLayer object renders a layer of bike paths and/or bicycle-specific
overlays into a common layer. This layer is returned by default within the
DirectionsRenderer when requesting directions of travel mode BICYCLING.
These layers are described below.
function showInDiv(text) {
var sidediv = document.getElementById('contentWindow');
sidediv.innerHTML = text;
}
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
};
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() {
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;
}
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>