December 16, 2016 | Author: Manoj Sharma | Category: N/A
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: html { height: 100% } body { height: 100%; margin: 0px; padding: 0px } #map_canvas { height: 100% } 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); }
Even in this simple example, there are a few things to note: 1. We declare the application as HTML5 using the 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:
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 declaration: html { height: 100% } body { height: 100%; margin: 0px; padding: 0px } #map_canvas { height: 100% }
This CSS declaration indicates that the map container (named map_canvas) should take up 100% of the height of the HTML body. Note that we must specifically declare those percentages for and as well.
Loading the Google Maps API
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 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
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 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 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
•
SATELLITE
•
HYBRID
•
TERRAIN
displays the normal, default 2D tiles of Google Maps. displays photographic tiles.
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.).
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 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
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 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!
Map Events Overview JavaScript within the browser is event driven, meaning that JavaScript responds to interactions by generating events, and expects a program to listen to interesting events. The event model for the Google Maps API V3 is similar to that used in V2 of the API, though much has changed under the hood. There are two types of events: •
User events (such as "click" mouse events) are propagated from the DOM to the Google Maps API. These events are separate and distinct from standard DOM events.
•
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. 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.maps.event namespace. Developers of V2 of the Google Maps API will be familiar with this usage.
UI Events Some objects within the Maps API are designed to respond to user events such as mouse or keyboard events. A google.maps.Marker object can listen to the following user events, for example: •
'click'
•
'dblclick'
•
'mouseup'
•
'mousedown'
•
'mouseover'
•
'mouseout'
These events may look like standard DOM events, but they are actually part of the Maps API. Because different browsers implement different DOM event models, the Maps API provides these mechanisms to listen for and respond to DOM events without needing to handle the various cross-browser peculiarities. 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. Whenever an object's property changes, the API will fire an event that the property has changed. For example, the API will fire a zoom_changed event on a map when the map's zoom level changes. You can intercept these state changes by registering addListener() event handlers on the event namespace method as well. User events and MVC state changes may look similar, but you generally wish to treat them differently in your code. MVC events, for example, do not pass arguments within their event. You will want to inspect the property that changed on an MVC state change by calling the appropriate getProperty method on that object.
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); google.maps.event.addListener(map, 'zoom_changed', function() { setTimeout(moveToDarwin, 3000); }); var marker = new google.maps.Marker({ position: myLatlng, map: map, title:"Hello World!" }); google.maps.event.addListener(marker, 'click', function() { map.setZoom(8); }); } 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.
Accessing Arguments in UI Events UI events within the Google Maps API V3 typically pass an event argument, which can be accessed by the event listener, noting the UI state when the event occurred. For example, a UI 'click' event typically passes a MouseEvent containing a latLng property denoting the clicked location on the map. Note that this behavior is unique to UI events; MVC state changes do not pass arguments in their events. You can access the event's arguments within an event listener the same way you would access an object's properties. The following example adds an event listener for the map, and creates a marker when the user clicks on the map at the clicked location.
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);
}
google.maps.event.addListener(map, 'click', function(event) { placeMarker(event.latLng); });
function placeMarker(location) { var marker = new google.maps.Marker({ position: location, map: map }); map.setCenter(location); }
Using Closures in Event Listeners When executing an event listener, it is often advantageous to have both private and persistent data attached to an object. JavaScript does not support "private" instance data, but it does support which allows inner functions to access outer variables. Closures are useful within event listeners to access variables not normally attached to the objects on which events occur. The following example uses a function closure in the event listener to assign a secret message to a set of markers. Clicking on each marker will review a portion of the secret message, which is not contained within the marker itself. 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); // Add 5 markers to the map at random locations var southWest = new google.maps.LatLng(-31.203405,125.244141); var northEast = new google.maps.LatLng(-25.363882,131.044922); var bounds = new google.maps.LatLngBounds(southWest,northEast); map.fitBounds(bounds); var lngSpan = northEast.lng() - southWest.lng(); var latSpan = northEast.lat() - southWest.lat(); for (var i = 0; i < 5; i++) { var location = new google.maps.LatLng(southWest.lat() + latSpan * Math.random(),
southWest.lng() + lngSpan * Math.random()); var marker = new google.maps.Marker({ position: location, map: map }); var j = i + 1; marker.setTitle(j.toString()); attachSecretMessage(marker, i); }
}
// The five markers show a secret message when clicked // but that message is not within the marker's instance data function attachSecretMessage(marker, number) { var message = ["This","is","the","secret","message"]; var infowindow = new google.maps.InfoWindow( { content: message[number], size: new google.maps.Size(50,50) }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); }); }
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. (User events do pass arguments which can be inspected.) If you need to inspect a property on an MVC state change, you should explicitly call the appropriate getProperty() method on that object. This inspection will always retrieve the current state of the MVC object, which may not be the state when the event was first fired. 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. Setting such a property will trigger a new event, for example, and if you always set a property within this event handler, you may end up creating an infinite loop. In the example below, we set up an event handler to respond to zoom events by bringing up an info window displaying that level. We also check whether the map is fully zoomed-out and zoom in to zoom level 17 if so. 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); var zoomLevel; var infowindow = new google.maps.InfoWindow(
{ content: 'Zoom Level Test', size: new google.maps.Size(50,50), position: myLatlng }); infowindow.open(map);
}
google.maps.event.addListener(map, 'zoom_changed', function() { zoomLevel = map.getZoom(); infowindow.setContent("Zoom: " + zoomLevel); if (zoomLevel == 0) { map.setZoom(10); } });
Listening to DOM Events The Google Maps Javascript API event model creates and manages its own custom events. However, the DOM (Document Object Model) within the browser also creates and dispatches its own events, according to the particular browser event model in use. If you wish to capture and respond to these events, the Maps API provides the addDomListener() static method to listen to and bind to DOM events. This convenience method has a signature as shown below: addDomListener(instance:Object, eventName:string, handler:Function)
where instance may be any DOM element supported by the browser, including: •
Hierarchical members of the DOM such as window or document.body.myform
•
Named elements such as document.getElementById("foo")
Note that addDomListener() simply passes the indicated event to the browser, which handles it according to the browser's DOM event model; however, almost all modern browsers at least support DOM Level 2. If you've been reading the documentation this far, you're probably already familiar with one DOM event: the window.onload event, which we've handled within the tag. We use this event to trigger the initial Javascript code once an HTML page is fully loaded, as shown below: function initialize() { // Map initialization }
Although this event is attached to the 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 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: function initialize() { // Map initialization } google.maps.event.addDomListener(window, 'load', initialize);
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.
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 Large Pan/Zoom for Navigation sizes larger than 400x350px Horizontal Bar for MapType screens larger than 320px wide Scale Not present
Small Screens Small Mini-Zoom for sizes smaller than 400x350px Dropdown for screens smaller than 320px wide Not present
iPhone
Android
Not present
"Android" control
Same as Large/Small Screens Not present
Same as Large/Small Screens 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); }
Adding Controls to the Map You may wish to tailor your interface by removing, adding, or modifying UI behavior or controls and ensure that future updates don't alter this behavior. If you wish to only add or modify existing behavior, you need to ensure that the control is explicitly added to your application. Some controls appear on the map by default while others will not appear unless you specifically request them. Adding or removing controls from the map is specified in the following Map options object's fields, which you set to true to make them visible or set to false to hide them: {
}
navigationControl: boolean, mapTypeControl: boolean, scaleControl: boolean
Note that the Maps API V3 does not currently allow you to dynamically add or remove controls. These must be set upon creation of the map through a Map options object. 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, so these modifications are additive to the default UI behavior. function initialize() { var myOptions = { zoom: 4,
center: new google.maps.LatLng(-33, 151), navigationControl: false, scaleControl: 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
•
google.maps.NavigationControlStyle.ZOOM_PAN
•
google.maps.NavigationControlStyle.ANDROID
•
google.maps.NavigationControlStyle.DEFAULT
displays a mini-zoom control, consisting of only + and - buttons. This style is appropriate for mobile devices. displays the standard zoom slider
control with a panning control, as on Google Maps. displays the small zoom control as used on the native Maps application on Android devices. 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
•
google.maps.MapTypeControlStyle.DROPDOWN_MENU
•
google.maps.MapTypeControlStyle.DEFAULT
displays the array of controls as
buttons in a horizontal bar as is shown on Google Maps. displays a single button control allowing you to select the map type via a dropdown menu. 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
•
navigationControl
•
scaleControl
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. 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. 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
•
TOP_RIGHT
•
LEFT_TOP
•
RIGHT_TOP indicates that the control below any TOP_RIGHT elements.
•
LEFT_CENTER
•
RIGHT_CENTER
•
LEFT_BOTTOM
•
RIGHT_BOTTOM
•
BOTTOM_CENTER
•
BOTTOM_LEFT
•
BOTTOM_RIGHT
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. 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. indicates that the control should be placed along the top left of the map, but below any TOP_LEFT elements. should be placed along the top right of the map, but
indicates that the control should be placed along the left side of the map, centered between the TOP_LEFT and BOTTOM_LEFT positions. indicates that the control should be placed along the right side of the map, centered between the TOP_RIGHT and BOTTOM_RIGHT positions. indicates that the control should be placed along the bottom left of the map, but above any BOTTOM_LEFT elements. indicates that the control should be placed along the bottom right of the map, but above any BOTTOM_RIGHT elements. indicates that the control should be placed along the bottom center of the
map. 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. 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 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 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 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 , a to hold the button outline, and another to hold the button interior. // Create a div to hold the control. var controlDiv = document.createElement('DIV'); // 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.style.padding = '5px'; // Set CSS for the control border var controlUI = document.createElement('DIV'); controlUI.style.backgroundColor = 'white'; controlUI.style.borderStyle = 'solid'; controlUI.style.borderWidth = '2px'; controlUI.style.cursor = 'pointer'; controlUI.style.textAlign = 'center'; controlUI.title = 'Click to set the map to Home'; controlDiv.appendChild(controlUI);
// Set CSS for the control interior var controlText = document.createElement('DIV'); controlText.style.fontFamily = 'Arial,sans-serif'; controlText.style.fontSize = '12px'; controlText.style.paddingLeft = '4px'; controlText.style.paddingRight = '4px'; controlText.innerHTML = 'Home'; controlUI.appendChild(controlText);
Handling Events from Custom Controls For a control to be useful, it must actually do something. What the control does is up to you. The control may respond to user input, or it may respond to changes in the Map's state. For responding to user input, the Maps API provides a cross-browser event handling method addDomListener() which handles most of the browser's supported DOM events. The following code snippet adds a listener for the browser's 'click' event. Note that this event is received from the DOM, not from the map. // Setup the click event listener: simply set the map to center on Chicago var chicago = new google.maps.LatLng(41.850033, -87.6500523); google.maps.event.addDomListener(outer, 'click', function() { map.setCenter(chicago) });
Positioning Custom Controls Custom controls are positioned on the map by placing them at appropriate positions within the Map object's controls property. This property contains an array of google.maps.ControlPositions. You add a custom control to the map by adding the Node (typically the ) to an appropriate ControlPosition. Each ControlPosition stores an MVCArray of the controls displayed in that position. As a result, when controls are added or removed from the position, the API will update the controls accordingly. The API places controls at each position by the order of an index property; controls with a lower index are placed first. For example, two custom controls at position BOTTOM_RIGHT will be laid out according to this index order, with lower index values taking precedence. By default, all custom controls are placed after placing any API default controls. You can override this behavior by setting a control's index property to be a negative value. 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. The following code creates a new custom control (its constructor is not shown) and adds it to the map in the TOP_RIGHT position. var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions); // Construct your control in whatever manner is appropriate. // Generally, your constructor will want access to the // DIV on which you'll attach the control UI to the Map. var controlDiv = document.createElement('DIV'); var myControl = new MyControl(controlDiv); // We don't really need to set an index value here, but
// this would be how you do it. Note that we set this // value as a property of the DIV itself. controlDiv.index = 1; // Add the control to the map at a designated control position // by pushing it on the position's array. This code will // implicitly add the control to the DOM, through the Map // object. You should not attach the control manually. map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv);
A Custom Control Example The following control is simple (though not particularly useful) and combines the patterns shown above. This control responds to DOM 'click' events by centering the map at a certain default location: var map; var chicago = new google.maps.LatLng(41.850033, -87.6500523); /** * The HomeControl adds a control to the map that simply * returns the user to Chicago. This constructor takes * the control DIV as an argument. */ function HomeControl(controlDiv, 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.style.padding = '5px'; // Set CSS for the control border var controlUI = document.createElement('DIV'); controlUI.style.backgroundColor = 'white'; controlUI.style.borderStyle = 'solid'; controlUI.style.borderWidth = '2px'; controlUI.style.cursor = 'pointer'; controlUI.style.textAlign = 'center'; controlUI.title = 'Click to set the map to Home'; controlDiv.appendChild(controlUI); // Set CSS for the control interior var controlText = document.createElement('DIV'); controlText.style.fontFamily = 'Arial,sans-serif'; controlText.style.fontSize = '12px'; controlText.style.paddingLeft = '4px'; controlText.style.paddingRight = '4px'; controlText.innerHTML = 'Home'; controlUI.appendChild(controlText);
}
// 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); }
Adding State to Controls Controls may also store state. The following example is similar to that shown before, but the control contains an additional "Set Home" button which sets the control to exhibit a new home location. We do so by creating a home_ property within the control to store this state and provide getters and setters for that state. var map; var chicago = new google.maps.LatLng(41.850033, -87.6500523); /** * The HomeControl adds a control to the map that * returns the user to the control's defined home. */ // Define a property to hold the Home state HomeControl.prototype.home_ = null; // Define setters and getters for this property HomeControl.prototype.getHome = function() { return this.home_; } HomeControl.prototype.setHome = function(home) { this.home_ = home; } function HomeControl(map, div, 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; // Set the home property upon construction control.home_ = home;
// 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.style.padding = '5px'; // Set CSS for the control border var goHomeUI = document.createElement('DIV'); goHomeUI.title = 'Click to set the map to Home'; controlDiv.appendChild(goHomeUI); // Set CSS for the control interior var goHomeText = document.createElement('DIV'); goHomeText.innerHTML = 'Home'; goHomeUI.appendChild(goHomeText); // Set CSS for the setHome control border var setHomeUI = document.createElement('DIV'); setHomeUI.title = 'Click to set Home to the current center'; controlDiv.appendChild(setHomeUI); // Set CSS for the control interior var setHomeText = document.createElement('DIV'); setHomeText.innerHTML = 'Set Home'; setHomeUI.appendChild(setHomeText); // Setup the click event listener for Home: // simply set the map to the control's current home property. google.maps.event.addDomListener(goHomeUI, 'click', function() { var currentHome = control.getHome(); map.setCenter(currentHome); });
}
// Setup the click event listener for Set Home: // Set the control's home to the current Map center. google.maps.event.addDomListener(setHomeUI, 'click', function() { var newHome = map.getCenter(); control.setHome(newHome); });
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); var marker = new google.maps.Marker({ position: myLatlng, title:"Hello World!" }); // To add the marker to the map, call setMap(); marker.setMap(map);
Removing Overlays To remove an overlay from a map, call the overlay's setMap() method, passing null. Note that calling this method does not delete the overlay; it simply removes the overlay from the map. If instead you wish to delete the overlay, you should remove it from the map, and then set the overlay itself to null. If you wish to manage a set of overlays, you should create an array to hold the overlays. Using this array, you can then call setMap() on each overlay in the array when you need to remove them. (Note that unlike in V2, no clearOverlays() method exists; you are responsible for keeping track of your overlays and removing them from the map when not needed.) You can delete the overlays by removing them from the map and then setting the array's length to 0, which removes all references to the overlays. The following example places markers on a map when clicked on the map, and places them within an array. The overlays can then be later cleared, shown, or deleted: var map; var markersArray = []; function initialize() { var haightAshbury = new google.maps.LatLng(37.7699298, -122.4469157); var mapOptions = { zoom: 12, center: haightAshbury, mapTypeId: google.maps.MapTypeId.TERRAIN }; map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
google.maps.event.addListener(map, 'click', function(event) { addMarker(event.latLng); });
function addMarker(location) { marker = new google.maps.Marker({ position: location, map: map }); markersArray.push(marker); } // Removes the overlays from the map, but keeps them in the array function clearOverlays() { if (markersArray) { for (i in markersArray) { markersArray[i].setMap(null); } } } // Shows any overlays currently in the array function showOverlays() { if (markersArray) { for (i in markersArray) {
} }
markersArray[i].setMap(map);
}
// Deletes all markers in the array by removing references to them function deleteOverlays() { if (markersArray) { for (i in markersArray) { markersArray[i].setMap(null); } markersArray.length = 0; } }
View example (overlay-remove.html)
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
•
map
(required) specifies a LatLng identifying the initial location of the marker.
(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); var marker = new google.maps.Marker({ position: myLatlng, map: map, title:"Hello World!" });
This Marker title will show up as a tooltip. If you do not wish to pass any Marker options in the marker's constructor, instead pass an empty object {} in the last argument of the constructor.
View example (marker-simple.html)
Animations You may also animate markers so that they exhibit dynamic movement in a variety of different circumstances. The way a marker is animated is specified within the marker's animation property, of type google.maps.Animation. The following Animation values are currently supported: •
DROP
•
BOUNCE
indicates that the marker should drop from the top of the map to its final location when first placed on the map. Animation will cease once the marker comes to rest and animation will revert to null. This type of animation is usually specified during creation of the Marker. indicates that the marker should "bounce" in place. A bouncing marker will continue bouncing until its animation property is explicitly set to null.
You may initiate an animation on an existing marker by calling setAnimation() on the Marker object. The following example creates a marker in Stockholm, Sweden using a DROP animation. Clicking on the marker toggles the marker between a BOUNCE animation or no animation: var var var var
stockholm = new google.maps.LatLng(59.32522, 18.07002); parliament = new google.maps.LatLng(59.327383, 18.06747); marker; map;
function initialize() { var mapOptions = { zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP, center: stockholm }; map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
marker = new google.maps.Marker({ map:map, draggable:true, animation: google.maps.Animation.DROP, position: parliament }); google.maps.event.addListener(marker, 'click', toggleBounce);
function toggleBounce() { if (marker.getAnimation() != null) { marker.setAnimation(null); } else { marker.setAnimation(google.maps.Animation.BOUNCE); } }
View example (marker-animations.html)
Note: if you have many markers, you might not want to drop them all at once on the map. You can make use of setTimeout() to space your markers' animations apart using a pattern like that shown below: function drop() { for (var i =0; i < markerArray.length; i++) { setTimeout(function() { addMarkerMethod(); }, i * 200); } }
View example (marker-animations-iteration.html)
Icons Markers may define an icon to show in place of the default icon. Defining an icon involves setting a number of properties that define the visual behavior of the marker.
Simple Icons In the most basic case, an icon can simply indicate an image to use instead of the default Google Maps pushpin icon by setting the marker's icon property to the URL of an image. The Google Maps API will size the icon automatically in this case. In the example below, we create an icon to signify the position of Bondi Beach in Sydney, Australia: function initialize() { var myLatlng = new google.maps.LatLng(-25.363882,131.044922); var myOptions = { zoom: 4, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
var image = 'beachflag.png'; var myLatLng = new google.maps.LatLng(-33.890542, 151.274856); var beachMarker = new google.maps.Marker({ position: myLatLng, map: map, icon: image });
View example (icon-simple.html)
Complex Icons More complex icons will want to specify complex shapes (which indicate regions that are clickable), add shadow images, and specify the "stack order" of how they should display relative to other overlays. Icons specifed in this manner should set their icon and shadow properties to an object of type MarkerImage.
Shadow images should generally be created at a 45 degree angle (upward and to the right) from the main image, and the bottom left corner of the shadow image should align with the bottomleft corner of the icon image. Shadow images should be 24-bit PNG images with alpha transparency so that image boundaries appear correctly on the map. objects not only define an image, but also define the size of the icon, the origin of the icon (if the image you want is part of a larger image in a sprite, for example), and the anchor where the icon's hotspot should be located (which is based on the origin). MarkerImage
The following example creates complex markers to signify beaches near Sydney, NSW, Australia. Note that the anchor is set to (0,32) to correspond to the base of the flagpole. function initialize() { var myOptions = { zoom: 10, center: new google.maps.LatLng(-33.9, 151.2), mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); setMarkers(map, beaches); } /** * Data for the markers consisting of a name, a LatLng and a zIndex for * the order in which these markers should display on top of each * other. */ var beaches = [ ['Bondi Beach', -33.890542, 151.274856, 4], ['Coogee Beach', -33.923036, 151.259052, 5], ['Cronulla Beach', -34.028249, 151.157507, 3], ['Manly Beach', -33.80010128657071, 151.28747820854187, 2], ['Maroubra Beach', -33.950198, 151.259302, 1] ]; function setMarkers(map, locations) { // Add markers to the map // Marker sizes are expressed as a Size of X,Y // where the origin of the image (0,0) is located // in the top left of the image. // Origins, anchor positions and coordinates of the marker // increase in the X direction to the right and in // the Y direction down. var image = new google.maps.MarkerImage('images/beachflag.png', // This marker is 20 pixels wide by 32 pixels tall. new google.maps.Size(20, 32), // The origin for this image is 0,0. new google.maps.Point(0,0), // The anchor for this image is the base of the flagpole at 0,32. new google.maps.Point(0, 32)); var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png', // The shadow image is larger in the horizontal dimension // while the position and offset are the same as for the main image.
}
new google.maps.Size(37, 32), new google.maps.Point(0,0), new google.maps.Point(0, 32)); // Shapes define the clickable region of the icon. // The type defines an HTML element 'poly' which // traces out a polygon as a series of X,Y points. The final // coordinate closes the poly by connecting to the first // coordinate. var shape = { coord: [1, 1, 1, 20, 18, 20, 18 , 1], type: 'poly' }; for (var i = 0; i < locations.length; i++) { var beach = locations[i]; var myLatLng = new google.maps.LatLng(beach[1], beach[2]); var marker = new google.maps.Marker({ position: myLatLng, map: map, shadow: shadow, icon: image, shape: shape, title: beach[0], zIndex: beach[3] }); }
View example (icon-complex.html)
Polylines The Polyline class defines a linear overlay of connected line segments on the map. A Polyline object consists of an array of LatLng locations, and creates a series of line segments that connect those locations in an ordered sequence.
Polyline Options The Polyline constructor takes a set of Polyline options specifying the LatLng coordinates of the line and a set of styles to adjust the polyline's visual behavior. Polylines
are drawn as a series of straight segments on the map. You can specify custom colors, weights, and opacities for the stroke of the line within a Polyline options object used when constructing your line, or change those properties after construction. A polyline supports the following stroke styles: •
strokeColor specifies a hexadecimal HTML color Polyline class does not support named colors.
•
strokeOpacity
•
strokeWeight
of the format "#FFFFFF". The
specifies a numerical fractional value between 0.0 and 1.0 (default) of the opacity of the line's color. specifies the weight of the line's stroke in pixels.
The following code snippet creates a 2-pixel-wide red polyline connecting the path of William Kingsford Smith's first trans-Pacific flight between Oakland, CA and Brisbane, Australia:
function initialize() { var myLatLng = new google.maps.LatLng(0, -180); var myOptions = { zoom: 3, center: myLatLng, mapTypeId: google.maps.MapTypeId.TERRAIN }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var flightPlanCoordinates = [ new google.maps.LatLng(37.772323, -122.214897), new google.maps.LatLng(21.291982, -157.821856), new google.maps.LatLng(-18.142599, 178.431), new google.maps.LatLng(-27.46758, 153.027892) ]; var flightPath = new google.maps.Polyline({ path: flightPlanCoordinates, strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 2 }); }
flightPath.setMap(map);
View example (polyline-simple.html)
Polyline Arrays A polyline specifies a series of coordinates as an array of LatLng objects. To retrieve these coordinates, call the Polyline's getPath(), which will return an array of type MVCArray. As such, you can manipulate and inspect the array using the following operations: •
getAt()
•
insertAt()
•
removeAt()
returns the LatLng at a given zero-based index value.
inserts a passed LatLng at a given zero-based index value. Note that any existing coordinates at that index value are moved forward. 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);
}
// Add a listener for the click event google.maps.event.addListener(map, 'click', addLatLng);
/** * Handles click events on a map, and adds a new point to the Polyline. * @param {MouseEvent} mouseEvent */ function addLatLng(event) { var path = poly.getPath(); // Because path is an MVCArray, we can simply append a new coordinate // and it will automatically appear path.push(event.latLng);
}
// Add a new marker at the new plotted point on the polyline. var marker = new google.maps.Marker({ position: event.latLng, title: '#' + path.getLength(), map: map });
View example (polyline-complex.html)
Polygons 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. Polygon
Additionally, Polygons may potentially exhibit complex shapes, including discontinuities (multiple polygons defined as one polygon), "donuts" (where polygonal areas appear inside the polygon as "islands") and intersections of one or more polygons. For this reason, a single polygon may specify multiple paths.
Polygon Options As with polylines, you can define custom colors, weights, and opacities for the edge of the polygon (the "stroke") and custom colors and opacities for the area within the enclosed region (the "fill"). Colors should be indicated in hexadecimal numeric HTML style.
Because a polygonal area may include several separate paths, the Polygon object's paths property specifies an "array of arrays," (each of type MVCArray) where each array defines a separate sequence of ordered LatLng coordinates. However, for simple polygons consisting of only one path, you may construct a Polygon using a single array of LatLng coordinates as a convenience. The Google Maps API will convert this simple array into an "array of arrays" upon construction when storing it within the Polygon's paths property. As well, the API provides a simple getPath() methods for simple polygons consisting of one path. Note: if you construct a polygon in this manner, you will still need to retrieve values from the polygon by manipulating the path as an MVCArray. The following code snippet creates a polygon representing the Bermuda Triangle: function initialize() { var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875); var myOptions = { zoom: 5, center: myLatLng, mapTypeId: google.maps.MapTypeId.TERRAIN }; var bermudaTriangle; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var triangleCoords = [ new google.maps.LatLng(25.774252, new google.maps.LatLng(18.466465, new google.maps.LatLng(32.321384, new google.maps.LatLng(25.774252, ];
-80.190262), -66.118292), -64.75737), -80.190262)
// Construct the polygon // Note that we don't specify an array or arrays, but instead just // a simple array of LatLngs in the paths property bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#FF0000", fillOpacity: 0.35 }); bermudaTriangle.setMap(map); }
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()
•
insertAt()
•
removeAt()
returns the LatLng at a given zero-based index value.
inserts a passed LatLng at a given zero-based index value. Note that any existing coordinates at that index value are moved forward. removes a LatLng at a given zero-based index value.
Note: you cannot simply retrieve the ith element of an array by using the syntax mvcArray[i]; you must use mvcArray.getAt(i). The following code handles click events on the polygon by displaying information on the polygon's coordinates: var map; var infoWindow; function initialize() { var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875); var myOptions = { zoom: 5, center: myLatLng, mapTypeId: google.maps.MapTypeId.TERRAIN }; var bermudaTriangle; map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var triangleCoords = [ new google.maps.LatLng(25.774252, -80.190262), new google.maps.LatLng(18.466465, -66.118292), new google.maps.LatLng(32.321384, -64.75737) ]; bermudaTriangle = new google.maps.Polygon({ paths: triangleCoords, strokeColor: "#FF0000", strokeOpacity: 0.8, strokeWeight: 3, fillColor: "#FF0000", fillOpacity: 0.35 }); bermudaTriangle.setMap(map);
// Add a listener for the click event google.maps.event.addListener(bermudaTriangle, 'click', showArrays); }
infowindow = new google.maps.InfoWindow();
function showArrays(event) { // Since this Polygon only has one path, we can call getPath() // to return the MVCArray of LatLngs var vertices = this.getPath(); var contentString = "Bermuda Triangle Polygon"; contentString += "Clicked Location: " + event.latLng.lat() + "," + event.latLng.lng() + ""; // Iterate over the vertices. for (var i =0; i < vertices.length; i++) { var xy = vertices.getAt(i); contentString += "" + "Coordinate: " + i + "" + xy.lat() +"," + xy.lng(); } // Replace our Info Window's content and position infowindow.setContent(contentString); infowindow.setPosition(event.latLng); }
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 } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var oldmap = new google.maps.GroundOverlay(
"http://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg", imageBounds); oldmap.setMap(map);
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
•
pixelOffset
•
position
•
maxWidth
contains either a string of text or DOM node to display within the info window when it is opened. 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. 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. 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 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 } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var contentString = ''+ ''+ ''+ 'Uluru'+ ''+ 'Uluru, also referred to as Ayers Rock, is a large ' + 'sandstone rock formation in the southern part of the '+ 'Northern Territory, central Australia. It lies 335 km (208 mi) '+ 'south west of the nearest large town, Alice Springs; 450 km '+ '(280 mi) by road. Kata Tjuta and Uluru are the two major '+ 'features of the Uluru - Kata Tjuta National Park. Uluru is '+ 'sacred to the Pitjantjatjara and Yankunytjatjara, the '+ 'Aboriginal people of the area. It has many springs, waterholes, '+ 'rock caves and ancient paintings. Uluru is listed as a World '+ 'Heritage Site.'+ 'Attribution: Uluru, '+ 'http://en.wikipedia.org/w/index.php?title=Uluru (last visited June 22, 2009).'+ ''+ ''; var infowindow = new google.maps.InfoWindow({ content: contentString }); var marker = new google.maps.Marker({ position: myLatlng, map: map, title:"Uluru (Ayers Rock)" }); google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker); });
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
•
FusionTablesLayer
•
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.
objects render KML and GeoRSS elements into a Maps API V3 tile overlay. objects render data contained in Google Fusion Tables.
These layers are described below.
KML and GeoRSS Layers The Google Maps API supports the KML and GeoRSS data formats for displaying geographic information. These data formats are displayed on a map using a KmlLayer object, whose constructor takes the URL of a publicly accessible KML or GeoRSS file. The Maps API converts the provided geographic XML data into a KML representation which is displayed on the map using a V3 tile overlay. This KML looks (and somewhat behaves) like familiar V3 overlay elements. KML and GeoRSS point elements are rendered as markers, for example, elements are rendered as polylines and elements are rendered as polygons. Similarly, elements are rendered as rectangular images on the map. Importantly, however, these objects are not Google Maps API Markers, Polylines, Polygons or GroundOverlays; instead, they are rendered into a single object on the map. objects appear on a map once their map property has been set. (You can remove them from the map by calling setMap() passing null.) The KmlLayer object manages the rendering of these child elements by automatically retrieving appropriate features for the map's given bounds. As the bounds change, features in the current viewport are automatically rendered. KmlLayer
Because the components within a KmlLayer are rendered on demand, the layer allows you to easily manage the rendering of thousands of markers, polylines, and polygons. Note that you can't access these constituent objects directly, 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. You can hide a KmlLayer by setting this value to null within the setMap() method. map
•
preserveViewport specifies that the map should not be adjusted to the bounds of the KmlLayer's contents when showing the layer. By default, when displaying a KmlLayer,
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.
features within the KmlLayer should not
Additionally, once the KmlLayer is rendered, it contains an immutable metadata property containing the layer's name, description, snippet and author within a KmlLayerMetadata object literal. You can inspect this information using the getMetadata() method. Because rendering of KmlLayer objects requires asynchronous communication to an external server, you will want to listen for the metadata_changed event, which will indicate that the property has been populated. The following example constructs a KmlLayer from the given GeoRSS feed: var myLatlng = new google.maps.LatLng(49.496675,-102.65625); var myOptions = { zoom: 4, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var georssLayer = new google.maps.KmlLayer('http://api.flickr.com/services/feeds/geo/? g=322338@N20〈=en-us&format=feed-georss'); georssLayer.setMap(map);
The following example constructs a KmlLayer from the given KML feed: var myLatlng = new google.maps.LatLng(41.875696,-87.624207); var myOptions = { zoom: 11, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var ctaLayer = new google.maps.KmlLayer('http://gmapssamples.googlecode.com/svn/trunk/ggeoxml/cta.kml'); ctaLayer.setMap(map);
KML Feature Data Because KML may include a large number of features, you may not access feature data from the KmlLayer object directly. Instead, as features are displayed, they are rendered to look like clickable Maps API overlays. Clicking on individual features, by default, brings up an InfoWindow containing KML and information on the given feature. Additionally, a click on a KML feature generates a KmlMouseEvent, which passes the following information:
•
position
•
pixelOffset
•
featureData
indicates the latitude/longitude coordinates at which to anchor the InfoWindow for this KML feature. This position is generally the clicked location for polygons, polylines, and GroundOverlays, but the true origin for markers. indicates the offset from the above position to anchor the InfoWindow "tail." For polygonal objects, this offset is typically 0,0 but for markers includes the height of the marker. contains a JSON structure of KmlFeatureData.
A sample KmlFeatureData object is shown below: {
}
author: { email: "
[email protected]", name: "Mr Nobody", uri: "http://example.com" }, description: "description", id: "id", infoWindowHtml: "html", name: "name", snippet: "snippet"
The following example displays KML feature text within a side when the feature is clicked: var myLatlng = new google.maps.LatLng(40.65, -73.95); var myOptions = { zoom: 12, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var nyLayer = new google.maps.KmlLayer('http://www.searcharoo.net/SearchKml/newyork.kml', {suppressInfoWindows: true}); nyLayer.setMap(map); google.maps.event.addListener(ctaLayer, 'click', function(kmlEvent) { var text = kmlEvent.featureData.description; showInDiv(text); }); function showInDiv(text) { var sidediv = document.getElementById('contentWindow'); sidediv.innerHTML = text; }
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. A Google Fusion Table is a database table where each row contains data about a particular feature; for geographic data, each row within a Google
Fusion Table additionally contains location data, holding a feature's positional information. The FusionTablesLayer provides an interface to a public Fusion Table and supports automatic rendering of this location data, providing clickable overlays which display a feature's additional data. A sample Fusion table, showing geographic data, is shown below:
The Bicycling Layer The Google Maps API allows you to add bicycle information to your maps using the BicyclingLayer object. The BicyclingLayer renders a layer of bike paths, suggested bike routes and other overlays specific to bicycling usage on top of the given map. Additionally, the layer alters the style of the base map itself to emphasize streets supporting bicycle routes and deemphasize streets inappropriate for bicycles. The following examples shows the Bicycle layer enabled on a map of Cambridge, MA: var myLatlng = new google.maps.LatLng(42.3726399, -71.1096528); var myOptions = { zoom: 14, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var bikeLayer = new google.maps.BicyclingLayer(); bikeLayer.setMap(map);
Dark green routes indicated dedicated bicycle routes. Light green routes indicate streets with dedicated "bike lanes." Dashed routes indicate streets or paths otherwise recommended for bicycle usage.
Custom Overlays The Google Maps API V3 provides an OverlayView class for creating your own custom overlays. The OverlayView is a base class providing several methods you must implement when creating your overlays. The class also provides a few methods that make it possible to translate between screen coordinates and locations on the map. To create a custom overlay: •
Set the custom object's prototype to a new instance of google.maps.OverlayView(). This will effectively "subclass" the overlay class.
•
Create a constructor for your custom overlay, and set any initialization parameters to custom properties within that constructor.
•
Implement an onAdd() method within your prototype, and attach the overlay to the map. OverlayView.onAdd() will be called when the map is ready for the overlay to be attached..
•
Implement a draw() method within your prototype, and handle the visual display of your object. OverlayView.draw() will be called when the object is first displayed as well.
•
You should also implement an onRemove() method to clean up any elements you added within the overlay.
We'll step through this explanation below.
SubClassing an Overlay We'll use OverlayView to create a simple image overlay (similar to the GGroundOverlay within the V2 API). We'll create a USGSOverlay object which contains a USGS image of the area in question and the bounds of the image. var overlay; function initialize() { var myLatLng = new google.maps.LatLng(62.323907, -150.109291); var myOptions = { zoom: 11, center: myLatLng, mapTypeId: google.maps.MapTypeId.SATELLITE }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var swBound = new google.maps.LatLng(62.281819, -150.287132); var neBound = new google.maps.LatLng(62.400471, -150.005608); var bounds = new google.maps.LatLngBounds(swBound, neBound);
}
// Photograph courtesy of the U.S. Geological Survey var srcImage = 'images/talkeetna.png'; overlay = new USGSOverlay(bounds, srcImage, map);
Next, we'll create a constructor for this class, and initialize the passed parameters as properties of the new object. We will also need to explicitly subclass the USGSOverlay from OverlayView. We do this by setting the new class' prototype to an instance of the parent class. (We set the prototype here to an instance, rather than the parent class itself, because we do not wish to modify the parent class.) function USGSOverlay(bounds, image, map) { // Now initialize all properties. this.bounds_ = bounds; this.image_ = image; this.map_ = map; // We define a property to hold the image's // div. We'll actually create this div // upon receipt of the add() method so we'll // leave it null for now. this.div_ = null; // Explicitly call setMap() on this overlay this.setMap(map);
} USGSOverlay.prototype = new google.maps.OverlayView();
We can't yet attach this overlay to the map in the overlay's constructor. In specific, we need to ensure that all of the map's panes (which specify in what order objects are displayed on a map) are available. Conveniently, the API provides a helper method indicating this has occurred. We'll handle that method in the next section.
Initializing an Overlay When the overlay is first instantiated and ready to display, we'll need to attach it to the map via the browser's DOM. The API indicates that the overlay has been added to the map by invoking the overlay's onAdd() method. We'll handle this method by creating a to hold our image, add an element, attach it to the , and then finally attach the overlay to one of the map's panes, which are nodes within the DOM tree. The set of panes, of type MapPanes, specify the stacking order for different layers on the map. The following panes are possible, and enumerated in the order in which they are stacked from bottom to top: •
MapPanes.mapPane
•
MapPanes.overlayLayer
•
MapPanes.overlayShadow
•
MapPanes.overlayImage
•
MapPanes.floatShadow
•
MapPanes.overlayMouseTarget
•
MapPanes.floatPane
Because our image is a "ground overlay," we'll use the overlayLayer map pane. Once we have that pane, we'll attach our object to it as a child. USGSOverlay.prototype.onAdd = function() { // Note: an overlay's receipt of onAdd() indicates that // the map's panes are now available for attaching // the overlay to the map via the DOM. // Create the DIV and set some basic attributes. var div = document.createElement('DIV'); div.style.border = "none"; div.style.borderWidth = "0px"; div.style.position = "absolute"; // Create an IMG element and attach it to the DIV. var img = document.createElement("img"); img.src = this.image_; img.style.width = "100%"; img.style.height = "100%"; div.appendChild(img); // Set the overlay's div_ property to this DIV this.div_ = div; // We add an overlay to a map via one of the map's panes.
}
// We'll add this overlay to the overlayImage pane. var panes = this.getPanes(); panes.overlayLayer.appendChild(div);
Drawing an Overlay Note that we haven't actually invoked any special visual display above. The API invokes a separate draw() method on the overlay whenever it needs to draw the overlay on the map (including when first added). We'll therefore implement this draw() method, retrieve the overlay's MapCanvasProjection using getProjection()and calculate the exact coordinates at which to anchor the object's top right and bottom left points, from which we'll resize the ; in turn this will resize the image to match the bounds we specified in the overlay's constructor. USGSOverlay.prototype.draw = function() { // Size and position the overlay. We use a southwest and northeast // position of the overlay to peg it to the correct position and size. // We need to retrieve the projection from this overlay to do this. var overlayProjection = this.getProjection(); // Retrieve the southwest and northeast coordinates of this overlay // in latlngs and convert them to pixels coordinates. // We'll use these coordinates to resize the DIV. var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest()); var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast()); // Resize the image's DIV to fit the indicated dimensions. var div = this.div_; div.style.left = sw.x + 'px'; div.style.top = ne.y + 'px'; div.style.width = (ne.x - sw.x) + 'px'; div.style.height = (sw.y - ne.y) + 'px'; }
Removing an Overlay We'll also add an onRemove() method to cleanly remove the overlay from the map. This method will be called automatically from the API if we ever set the overlay's map property to null. USGSOverlay.prototype.onRemove = function() { this.div_.parentNode.removeChild(this.div_); this.div_ = null; }
Hiding and Showing an Overlay If you wish to hide or show an overlay rather than simply create or remove the overlay, you can implement your own hide() and show() methods to adjust the overlay's visibility. Alternatively, you may detach the overlay from the map's DOM, though this operation is slightly more expensive. Note that if you then reattach the overlay to the map's DOM, it will re-invoke the overlay's onAdd() method.
The following example adds hide() and show() methods to the overlay's prototype which toggle the container 's visibility. Additionally, we add a toogleDOM() method, which attaches or detaches the overlay to the map. Note that if we set the visibility to "hidden" and then detach the map from the DOM via toggleDOM(), if we later reattach the map, it will be visible again, since the containing is recreated in the overlay's onAdd() method. // Note that the visibility property must be a string enclosed in quotes USGSOverlay.prototype.hide = function() { if (this.div_) { this.div_.style.visibility = "hidden"; } } USGSOverlay.prototype.show = function() { if (this.div_) { this.div_.style.visibility = "visible"; } } USGSOverlay.prototype.toggle = function() { if (this.div_) { if (this.div_.style.visibility == "hidden") { this.show(); } else { this.hide(); } } } USGSOverlay.prototype.toggleDOM = function() { if (this.getMap()) { this.setMap(null); } else { this.setMap(this.map_); } } // Now we add an input button to initiate the toggle method // on the specific overlay