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.)

The "Hello, World" of Google Maps v3
The easiest way to start learning about the Google Maps API is to see a simple example. The following web page displays a map centered on Sydney, New South Wales, Australia:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> html { height: 100% } body { height: 100%; margin: 0px; padding: 0px } #map_canvas { height: 100% } </style> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=set_to_true_or_false"> </script> <script type="text/javascript"> function initialize() { var latlng = new google.maps.LatLng(-34.397, 150.644); var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); } </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.

Loading the Google Maps API
<html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <script type="text/javascript" src="http://maps.google.com/maps/api/js? sensor=set_to_true_or_false"> </script>

The http://maps.google.com/maps/api/js URL points to the location of a JavaScript file that loads all of the symbols and definitions you need for using v3 of the Google Maps API. Your page must contain a script tag pointing to this URL. The <meta> tag within this header specifies that this map should be displayed full-screen and should not be resizable by the user Note that we also need to set a sensor parameter to indicate whether this application uses a sensor to determine the user's location. We've left this example as a variable set_to_true_or_false to emphasize that you must set this value to either true or false explicitly.

Map DOM Elements
<div id="map_canvas" style="width: 100%; height: 100%"></div>

For the map to display on a web page, we must reserve a spot for it. Commonly, we do this by creating a named div element and obtaining a reference to this element in the browser's document object model (DOM). In the example above, we define a <div> named "map_canvas" and set its size using style attributes. Note that this size is set to "100%" which will expand to fit the size on mobile devices. You may need to adjust these values based on the browser's screensize and padding. Note that the map will always take its size from that of its containing element, so you must always set a size on that <div> explicitly.

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. displays photographic tiles.

SATELLITE HYBRID

displays a mix of photographic tiles and a tile layer for prominent features (roads, city names). displays physical relief tiles for displaying elevation and water features (mountains, rivers, etc.).
TERRAIN

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. )

Loading the Map
<body onload="initialize()">

While an HTML page renders, the document object model (DOM) is built out, and any external images and scripts are received and incorporated into the document object. To ensure that our map is placed on the page after the page has fully loaded, we only execute the function which constructs the Map object once the <body> element of the HTML page receives an onload event. Doing so avoids unpredictable behavior and gives us more control on how and when the map draws. The body tag's onload attribute is an example of an event handler.

Latitudes and Longitudes
We need a way to refer to locations on the map. The google.maps.LatLng object provides such a mechanism within the Google Maps API. You construct a LatLng object, passing its parameters in the order { latitude, longitude }:
var myLatlng = new google.maps.LatLng(myLatitude, myLongitude)

Note: the process of turning an address into a geographic point is known as geocoding. Geocoding is supported in this release of the Google Maps API LatLng objects have many uses within the Google Maps API. The google.maps.Marker object uses a LatLng in its constructor, for example, and places a marker overlay on the map at the given geographic location.

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

Google Maps Javascript API V3 Events
Note: The Google Maps Javascript API Version 3 documented within these pages is now the official Javascript API. Version 2 of this API has been officially deprecated as per our deprecation policy. We encourage you to migrate your code to this newly updated and enhanced version!

do not pass arguments within their event. but you generally wish to treat them differently in your code. though much has changed under the hood. Because different browsers implement different DOM event models. Map Events . UI Events Some objects within the Maps API are designed to respond to user events such as mouse or keyboard events. the API will fire a zoom_changed event on a map when the map's zoom level changes. A google. You can intercept these state changes by registering addListener() event handlers on the event namespace method as well.maps. MVC state change notifications reflect changes in Maps API objects and are named using a property_changed convention Each Maps API object exports a number of named events. For example. You will want to inspect the property that changed on an MVC state change by calling the appropriate getProperty method on that object. Programs interested in certain events will register JavaScript event listeners for those events and execute code when those events are received by registering addListener() event handlers on the google. MVC events. the API will fire an event that the property has changed. for example: • • • • • • 'click' 'dblclick' 'mouseup' 'mousedown' 'mouseover' 'mouseout' These events may look like standard DOM events. These events are separate and distinct from standard DOM events. User events and MVC state changes may look similar. the Maps API provides these mechanisms to listen for and respond to DOM events without needing to handle the various cross-browser peculiarities. Whenever an object's property changes. but they are actually part of the Maps API.Map Events Overview JavaScript within the browser is event driven. Developers of V2 of the Google Maps API will be familiar with this usage. The event model for the Google Maps API V3 is similar to that used in V2 of the API.Marker object can listen to the following user events. meaning that JavaScript responds to interactions by generating events. These events also typically pass arguments within the event noting some UI state (such as the mouse position). MVC State Changes MVC objects typically contain state. for example.event namespace.maps. and expects a program to listen to interesting events. There are two types of events: • • User events (such as "click" mouse events) are propagated from the DOM to the Google Maps API.

maps.event. getBounds() may not report useful results until after the viewport has authoritatively changed. and creates a marker when the user clicks on the map at the clicked location.MapTypeId. a UI 'click' event typically passes a MouseEvent containing a latLng property denoting the clicked location on the map. 130. } Note: If you are trying to detect a change in the viewport.044922). an event to listen for. 'click'.841904). function() { setTimeout(moveToDarwin. which can be accessed by the event listener. If you wish to getBounds() after such an event.LatLng(-25. mapTypeId: google. noting the UI state when the event occurred. google.Map(document. Australia on receipt of the zoom_changed event: var map.363882.event. For example. center: myLatlng. 'zoom_changed'. }).setZoom(8). } function moveToDarwin() { var darwin = new google. Note that this behavior is unique to UI events. title:"Hello World!" }). myOptions). Because the Maps API fires these latter events independently. and a function to call when the specified event occurs. .Marker({ position: myLatlng.maps. var myOptions = { zoom: 4.461334. The following example adds an event listener for the map. Accessing Arguments in UI Events UI events within the Google Maps API V3 typically pass an event argument. We also add an event handler to the map for changes to the 'zoom' property and move the map to Darwin. var marker = new google.getElementById("map_canvas"). google. We attach an event handler to a marker that zooms the map when clicked.maps.131. be sure to listen to the bounds_changed event instead. be sure to use the specific bounds_changed event rather than constituent zoom_changed and center_changed events. }). You can access the event's arguments within an event listener the same way you would access an object's properties.addListener(map.addListener(marker.setCenter(darwin). The following code mixes user events with state change events. MVC state changes do not pass arguments in their events. function initialize() { var myLatlng = new google.maps. map: map. function() { map.LatLng(-12.ROADMAP } map = new google. That method takes an object. Northern Territory.maps.You register for event notifications using the addListener() event handler. map.maps.maps. 3000).

myOptions).maps.244141).lat(). i++) { var location = new google. i < 5.LatLng(-25.latLng).ROADMAP } map = new google. for (var i = 0.MapTypeId.044922).getElementById("map_canvas").MapTypeId.LatLngBounds(southWest. which is not contained within the marker itself.363882. var myOptions = { zoom: 4.fitBounds(bounds). but it does support which allows inner functions to access outer variables. mapTypeId: google.131. // Add 5 markers to the map at random locations var southWest = new google.Map(document.LatLng(southWest. var lngSpan = northEast. mapTypeId: google.Marker({ position: location.maps.044922).LatLng(-25.044922).LatLng(-25.131. function initialize() { var myLatlng = new google.lat() + latSpan * Math. google.maps. var myOptions = { zoom: 4.maps.southWest. var bounds = new google.Map(document. } Using Closures in Event Listeners When executing an event listener.363882. The following example uses a function closure in the event listener to assign a secret message to a set of markers.event.southWest. var latSpan = northEast.maps. map: map }).lng(). center: myLatlng. myOptions). function(event) { placeMarker(event.maps. 'click'.northEast).maps. Closures are useful within event listeners to access variables not normally attached to the objects on which events occur.125.lng() .maps. function initialize() { var myLatlng = new google. } function placeMarker(location) { var marker = new google. it is often advantageous to have both private and persistent data attached to an object. JavaScript does not support "private" instance data. }). map. map. var map.getElementById("map_canvas").131. Clicking on each marker will review a portion of the secret message. var northEast = new google.ROADMAP } map = new google.maps.maps.var map.maps.lat() .363882.203405. center: myLatlng.maps. .addListener(map.setCenter(location).random().LatLng(-31.

InfoWindow( . var infowindow = new google."the".363882. function() { infowindow. } Getting and Setting Properties Within Event Handlers None of the MVC state change events in the Maps API event system pass arguments when the event is triggered.Size(50. Note: explicitly setting a property within an event handler which responds to a state change of that particular property may produce unpredictable and/or unwanted behavior. i).maps. attachSecretMessage(marker. This inspection will always retrieve the current state of the MVC object.50) }). google.InfoWindow( { content: message[number]. number) { var message = ["This".LatLng(-25.Map(document.maps.marker). center: myLatlng.maps."message"].random()).toString()). In the example below. var j = i + 1. mapTypeId: google. var map."is". 'click'.131."secret". var zoomLevel. var infowindow = new google. We also check whether the map is fully zoomed-out and zoom in to zoom level 17 if so. var myOptions = { zoom: 4.MapTypeId. we set up an event handler to respond to zoom events by bringing up an info window displaying that level. marker.maps. myOptions). var marker = new google.lng() + lngSpan * Math.setTitle(j. }). } } // The five markers show a secret message when clicked // but that message is not within the marker's instance data function attachSecretMessage(marker.southWest. (User events do pass arguments which can be inspected.maps.addListener(marker.) If you need to inspect a property on an MVC state change.open(map. which may not be the state when the event was first fired. size: new google. and if you always set a property within this event handler. Setting such a property will trigger a new event. map: map }). function initialize() { var myLatlng = new google.getElementById("map_canvas").maps.Marker({ position: location.event.044922).ROADMAP } map = new google. for example.maps. you should explicitly call the appropriate getProperty() method on that object. you may end up creating an infinite loop.maps.

eventName:string. which we've handled within the <body> tag.event. the Maps API provides the addDomListener() static method to listen to and bind to DOM events. Generally. If you've been reading the documentation this far. infowindow. } }).setContent("Zoom: " + zoomLevel).setZoom(10). infowindow. } Listening to DOM Events The Google Maps Javascript API event model creates and manages its own custom events.open(map).{ content: 'Zoom Level Test'.getZoom(). position: myLatlng }). This convenience method has a signature as shown below: addDomListener(instance:Object. 'zoom_changed'. as shown below: <script> function initialize() { // Map initialization } </script> <body onload="initialize()"> <div id="map_canvas"></div> </body> Although this event is attached to the <body> element here. if (zoomLevel == 0) { map. However. it is good practice to separate your content code (HTML) from your .maps. If you wish to capture and respond to these events. having an onload event within a <body> tag mixes content with behavior. including: • • Hierarchical members of the DOM such as window or document.body.myform Named elements such as document. google.onload event.50).maps. Although easy to understand.getElementById("foo") Note that addDomListener() simply passes the indicated event to the browser. the DOM (Document Object Model) within the browser also creates and dispatches its own events. however. We use this event to trigger the initial Javascript code once an HTML page is fully loaded. according to the particular browser event model in use. handler:Function) where instance may be any DOM element supported by the browser. this event is really a window event indicating that the DOM hierarchy below the window element has been fully built out and rendered. which handles it according to the browser's DOM event model.addListener(map.Size(50. size: new google. almost all modern browsers at least support DOM Level 2. function() { zoomLevel = map. you're probably already familiar with one DOM event: the window.

To learn about default UI behavior (and how to modify such behavior). The MapType control lets the user toggle between map types (such as ROADMAP and SATELLITE). To get this behavior. These elements are known as controls and you can include variations of these controls in your Google Maps API application. Not all of these controls are enabled by default. you modify the map's MapOptions fields which affect the visibility and presentation of controls. This control is not enabled by default. you may simply wish to specify that your map exhibit the look and feel of the Google Maps interface. 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. see The Default UI below. The Scale control displays a map scale element. 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 } google. 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. The Default UI Rather than specifying and setting up individual controls. (including any new features or controls that get added in the future).event. 'load'.addDomListener(window. Controls Overview The maps on Google Maps contain UI elements for allowing user interaction through the map.behavioral code (Javascript) and provide your presentation code (CSS) separately as well. </script> <body> <div id="map_canvas"></div> </body> Although the above code is Maps Javascript API code. the addDomListener() method binds to the window object of the browser and allows the API to communicate with objects outside of the API's normal domain. Instead. you can do nothing and let the Google Maps API handle all control behavior. You don't access or modify these map controls directly.maps. you need do nothing. Alternatively. The Default Control Set The Maps API provides the following default controls: . This control appears by default in the top right corner of the map. initialize). Your map will show up with default controls. This control appears by default in the top left corner of the map.

myOptions). mapTypeId: google.ROADMAP } var map = new google.Large Screens Large Pan/Zoom for Navigation sizes larger than 400x350px Horizontal Bar for MapType screens larger than 320px wide Scale Not present Control Small Screens Small Mini-Zoom for sizes smaller than 400x350px Dropdown for screens smaller than 320px wide Not present iPhone Not present Same as Large/Small Screens Not present Android "Android" control Same as Large/Small Screens Not present Additionally. . } Adding Controls to the Map You may wish to tailor your interface by removing. center: new google. adding.LatLng(-33.maps. keyboard handling is on by default on all devices. Some controls appear on the map by default while others will not appear unless you specifically request them.Map(document. Disabling the Default UI You may instead wish to turn off the API's default UI settings. If you wish to only add or modify existing behavior. so these modifications are additive to the default UI behavior. To do so.maps. scaleControl: boolean } Note that the Maps API V3 does not currently allow you to dynamically add or remove controls. The following example sets the map to hide the navigation control and display the scale control. Note that we do not explicitly disable the default UI. mapTypeControl: boolean. The following code disables the default UI entirely: function initialize() { var myOptions = { zoom: 4.getElementById("map_canvas"). These must be set upon creation of the map through a Map options object. This property disables any automatic UI behavior from the Google Maps API. or modifying UI behavior or controls and ensure that future updates don't alter this behavior. Adding or removing controls from the map is specified in the following Map options object's fields. function initialize() { var myOptions = { zoom: 4. which you set to true to make them visible or set to false to hide them: { navigationControl: boolean. 151).maps.MapTypeId. you need to ensure that the control is explicitly added to your application. set the Map's disableDefaultUI property (within the Map options object) to true. disableDefaultUI: true.

google.. For example.SMALL google. navigationControl: true.maps. to set a Navigation control to exhibit the SMALL style... consisting of only + and . These controls are modified by altering appropriate control options fields within the MapOptions object upon creation of the map.SMALL } . scaleControl: true.maps. or as a smaller. For example. This style is appropriate for mobile devices. The Navigation control may appear in one of the following style options: • • • • displays a mini-zoom control.maps.DEFAULT picks an appropriate navigation control based on the map's size and the device on which the map is running. mapTypeId: google. options for altering the Navigation control are indicated in the navigationControlOptions field.maps. google. for example. The following example sets a drop-down MapType control and specifies that the Navigation control use a small mini-zoom layout: . } Control Options Several controls are configurable.DEFAULT displays the "default" behavior. myOptions).maps. mini-zoom control for smaller devices.center: new google.ANDROID google.MapTypeControlStyle.ZOOM_PAN displays the standard zoom slider control with a panning control. navigationControl: false.Map(document. allowing you to alter their behavior or change their appearance. may display as either a large control with a full zoom control and panning controls as shown on Google Maps. google.NavigationControlStyle. 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.NavigationControlStyle.buttons. The Navigation control.ROADMAP } var map = new google.DROPDOWN_MENU google.MapTypeControlStyle. displays a single button control allowing you to select the map type via a dropdown menu.MapTypeId. 151).maps. use the following code within the MapOptions object: .maps.LatLng(-33..getElementById("map_canvas").maps.MapTypeControlStyle.maps.maps.NavigationControlStyle. displays the small zoom control as used on the native Maps application on Android devices.NavigationControlStyle. navigationControlOptions: { style: google.HORIZONTAL_BAR The MapType control may appear in one of the following style options: • • • displays the array of controls as buttons in a horizontal bar as is shown on Google Maps.maps. as on Google Maps. google.NavigationControlStyle.

navigationControl • enables/disables the Scale control that provides a simple map scale. myOptions). mapTypeControlOptions: { style: google. The following control positions are supported: • TOP_CENTER indicates that the control should be placed along the top center of the map. When enabled. The navigationControlOptions field additionally specifies the NavigationControlOptions to use for this control. These fields are denoted below: • enables/disables the Map Type control that lets the user toggle between map types (such as Map and Satellite). } Controls are typically configured upon creation of the map.MapTypeId.ROADMAP } var map = new google. Positioning of these controls is not absolute. this control is not visible.SMALL }.MapTypeControlStyle. The scaleControlOptions additionally specifies the ScaleControlOptions to use for this control. or other controls. instead. Control Positioning Each of these control options contains a position property (of type ControlPosition) which indicates where on the map to place the control. within given constraints (such as the map size). navigationControlOptions: { style: google.DROPDOWN_MENU }. it appears in the bottom left corner of the map.Map(document. this control is visible and appears in the top right corner of the map. By default. passing it new control options.maps. navigationControl: true.maps.maps.getElementById("map_canvas").LatLng(-33. The mapTypeControlOptions field additionally specifies the MapTypeControlOptions to use for this control. though the API will attempt to arrange them intelligently. Modifying Controls You specify a control's presentation when you create your map through fields within the map's MapOptions object. By default. However.maps. .NavigationControlStyle. mapTypeControl • enables/disables the Navigation control that provides a pan/zoom control. center: new google. 151). mapTypeControl: true.maps. mapTypeId: google. this control is visible and appears in the top left corner of the map. scaleControl Note that you may specify options for controls you initially disable. you may alter the presentation of controls dynamically by calling the Map's setOptions() method.function initialize() { var myOptions = { zoom: 4. the API will layout the controls intelligently by "flowing" them around existing map elements. By default. Note: no guarantees can be made that controls may not overlap given complicated layouts.

with any sub-elements of the control "flowing" towards the top center.maps. with any sub-elements of the control "flowing" towards the top center. navigationControlOptions: { style: google. position: google. scaleControl: true.maps. TOP_RIGHT LEFT_TOP indicates that the control should be placed along the top left of the map.maps. function initialize() { var myOptions = { zoom: 12. but above any BOTTOM_RIGHT elements.• • • • • • • • • • • indicates that the control should be placed along the top left of the map. center: new google. position: google. TOP_LEFT indicates that the control should be placed along the top right of the map.643387. mapTypeId: google.maps.ControlPosition. indicates that the control should be placed along the bottom left of the map. RIGHT_BOTTOM BOTTOM_CENTER indicates that the control should be placed along the bottom center of the map.maps. RIGHT_TOP indicates that the control below any TOP_RIGHT elements. centered between the TOP_LEFT and BOTTOM_LEFT positions.TOP_RIGHT }. scaleControlOptions: { .ZOOM_PAN. BOTTOM_LEFT indicates that the control should be placed along the bottom right of the map. centered between the TOP_RIGHT and BOTTOM_RIGHT positions. mapTypeControl: true. indicates that the control should be placed along the right side of the map. with any sub-elements of the control "flowing" towards the bottom center.MapTypeId. navigationControl: true.ControlPosition. but indicates that the control should be placed along the left side of the map.MapTypeControlStyle. The following example shows a simple map with all controls enabled.HORIZONTAL_BAR. 153. indicates that the control should be placed along the bottom right of the map. in different positions. but below any TOP_LEFT elements. RIGHT_CENTER LEFT_BOTTOM indicates that the control should be placed along the bottom left of the map.ROADMAP. mapTypeControlOptions: { style: google. In those cases. with any sub-elements of the control "flowing" towards the bottom center.LatLng(-28. BOTTOM_RIGHT Note that these positions may coincide with positions of UI elements whose placements you may not modify (such as copyrights and the Google logo).612224).NavigationControlStyle. LEFT_CENTER should be placed along the top right of the map.BOTTOM }. the controls will "flow" according to the logic noted for each position and appear as close as possible to their indicated position.maps. but above any BOTTOM_LEFT elements.

TOP_LEFT } } var map = new google. controlUI. myOptions). controlUI. However.style. displays some UI to the user.padding = '5px'. controlUI. controlUI.createElement('DIV'). // Create a div to hold the control. controlUI. controlDiv.title = 'Click to set the map to Home'. a <div> to hold the button outline. var controlDiv = document. We will use this design pattern in the samples shown below. as opposed to overlays.} position: google.style. you can create your own controls to handle interaction with the user. controlUI.maps. More fundamentally.createElement('DIV').Map(document.style.style. which move with the underlying map. 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.maps. Generally. and handles interaction with either the user or the map. The following code shows how a simple control is created from a containing <div>. Custom Controls As well as modifying the style and position of existing API controls.cursor = 'pointer'. '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.borderStyle = 'solid'. // Set CSS for the control border var controlUI = document.getElementById("map_canvas").backgroundColor = 'white'.style. a control is simply a <div> element which has an absolute position on the map. // Set CSS styles for the DIV containing the control // Setting padding to 5 px will offset the control // from the edge of the map controlDiv. and another <div> to hold the button interior.textAlign = 'center'.style. the following guidelines can act as best practices: • • • Define appropriate CSS for the control element(s) todisplay. Drawing Custom Controls How you draw your control is up to you. To create your own custom control. few "rules" are necessary. usually through an event handler.appendChild(controlUI). Handle interaction with the user or the map through event handlers for either map property changes or user events (e. .borderWidth = '2px'.g.ControlPosition. Controls are stationary widgets which float on top of a map at absolute positions. Designing attractive controls requires some knowledge of CSS and DOM structure.

// We don't really need to set an index value here. Handling Events from Custom Controls For a control to be useful. Each ControlPosition stores an MVCArray of the controls displayed in that position. For responding to user input. when controls are added or removed from the position.sans-serif'.850033. var map = new google.6500523). You add a custom control to the map by adding the Node (typically the <div>) to an appropriate ControlPosition.maps. google. For example.style. You can override this behavior by setting a control's index property to be a negative value. As a result. -87. your constructor will want access to the // DIV on which you'll attach the control UI to the Map.fontSize = '12px'.getElementById('map_canvas'). controlText. function() { map. the Maps API provides a cross-browser event handling method addDomListener() which handles most of the browser's supported DOM events. controlText. // Construct your control in whatever manner is appropriate.style.// Set CSS for the control interior var controlText = document.event.addDomListener(outer.setCenter(chicago) }). controlText. Positioning Custom Controls Custom controls are positioned on the map by placing them at appropriate positions within the Map object's controls property. the API will update the controls accordingly.paddingRight = '4px'.ControlPositions. not from the map.maps. mapOptions).maps. or it may respond to changes in the Map's state. // Setup the click event listener: simply set the map to center on Chicago var chicago = new google. var controlDiv = document.fontFamily = 'Arial.paddingLeft = '4px'. controlUI. but . with lower index values taking precedence. 'click'.createElement('DIV'). The API places controls at each position by the order of an index property.style. This property contains an array of google.innerHTML = 'Home'. controlText. controlText. Note that this event is received from the DOM.LatLng(41. controls with a lower index are placed first. What the control does is up to you. var myControl = new MyControl(controlDiv). Note that you will normally only need to set an index value if you wish to place your control "before" a default API control in the same position. two custom controls at position BOTTOM_RIGHT will be laid out according to this index order. // Generally. it must actually do something.style.Map(document.maps. By default.appendChild(controlText). all custom controls are placed after placing any API default controls. The following code snippet adds a listener for the browser's 'click' event.createElement('DIV'). The control may respond to user input. The following code creates a new custom control (its constructor is not shown) and adds it to the map in the TOP_RIGHT position.

maps. controlText. This code will // implicitly add the control to the DOM. /** * The HomeControl adds a control to the map that simply * returns the user to Chicago.padding = '5px'.style.850033.innerHTML = 'Home'.style.style.style.backgroundColor = 'white'. controlUI.style.title = 'Click to set the map to Home'.event. var chicago = new google.borderWidth = '2px'.push(controlDiv). controlUI. Note that we set this // value as a property of the DIV itself. controlUI. controlText.cursor = 'pointer'.createElement('DIV'). You should not attach the control manually. controlUI. // Set CSS for the control border var controlUI = document. // Set CSS for the control interior var controlText = document. controlUI.appendChild(controlUI).style.style.appendChild(controlText).6500523).maps.sans-serif'. */ function HomeControl(controlDiv. controlUI.paddingRight = '4px'. A Custom Control Example The following control is simple (though not particularly useful) and combines the patterns shown above.style. controlText. } . controlText. through the Map // object. This control responds to DOM 'click' events by centering the map at a certain default location: var map. map. function() { map. // Setup the click event listeners: simply set the map to Chicago google. controlUI.fontFamily = 'Arial. -87. 'click'.index = 1. controlDiv.borderStyle = 'solid'. controlText.style.paddingLeft = '4px'.textAlign = 'center'.// this would be how you do it.ControlPosition.LatLng(41. // Add the control to the map at a designated control position // by pushing it on the position's array.controls[google.createElement('DIV'). map) { // Set CSS styles for the DIV containing the control // Setting padding to 5 px will offset the control // from the edge of the map controlDiv. This constructor takes * the control DIV as an argument. controlDiv.setCenter(chicago) }).maps.fontSize = '12px'.style.addDomListener(controlUI.TOP_RIGHT].

We do so by creating a home_ property within the control to store this state and provide getters and setters for that state.prototype. // Create the DIV to hold the control and call the HomeControl() constructor // passing in this DIV. div.function initialize() { var mapDiv = document.maps.TOP_RIGHT]. . We'll attach our control UI to this DIV.home_ = home. mapTypeId: google.getHome = function() { return this. // We set up a variable for the 'this' keyword since we're adding event // listeners later and 'this' will be out of scope.maps.maps. var map. home) { // Get the control DIV. // Define setters and getters for this property HomeControl.prototype. var homeControl = new HomeControl(homeControlDiv. var homeControlDiv = document.MapTypeId. } HomeControl.push(homeControlDiv).home_.maps.LatLng(41. homeControlDiv. var control = this.6500523).index = 1.Map(mapDiv. var chicago = new google. myOptions).createElement('DIV'). var myOptions = { zoom: 12. center: chicago. /** * The HomeControl adds a control to the map that * returns the user to the control's defined home. map). -87.home_ = null.prototype. map.setHome = function(home) { this. // Set the home property upon construction control.850033. var controlDiv = div.ROADMAP } map = new google.controls[google.ControlPosition.getElementById('map_canvas').home_ = home. but the control contains an additional "Set Home" button which sets the control to exhibit a new home location. The following example is similar to that shown before. } Adding State to Controls Controls may also store state. */ // Define a property to hold the Home state HomeControl. } function HomeControl(map.

createElement('DIV'). goHomeUI. // Set CSS for the setHome control border var setHomeUI = document.index = 1.Map(mapDiv. myOptions).// Set CSS styles for the DIV containing the control.innerHTML = 'Set Home'.appendChild(setHomeText).createElement('DIV'). controlDiv.TOP_RIGHT].event.getHome(). var homeControl = new HomeControl(map.maps.appendChild(goHomeUI). map. goHomeUI. } function initialize() { var mapDiv = document.appendChild(setHomeUI). chicago). homeControlDiv.title = 'Click to set Home to the current center'.MapTypeId.getElementById('map_canvas').addDomListener(setHomeUI. // Setup the click event listener for Set Home: // Set the control's home to the current Map center.appendChild(goHomeText). control. setHomeUI.controls[google.setHome(newHome). var myOptions = { zoom: 12. controlDiv. setHomeUI. // Create the DIV to hold the control and call the HomeControl() // constructor passing in this DIV.getCenter(). mapTypeId: google.addDomListener(goHomeUI.maps.createElement('DIV'). map. // Set CSS for the control interior var goHomeText = document.maps.createElement('DIV'). // Setup the click event listener for Home: // simply set the map to the control's current home property.maps. // Set CSS for the control border var goHomeUI = document. function() { var newHome = map. // Set CSS for the control interior var setHomeText = document. function() { var currentHome = control.innerHTML = 'Home'. google. setHomeText. center: chicago. Setting padding to // 5 px will offset the control from the edge of the map controlDiv. goHomeText.style.padding = '5px'. }). homeControlDiv.ROADMAP } map = new google. google.event. 'click'. } .title = 'Click to set the map to Home'.push(homeControlDiv).setCenter(currentHome). 'click'. var homeControlDiv = document.ControlPosition.maps.createElement('DIV'). }).

var myOptions = { zoom: 4. Markers may sometimes display custom icon images. call setMap(). polygons define a region which they enclose. (For more information.131.363882.LatLng(-25. so they move when you drag or zoom the map. see Markers and Icons below. Overlays reflect objects that you "add" to the map to designate points. see Polylines. lines.) Areas of arbitrary shape on the map are displayed using polygons. unlike polylines. title:"Hello World!" }). see Info Windows. areas. (For more information. These custom overlays implement the OverlayView interface. var marker = new google. Lines are objects of type Polyline. mapTypeId: google.) Map layers may be displayed using overlay map types.maps. (For more information.044922).ROADMAP. see Custom Overlays.getElementById("map_canvas"). You may also add an overlay to the map directly by using the overlay's setMap() method.) You may also implement your own custom overlays. 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. var myLatlng = new google. You can create your own set of tiles by creating custom map types which either replace base map tile sets. center: myLatlng. . (For more information.maps. passing it the map on which to add the overlay. all overlays define an Options object for use in construction that allows you to designate the map on which they should appear. which are similar to polylines. } var map = new google.maps. (For more information.maps. // To add the marker to the map. The Maps API has several types of overlays: • Single locations on the map are displayed using markers. myOptions). see Polygons below. polygons are an ordered sequence of locations.) Lines on the map are displayed using polylines (representing an ordered sequence of locations). or collections of objects. or display on top of existing base map tile sets as overlays. (For more information.MapTypeId. in which case they are usually referred to as "icons." Markers and icons are objects of type Marker. Like polylines.) • • • • • Adding Overlays Overlays are often added to the map upon their construction.Marker({ position: myLatlng.Overlays Overview Overlays are objects on the map that are tied to latitude/longitude coordinates.Map(document. see Custom Map Types. marker.setMap(map).

but keeps them in the array function clearOverlays() { if (markersArray) { for (i in markersArray) { markersArray[i]. function initialize() { var haightAshbury = new google. it simply removes the overlay from the map. If instead you wish to delete the overlay. call the overlay's setMap() method. you should remove it from the map. you should create an array to hold the overlays. The overlays can then be later cleared.latLng).LatLng(37. mapOptions). you are responsible for keeping track of your overlays and removing them from the map when not needed. shown.event. map: map }). var markersArray = []. } } } // Shows any overlays currently in the array function showOverlays() { if (markersArray) { for (i in markersArray) { .MapTypeId. markersArray.maps. } function addMarker(location) { marker = new google.maps. passing null.Removing Overlays To remove an overlay from a map.TERRAIN }. or deleted: var map. which removes all references to the overlays.maps. } // Removes the overlays from the map. no clearOverlays() method exists. }).4469157).7699298.setMap(null). Note that calling this method does not delete the overlay. var mapOptions = { zoom: 12. mapTypeId: google.Map(document.addListener(map. google.push(marker). 'click'.getElementById("map_canvas"). Using this array. and then set the overlay itself to null. If you wish to manage a set of overlays. function(event) { addMarker(event. and places them within an array.) You can delete the overlays by removing them from the map and then setting the array's length to 0. map = new google. The following example places markers on a map when clicked on the map. you can then call setMap() on each overlay in the array when you need to remove them. center: haightAshbury.Marker({ position: location. -122.maps. (Note that unlike in V2.maps.

center: myLatlng. they receive 'click' events.maps.maps. they use a standard icon. } } View example (overlay-remove.131. The following example adds a simple marker to a map at Uluru.maps.html) Markers Markers identify locations on the map.setMap(map). for example.Map(document.getElementById("map_canvas"). By default.Marker({ position: myLatlng. } markersArray.maps. the marker is created but is not attached (or displayed) on the map. mapTypeId: google.044922).length = 0.} } } markersArray[i]. The google. Note that within the Marker constructor. You may add the marker later by calling the marker's setMap() method.MapTypeId. If you do not wish to pass any Marker options in the marker's constructor. Markers are designed to be interactive. you should specify the map on which to add the marker. The following fields are particularly important and commonly set when constructing your marker: • • position map (required) specifies a LatLng identifying the initial location of the marker. call the setMap() method passing null as the argument. though you can set a custom icon within the marker's constructor or by calling setIcon() on the marker. // Deletes all markers in the array by removing references to them function deleteOverlays() { if (markersArray) { for (i in markersArray) { markersArray[i]. (optional) specifies the Map object on which to place the marker.maps. and are often used within event listeners to bring up info windows. var marker = new google. To remove a marker. map: map.LatLng(-25.setMap(null). title:"Hello World!" }).363882. in the center of Australia: var myLatlng = new google.ROADMAP } var map = new google. . By default. If you do not specify this argument.Marker constructor takes a single Marker options object literal specifying the initial properties of the marker. instead pass an empty object {} in the last argument of the constructor. This Marker title will show up as a tooltip. var myOptions = { zoom: 4. myOptions).

Animation.maps.maps. position: parliament }).maps.DROP. Clicking on the marker toggles the marker between a BOUNCE animation or no animation: var var var var stockholm = new google. A bouncing marker will continue bouncing until its animation property is explicitly set to null.html) Animations You may also animate markers so that they exhibit dynamic movement in a variety of different circumstances.View example (marker-simple.maps.maps.maps.ROADMAP.LatLng(59.event. Sweden using a DROP animation.getElementById("map_canvas").32522.getAnimation() != null) { marker.maps. } function toggleBounce() { if (marker. BOUNCE You may initiate an animation on an existing marker by calling setAnimation() on the Marker object. of type google.maps.maps. The way a marker is animated is specified within the marker's animation property. marker = new google. draggable:true. mapOptions). toggleBounce). map = new google. This type of animation is usually specified during creation of the Marker. google.setAnimation(google. marker. parliament = new google.MapTypeId. Animation will cease once the marker comes to rest and animation will revert to null. } } View example (marker-animations. function initialize() { var mapOptions = { zoom: 13. The following Animation values are currently supported: • indicates that the marker should drop from the top of the map to its final location when first placed on the map.html) .Marker({ map:map.BOUNCE). 18. mapTypeId: google.Animation.07002). 18. animation: google.setAnimation(null). DROP • indicates that the marker should "bounce" in place.06747).addListener(marker.Animation. center: stockholm }.Map(document.327383. 'click'.LatLng(59. map. The following example creates a marker in Stockholm. } else { marker.

var myLatLng = new google. Defining an icon involves setting a number of properties that define the visual behavior of the marker.html) Icons Markers may define an icon to show in place of the default icon.Note: if you have many markers. i * 200). The Google Maps API will size the icon automatically in this case.getElementById("map_canvas"). add shadow images.maps.890542.maps. 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. var myOptions = { zoom: 4. you might not want to drop them all at once on the map.131. i < markerArray. . i++) { setTimeout(function() { addMarkerMethod(). 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.maps.363882. Icons specifed in this manner should set their icon and shadow properties to an object of type MarkerImage.Marker({ position: myLatLng.LatLng(-33. and specify the "stack order" of how they should display relative to other overlays. } } View example (marker-animations-iteration.Map(document.maps.274856).html) Complex Icons More complex icons will want to specify complex shapes (which indicate regions that are clickable).maps. var beachMarker = new google.png'. In the example below.044922).MapTypeId. we create an icon to signify the position of Bondi Beach in Sydney. mapTypeId: google. myOptions). center: myLatlng. var image = 'beachflag. } View example (icon-simple.length.LatLng(-25.ROADMAP } var map = new google. map: map. Australia: function initialize() { var myLatlng = new google. icon: image }). 151. Simple Icons In the most basic case. }.

151. function setMarkers(map. the origin of the icon (if the image you want is part of a larger image in a sprite.32) to correspond to the base of the flagpole.259052. ['Cronulla Beach'. beaches). objects not only define an image. Shadow images should be 24-bit PNG images with alpha transparency so that image boundaries appear correctly on the map. Australia.png'.Point(0. // Origins. and the bottom left corner of the shadow image should align with the bottomleft corner of the icon image. // This marker is 20 pixels wide by 32 pixels tall. a LatLng and a zIndex for * the order in which these markers should display on top of each * other. function initialize() { var myOptions = { zoom: 10. ['Maroubra Beach'. 5]. -33.maps.Point(0. 4].maps. NSW.0.028249. var shadow = new google. -33.Size(20. -34. 2]. but also define the size of the icon. // The origin for this image is 0.950198. locations) { // Add markers to the map // Marker sizes are expressed as a Size of X. center: new google.MarkerImage('images/beachflag_shadow.png'.0) is located // in the top left of the image.getElementById("map_canvas"). */ var beaches = [ ['Bondi Beach'.0). 32)). new google.maps.259302. setMarkers(map. myOptions). 32).LatLng(-33.MarkerImage('images/beachflag.Shadow images should generally be created at a 45 degree angle (upward and to the right) from the main image. Note that the anchor is set to (0. MarkerImage The following example creates complex markers to signify beaches near Sydney.ROADMAP } var map = new google. mapTypeId: google. -33. for example).157507.maps.Map(document. 151. ['Manly Beach'. 151. . 3]. 151.890542.32. 1] ]. -33.2).Y // where the origin of the image (0.9.maps. anchor positions and coordinates of the marker // increase in the X direction to the right and in // the Y direction down. // The shadow image is larger in the horizontal dimension // while the position and offset are the same as for the main image.923036. var image = new google. new google. new google. 151. and the anchor where the icon's hotspot should be located (which is based on the origin). ['Coogee Beach'. } /** * Data for the markers consisting of a name.274856.28747820854187. 151.maps.maps.80010128657071.MapTypeId.maps. // The anchor for this image is the base of the flagpole at 0.

Point(0. CA and Brisbane. shadow: shadow. icon: image. Polylines are drawn as a series of straight segments on the map.Point(0. 1. title: beach[0]. i++) { var beach = locations[i]. for (var i = 0. A Polyline object consists of an array of LatLng locations.0 and 1. 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. Australia: . The specifies a numerical fractional value between 0. beach[2]).Y points. map: map. weights.maps. // The type defines an HTML <area> element 'poly' which // traces out a polygon as a series of X. 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. var myLatLng = new google.maps. and opacities for the stroke of the line within a Polyline options object used when constructing your line. 18 .maps. i < locations.Size(37.length. strokeOpacity strokeWeight of the format "#FFFFFF". new google. 18.Marker({ position: myLatLng.LatLng(beach[1].maps. 32)). You can specify custom colors.0).maps. specifies the weight of the line's stroke in pixels. zIndex: beach[3] }). var marker = new google.html) Polylines The Polyline class defines a linear overlay of connected line segments on the map.} new google. type: 'poly' }. 32). 1]. and creates a series of line segments that connect those locations in an ordered sequence. } View example (icon-complex. or change those properties after construction. 20. The final // coordinate closes the poly by connecting to the first // coordinate. shape: shape.0 (default) of the opacity of the line's color. var shape = { coord: [1. A polyline supports the following stroke styles: • • • strokeColor specifies a hexadecimal HTML color Polyline class does not support named colors. 20. // Shapes define the clickable region of the icon. new google. 1.

maps.maps. you must use mvcArray.624333). var myOptions = { zoom: 7. -87. 178.LatLng(-27. function initialize() { var chicago = new google.maps.TERRAIN }. new google.Map(document.772323.maps. As such. new google. mapTypeId: google. var flightPlanCoordinates = [ new google. which will return an array of type MVCArray.214897).0.027892) ].LatLng(-18.LatLng(41. mapTypeId: google.html) Polyline Arrays A polyline specifies a series of coordinates as an array of LatLng objects. To retrieve these coordinates. var flightPath = new google.LatLng(37. var map. insertAt() removeAt() removes a LatLng at a given zero-based index value. inserts a passed LatLng at a given zero-based index value.setMap(map). .MapTypeId.LatLng(21.879535.MapTypeId. var myOptions = { zoom: 3. strokeOpacity: 1. Note that the polyline only appears once its path property contains two LatLng coordinates.142599. strokeColor: "#FF0000". new google.Polyline({ path: flightPlanCoordinates.function initialize() { var myLatLng = new google.maps. -122.getElementById("map_canvas"). 153. call the Polyline's getPath(). myOptions). var map = new google. var poly.maps.46758.431). View example (polyline-simple. -180).ROADMAP }.maps. Note that any existing coordinates at that index value are moved forward. Note: you cannot simply retrieve the ith element of an array by using the syntax mvcArray[i]. The following code creates an interactive map which constructs a polyline based on user clicks.821856). you can manipulate and inspect the array using the following operations: • • • getAt() returns the LatLng at a given zero-based index value. center: myLatLng. center: chicago. strokeWeight: 2 }).LatLng(0. -157.maps.291982.maps.maps. } flightPath.getAt(i).

Polygons may potentially exhibit complex shapes.maps. you can define custom colors.maps. Polygon Additionally.getLength().Map(document.Polyline(polyOptions). unlike polylines. // Add a new marker at the new plotted point on the polyline. Colors should be indicated in hexadecimal numeric HTML style. var polyOptions = { strokeColor: '#000000'. } /** * Handles click events on a map. a single polygon may specify multiple paths.html) Polygons objects are similar to Polyline objects in that they consist of a series of coordinates in an ordered sequence. they allow you to define a stroke. var marker = new google. title: '#' + path.latLng). Polygon Options As with polylines.addListener(map. Similar to polylines.getElementById('map_canvas'). weights.Marker({ position: event. strokeOpacity: 1.setMap(map).event.maps.0. However. addLatLng). // Add a listener for the click event google.latLng. including discontinuities (multiple polygons defined as one polygon).getPath(). * @param {MouseEvent} mouseEvent */ function addLatLng(event) { var path = poly. poly. map: map }). . myOptions).map = new google. polygons are designed to define regions within a closed loop. } View example (polyline-complex.push(event. which affects the outline of the polygon. and adds a new point to the Polyline. // Because path is an MVCArray. strokeWeight: 3 } poly = new google. "donuts" (where polygonal areas appear inside the polygon as "islands") and intersections of one or more polygons. and opacities for the edge of the polygon (the "stroke") and custom colors and opacities for the area within the enclosed region (the "fill"). we can simply append a new coordinate // and it will automatically appear path. instead of being open-ended.maps. For this reason. 'click'. they also allow you to define a fill region inside the polygon.

LatLng(25. strokeWeight: 2. but instead just // a simple array of LatLngs in the paths property bermudaTriangle = new google.maps. As well.LatLng(25.8.MapTypeId." (each of type MVCArray) where each array defines a separate sequence of ordered LatLng coordinates.LatLng(32. strokeColor: "#FF0000". -70.getElementById("map_canvas"). 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.Because a polygonal area may include several separate paths.75737).190262). you don't need to define this last coordinate. -80.Polygon({ paths: triangleCoords. you will still need to retrieve values from the polygon by manipulating the path as an MVCArray.321384. -64. for simple polygons consisting of only one path.Map(document. new google.setMap(map). -66. var bermudaTriangle. but notice that the first and last coordinate are the same location. strokeOpacity: 0.2685546875).maps. In practice. the API provides a simple getPath() methods for simple polygons consisting of one path.maps. } Polygon Auto-Completion The Polygon in the example above consists of four coordinates. fillOpacity: 0. fillColor: "#FF0000".maps. However.TERRAIN }.774252. ]. -80.466465.LatLng(24. new google. bermudaTriangle.maps. var myOptions = { zoom: 5. The following code snippet creates a polygon representing the Bermuda Triangle: function initialize() { var myLatLng = new google. the Polygon object's paths property specifies an "array of arrays.maps. you may construct a Polygon using a single array of LatLng coordinates as a convenience.35 }).maps. The Maps API will .maps. mapTypeId: google.LatLng(18. var triangleCoords = [ new google. Note: if you construct a polygon in this manner. center: myLatLng. however. which defines the loop.774252.190262) // Construct the polygon // Note that we don't specify an array or arrays. var map = new google. new google. since polygons define closed areas.886436490787712. myOptions).118292).

setMap(map).466465. The following code handles click events on the polygon by displaying information on the polygon's coordinates: var map.321384.LatLng(24.MapTypeId. Note that any existing coordinates at that index value are moved forward. Note: you cannot simply retrieve the ith element of an array by using the syntax mvcArray[i]. var myOptions = { zoom: 5.maps. .190262). -64.LatLng(18. mapTypeId: google. -66. strokeWeight: 3. bermudaTriangle.maps.886436490787712. Polygon Arrays A polygon specifies its series of coordinates as an array of arrays.LatLng(25.118292). strokeOpacity: 0. center: myLatLng.2685546875).35 }). function initialize() { var myLatLng = new google. var infoWindow.LatLng(32. var bermudaTriangle.maps. 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.automatically "close" any polygons by drawing a stroke connecting the last coordinate back to the first coordinate for any given paths. To retrieve these coordinates. insertAt() removeAt() removes a LatLng at a given zero-based index value.getAt(i).maps.getElementById("map_canvas"). bermudaTriangle = new google. fillColor: "#FF0000". strokeColor: "#FF0000". map = new google. The following example is identical to the first example except that the last coordinate is omitted. inserts a passed LatLng at a given zero-based index value. myOptions).75737) ].TERRAIN }. new google. Each "leaf" array is an array of LatLng coordinates specifying a single path.maps. you must use mvcArray. where each array is of type MVCArray. call the Polygon's getPaths() method. var triangleCoords = [ new google.maps. new google. -70.Map(document. -80.774252.8.Polygon({ paths: triangleCoords. fillOpacity: 0.maps.

for (var i =0.latLng. constrained to the given bounds. -74.ROADMAP } var map = new google.InfoWindow().18).maps.Map(document.lng() + "<br />".-74. var oldmap = new google. // Iterate over the vertices. new google.latLng). 'click'. The constructor for a GroundOverlay specifies a URL of an image and the LatLngBounds of the image as parameters.maps. mapTypeId: google. Ground Overlays Polygons are useful overlays to represent arbitrarily-sized areas.MapTypeId.maps. and conformed using the map's projection. showArrays).LatLng(40.maps.maps.-74. } // Replace our Info Window's content and position infowindow.716216.getElementById("map_canvas").LatLng(40. The image will be rendered on the map.length. } infowindow = new google.maps. } infowindow. contentString += "<br />" + "Coordinate: " + i + "<br />" + xy.setContent(contentString).latLng.lng().213393). i < vertices.// Add a listener for the click event google.lat() + ".maps.event. If you have an image that you wish to place on a map.maps.139235)). NJ on the map as an overlay: var newark = new google. The following example places an antique map of Newark.addListener(bermudaTriangle. var myOptions = { zoom: 13.getPath()." + xy.maps.LatLngBounds( new google. we can call getPath() // to return the MVCArray of LatLngs var vertices = this. you can use a GroundOverlay object.setPosition(event.lat() +".open(map). but they cannot display images.GroundOverlay( . i++) { var xy = vertices. myOptions).765641. contentString += "Clicked Location: <br />" + event. function showArrays(event) { // Since this Polygon only has one path.LatLng(40.getAt(i). infowindow. var imageBounds = new google." + event. center: newark. var contentString = "<b>Bermuda Triangle Polygon</b><br />".740.

open() method.lib. Once it reaches the maximum width. which specifies a set of initial parameters for display of the info window. If you wish to explicitly size the content. (If no marker is provided. or a DOM element itself. To change the info window's location you may either change its position explicitly by calling setPosition() on the info window. If you only want one info window to display at a time (as is the behavior on Google Maps).jpg". and enable scrolling if you wish. imageBounds). Note that if you do not enable scrolling and the content exceeds the space available in an info window. which you can reassign to different locations or markers upon map events (such as user clicks). a snippet of HTML. To make the info window visible. where the tip of the stem is at a specified location on the map.edu/maps/historical/newark_nj_1922. 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. 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. you need to call the open() method on the InfoWindow. or by attaching it to a new marker using the InfoWindow. the info window may still expand vertically if screen real estate is available. The info window looks a little like a comic-book word balloon. you should not need to modify this field. either pass it within the InfoWindow options constructor or call setContent() on the InfoWindow explicitly. the info window will open at its position property. The InfoWindow's content may contain either a string of text. you need only create one info window.setMap(map). it has a content area and a tapered stem. In practice. an info window expands to fit its content.) The InfoWindow options object is an object literal containing the following fields: • • • • contains either a string of text or DOM node to display within the info window when it is opened. the Marker with which to anchor it. Note that opening an info window on a marker will automatically update this value with a new position. a map may now display multiple InfoWindow objects if you so choose. and optionally. pixelOffset position maxWidth contains the LatLng at which this info window is anchored. the content may "spill" out of the info window. content contains an offset from the tip of the info window to the location on which the info window is anchored. You can see the info window in action by clicking business markers on Google Maps. Note that if you call open() without passing a marker. however. Upon creation."http://www. oldmap. you may use <div>s to do so. specifies the maximum width in pixels of the info window. the InfoWindow will use the position specified upon construction through the InfoWindow options object.utexas. an info window is not added to the map. By default. passing it the Map on which to open. The InfoWindow constructor takes an InfoWindow options object. To set this content. . Unlike behavior in V2 of the Google Maps API. Info Windows InfoWindows displays content in a floating window above the map.

maps. <a href="http://en. Uluru is '+ 'sacred to the Pitjantjatjara and Yankunytjatjara. var myLatlng = new google. Kata Tjuta and Uluru are the two major '+ 'features of the Uluru . 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.Kata Tjuta National Park.InfoWindow({ content: contentString }).The following code displays a marker within the center of Australia.</p>'+ '<p>Attribution: Uluru.event.wikipedia.MapTypeId. but are manipulated as a single unit.php? title=Uluru&oldid=297882194">'+ 'http://en. var contentString = '<div id="content">'+ '<div id="siteNotice">'+ '</div>'+ '<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+ '<div id="bodyContent">'+ '<p><b>Uluru</b>.131. also referred to as <b>Ayers Rock</b>.org/w/index. 2009). 450 km '+ '(280 mi) by road.maps.addListener(marker.getElementById("map_canvas").maps. is a large ' + 'sandstone rock formation in the southern part of the '+ 'Northern Territory.Marker({ position: myLatlng. It lies 335 km (208 mi) '+ 'south west of the nearest large town. var marker = new google. myOptions). '+ 'rock caves and ancient paintings. var myOptions = { zoom: 4. }).LatLng(-25. var infowindow = new google.363882. Layers generally reflect collections of objects that you add on top of the map to .ROADMAP } var map = new google. Clicking on that marker shows the info window. central Australia. Alice Springs. google. waterholes.open(map.Map(document. title:"Uluru (Ayers Rock)" }). the '+ 'Aboriginal people of the area.php?title=Uluru</a> (last visited June 22. Uluru is listed as a World '+ 'Heritage Site.044922). mapTypeId: google. function() { infowindow. 'click'.maps.marker).org/w/index. center: myLatlng.maps.</p>'+ '</div>'+ '</div>'.maps. It has many springs.wikipedia. map: map.

slightly altering the base tiles in a fashion consistent with the layer. polylines. the layer allows you to easily manage the rendering of thousands of markers. though they each provide click events which return data on those individual objects. KML Layer Options The KmlLayer() constructor optionally passes a number of KmlLayerOptions: • specifies the Map on which to render the KmlLayer. These data formats are displayed on a map using a KmlLayer object. As the bounds change. (You can remove them from the map by calling setMap() passing null. Note that most layers. This layer is returned by default within the DirectionsRenderer when requesting directions of travel mode BICYCLING. for example. KmlLayer Because the components within a KmlLayer are rendered on demand. objects appear on a map once their map property has been set. objects render data contained in Google Fusion Tables. features in the current viewport are automatically rendered. Polygons or GroundOverlays. KML <Placemark> and GeoRSS point elements are rendered as markers. instead. FusionTablesLayer The TrafficLayer object renders a layer depicting traffic conditions and overlays representing traffic.designate a common association. To add a layer to a map. by design. these objects are not Google Maps API Markers. <LineString> elements are rendered as polylines and <Polygon> elements are rendered as polygons. The Maps API has several types of layers: • • • • KmlLayer objects render KML and GeoRSS elements into a Maps API V3 tile overlay. You can hide a KmlLayer by setting this value to null within the setMap() method. Similarly. The BicyclingLayer object renders a layer of bike paths and/or bicycle-specific overlays into a common layer. whose constructor takes the URL of a publicly accessible KML or GeoRSS file. may not be accessed via their individual objects. Importantly. map . Polylines. however. Note that you can't access these constituent objects directly. This KML looks (and somewhat behaves) like familiar V3 overlay elements. 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.) The KmlLayer object manages the rendering of these child elements by automatically retrieving appropriate features for the map's given bounds. call setMap(). passing null. and polygons. Similarly. These layers are described below. you only need to call setMap(). they are rendered into a single object on the map. Layers may also alter the presentation layer of the map itself. KML and GeoRSS Layers The Google Maps API supports the KML and GeoRSS data formats for displaying geographic information. but may only be manipulated as a unit. passing it the map object on which to display the layer. to hide a layer. <GroundOverlay> elements are rendered as rectangular images on the map. The Maps API converts the provided geographic XML data into a KML representation which is displayed on the map using a V3 tile overlay.

it contains an immutable metadata property containing the layer's name. by default.MapTypeId. The following example constructs a KmlLayer from the given KML feed: var myLatlng = new google.Map(document. you will want to listen for the metadata_changed event. as features are displayed.maps. brings up an InfoWindow containing KML <title> and <description> information on the given feature. mapTypeId: google. You can inspect this information using the getMetadata() method.-102.maps. myOptions).maps. var ctaLayer = new google. a click on a KML feature generates a KmlMouseEvent.875696. snippet and author within a KmlLayerMetadata object literal.kml').com/svn/trunk/ggeoxml/cta. myOptions).ROADMAP } var map = new google. description.KmlLayer('http://gmapssamples.maps.maps.LatLng(41. Clicking on individual features.flickr. var myOptions = { zoom: 4.65625). mapTypeId: google.maps. when displaying a KmlLayer.MapTypeId.ROADMAP } var map = new google. features within the KmlLayer should not Additionally.496675. By default.-87.setMap(map).googlecode. they are rendered to look like clickable Maps API overlays. var georssLayer = new google. you may not access feature data from the KmlLayer object directly.maps. once the KmlLayer is rendered. var myOptions = { zoom: 11. The following example constructs a KmlLayer from the given GeoRSS feed: var myLatlng = new google.KmlLayer('http://api.Map(document. KML Feature Data Because KML may include a large number of features. center: myLatlng.LatLng(49.624207). ctaLayer.getElementById("map_canvas"). georssLayer. which passes the following information: .• preserveViewport specifies that the map should not be adjusted to the bounds of the KmlLayer's contents when showing the layer. which will indicate that the property has been populated. Additionally.setMap(map). the map is zoomed and positioned to show the entirety of the layer's contents • suppressInfoWindows indicates that clickable trigger the display of InfoWindow objects.getElementById("map_canvas"). center: myLatlng.com/services/feeds/geo/? g=322338@N20〈=en-us&format=feed-georss').maps. Because rendering of KmlLayer objects requires asynchronous communication to an external server. Instead.

0 but for markers includes the height of the marker. id: "id". -73.setMap(map).com" }.KmlLayer('http://www. function(kmlEvent) { var text = kmlEvent. description: "description". name: "Mr Nobody".LatLng(40. } Fusion Table Layers ( Experimental) The Google Maps API allows you to render data contained in Google Fusion Tables as a layer on a map using the FusionTablesLayer object. {suppressInfoWindows: true}).maps.description. myOptions). }).event. infoWindowHtml: "html".65.getElementById("map_canvas")." For polygonal objects.com".addListener(ctaLayer. A sample KmlFeatureData object is shown below: author: { email: "nobody@google. function showInDiv(text) { var sidediv = document. var myOptions = { zoom: 12. snippet: "snippet" } The following example displays KML feature <Description> text within a side <div> when the feature is clicked: var myLatlng = new google.• indicates the latitude/longitude coordinates at which to anchor the InfoWindow for this KML feature.95).kml'.maps. name: "name".maps. showInDiv(text). this offset is typically 0.innerHTML = text.ROADMAP } var map = new google.maps. but the true origin for markers.featureData.Map(document. A Google Fusion Table is a database table where each row contains data about a particular feature. for geographic data. var nyLayer = new google. 'click'. pixelOffset featureData • { contains a JSON structure of KmlFeatureData.getElementById('contentWindow').net/SearchKml/newyork. sidediv. This position is generally the clicked location for polygons. polylines. uri: "http://example. nyLayer. each row within a Google .searcharoo. mapTypeId: google.maps. position • indicates the offset from the above position to anchor the InfoWindow "tail.MapTypeId. google. and GroundOverlays. center: myLatlng.

BicyclingLayer().setMap(map). -71.3726399. Dark green routes indicated dedicated bicycle routes. providing clickable overlays which display a feature's additional data.maps.Map(document.Fusion Table additionally contains location data.1096528). Additionally. the layer alters the style of the base map itself to emphasize streets supporting bicycle routes and deemphasize streets inappropriate for bicycles. holding a feature's positional information. Create a constructor for your custom overlay. Implement an onAdd() method within your prototype. and set any initialization parameters to custom properties within that constructor. The following examples shows the Bicycle layer enabled on a map of Cambridge. var myOptions = { zoom: 14.maps.getElementById("map_canvas"). suggested bike routes and other overlays specific to bicycling usage on top of the given map. To create a custom overlay: • Set the custom object's prototype to a new instance of google. • • .maps.ROADMAP } var map = new google.LatLng(42.OverlayView(). Custom Overlays The Google Maps API V3 provides an OverlayView class for creating your own custom overlays. mapTypeId: google. Light green routes indicate streets with dedicated "bike lanes. The FusionTablesLayer provides an interface to a public Fusion Table and supports automatic rendering of this location data. The BicyclingLayer renders a layer of bike paths. center: myLatlng. The OverlayView is a base class providing several methods you must implement when creating your overlays. myOptions). and attach the overlay to the map. The class also provides a few methods that make it possible to translate between screen coordinates and locations on the map. This will effectively "subclass" the overlay class." Dashed routes indicate streets or paths otherwise recommended for bicycle usage. MA: var myLatlng = new google.onAdd() will be called when the map is ready for the overlay to be attached.. showing geographic data.MapTypeId.maps. OverlayView. is shown below: The Bicycling Layer The Google Maps API allows you to add bicycle information to your maps using the BicyclingLayer object. A sample Fusion table. var bikeLayer = new google. bikeLayer.maps.

draw() will be called when the object is first displayed as well. and handle the visual display of your object.getElementById("map_canvas"). myOptions). . // Explicitly call setMap() on this overlay this.Map(document. this.maps. var overlay.SATELLITE }. var map = new google. map) { // Now initialize all properties.) function USGSOverlay(bounds. we'll create a constructor for this class. and initialize the passed parameters as properties of the new object.323907. We do this by setting the new class' prototype to an instance of the parent class. function initialize() { var myLatLng = new google.MapTypeId. var bounds = new google. map).image_ = image.LatLngBounds(swBound. var myOptions = { zoom: 11.• • Implement a draw() method within your prototype.109291). this.LatLng(62.maps.400471. OverlayView. // Photograph courtesy of the U.map_ = map.maps.LatLng(62. var neBound = new google.281819.005608). -150. We'll step through this explanation below. this. var swBound = new google.maps.png'.S.bounds_ = bounds. image. We will also need to explicitly subclass the USGSOverlay from OverlayView. overlay = new USGSOverlay(bounds.maps.maps. We'll actually create this div // upon receipt of the add() method so we'll // leave it null for now. -150. } Next. We'll create a USGSOverlay object which contains a USGS image of the area in question and the bounds of the image.setMap(map). -150.LatLng(62. (We set the prototype here to an instance. SubClassing an Overlay We'll use OverlayView to create a simple image overlay (similar to the GGroundOverlay within the V2 API). because we do not wish to modify the parent class.div_ = null. neBound). srcImage. this. center: myLatLng. mapTypeId: google. Geological Survey var srcImage = 'images/talkeetna.287132). rather than the parent class itself. // We define a property to hold the image's // div. You should also implement an onRemove() method to clean up any elements you added within the overlay.

createElement('DIV'). // We add an overlay to a map via one of the map's panes. var img = document.div_ = div. The API indicates that the overlay has been added to the map by invoking the overlay's onAdd() method. img. img. and then finally attach the overlay to one of the map's panes. of type MapPanes." we'll use the overlayLayer map pane.createElement("img"). specify the stacking order for different layers on the map.overlayImage MapPanes. var div = document.floatShadow MapPanes.border = "none".} USGSOverlay. we need to ensure that all of the map's panes (which specify in what order objects are displayed on a map) are available. We'll handle this method by creating a <div> to hold our image. // Create the DIV and set some basic attributes.borderWidth = "0px".width = "100%".style.maps. We can't yet attach this overlay to the map in the overlay's constructor. Initializing an Overlay When the overlay is first instantiated and ready to display. which are nodes within the DOM tree. The set of panes.style.mapPane MapPanes. we'll attach our object to it as a child. USGSOverlay.style. Conveniently.style. the API provides a helper method indicating this has occurred.overlayShadow MapPanes.image_.overlayLayer MapPanes. // Set the overlay's div_ property to this DIV this. div. // Create an IMG element and attach it to the DIV. We'll handle that method in the next section. div.height = "100%".prototype = new google.appendChild(img).position = "absolute". In specific. add an <img> element. div. The following panes are possible.floatPane Because our image is a "ground overlay. img.style.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. we'll need to attach it to the map via the browser's DOM. div.overlayMouseTarget MapPanes.src = this. Once we have that pane. and enumerated in the order in which they are stacked from bottom to top: • • • • • • • MapPanes. attach it to the <div>.OverlayView(). .

div_.getPanes().x . USGSOverlay. from which we'll resize the <div>. // Resize the image's DIV to fit the indicated dimensions. though this operation is slightly more expensive.prototype. div.div_ = null.x + 'px'.style. 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.parentNode. var panes = this. you can implement your own hide() and show() methods to adjust the overlay's visibility. This method will be called automatically from the API if we ever set the overlay's map property to null. in turn this will resize the image to match the bounds we specified in the overlay's constructor. this.style.overlayLayer. var sw = overlayProjection. div.style.bounds_.fromLatLngToDivPixel(this.div_).bounds_.onRemove = function() { this. div.width = (ne. . // We'll use these coordinates to resize the DIV. We use a southwest and northeast // position of the overlay to peg it to the correct position and size. div.x) + 'px'. Drawing an Overlay Note that we haven't actually invoked any special visual display above.sw. var ne = overlayProjection. var overlayProjection = this. } Hiding and Showing an Overlay If you wish to hide or show an overlay rather than simply create or remove the overlay.y + 'px'. // We need to retrieve the projection from this overlay to do this.div_.getSouthWest()). you may detach the overlay from the map's DOM.draw = function() { // Size and position the overlay. Note that if you then reattach the overlay to the map's DOM. USGSOverlay.y) + 'px'.fromLatLngToDivPixel(this. Alternatively.height = (sw.removeChild(this. it will re-invoke the overlay's onAdd() method.y .getProjection(). panes.getNorthEast()). We'll therefore implement this draw() method. var div = this.ne.prototype.top = ne.style. } Removing an Overlay We'll also add an onRemove() method to cleanly remove the overlay from the map.} // We'll add this overlay to the overlayImage pane. The API invokes a separate draw() method on the overlay whenever it needs to draw the overlay on the map (including when first added).appendChild(div). // Retrieve the southwest and northeast coordinates of this overlay // in latlngs and convert them to pixels coordinates.left = sw.

hide().style. Additionally.div_. } else { this. } else { this."></div> .toggle = function() { if (this. } } } USGSOverlay.prototype. } } // Now we add an input button to initiate the toggle method // on the specific overlay <div id ="toolbar" width="100%.div_) { this.prototype."></input> </div> <div id="map_canvas" style="width: 100%.getMap()) { this.div_) { this. if we later reattach the map.toggleDOM = function() { if (this.visibility = "visible". we add a toogleDOM() method.The following example adds hide() and show() methods to the overlay's prototype which toggle the container <div>'s visibility.setMap(null). // Note that the visibility property must be a string enclosed in quotes USGSOverlay. which attaches or detaches the overlay to the map.style. Note that if we set the visibility to "hidden" and then detach the map from the DOM via toggleDOM(). height:20px.toggle().style.div_. it will be visible again." style="text-align:center"> <input type="button" value="Toggle Visibility" onclick="overlay.toggleDOM().hide = function() { if (this. since the containing <div> is recreated in the overlay's onAdd() method.setMap(this.show = function() { if (this.div_) { if (this. height: 95%.map_). } } USGSOverlay.visibility == "hidden") { this.visibility = "hidden"."></input> <input type="button" value="Toggle DOM Attachment" onclick="overlay.div_.show(). } } USGSOverlay.prototype.prototype.

Sign up to vote on this title
UsefulNot useful