Same great maps plus a SLA, support, and control over ads
The Google Maps API is regularly extended, adding new functionality and features that are often released on maps.google.com first. This section covers these services. Note: because the definition of a "service" is somewhat elusive, this section is somewhat of a catch-all. Basically, this section is where we put all of those neat things that we couldn't put anywhere else.
The Google Maps API exports a factory method for creating browser-neutral
XmlHttpRequest() objects that work in recent versions
of Internet Explorer, Firefox, and Safari. As with all XmlHttpRequests,
any retrieved files must be on your local domain. The following example
downloads a file called myfile.txt and displays its contents in a
JavaScript alert():
var request = GXmlHttp.create();
request.open("GET", "myfile.txt", true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
alert(request.responseText);
}
}
request.send(null);
The API also exports a simpler GDownloadUrl() method
for typical HTTP GET requests that eliminates the need for
XmlHttpRequest() readyState checking.
The example above could be rewritten using GDownloadUrl()
like this:
GDownloadUrl("myfile.txt", function(data, responseCode) {
alert(data);
});
You can parse an XML document with the static method
GXml.parse(), which takes a string of XML as its
only argument. This method is compatible with most modern browsers,
but it throws an exception if the browser does not support XML parsing
natively.
In this example, we download a static file ("data.xml")
that contains a list of lat/lng coordinates in XML using the
GDownloadUrl method. When
the download completes, we parse the XML with
GXml and create a marker at each of those points in the XML document.
var map = new GMap2(document.getElementById("map_canvas"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
// Download the data in data.xml and load it on the map. The format we
// expect is:
// <markers>
// <marker lat="37.441" lng="-122.141"/>
// <marker lat="37.322" lng="-121.213"/>
// </markers>
GDownloadUrl("data.xml", function(data, responseCode) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
map.addOverlay(new GMarker(point));
}
});
View example (xhr-requests.html). This example uses an external XML data file data.xml.
See the GXmlHttp
and GXml class
references for more information.
Geocoding is the process of converting addresses (like "1600 Amphitheatre
Parkway, Mountain View, CA") into geographic coordinates (like latitude
37.423021 and longitude -122.083739), which you can use to place markers or
position the map. The Google Maps API includes a Geocoding service that
can be accessed directly via an HTTP request or by using a GClientGeocoder
object.
The Google Maps API provides a client geocoder for geocoding addresses dynamically from user input. If instead, you wish to geocode static, known addresses, see the Geocoding Service documentation.
You can access the Google Maps API geocoding service via the GClientGeocoder
object. Use GClientGeocoder.getLatLng() to convert a string address into
a GLatLng. This method takes as parameters a string address to convert,
and a callback function to execute upon retrieval of the address. The callback function is
necessary since geocoding involves sending a request to Google's servers and
can take some time.
In this example, we geocode an address, add a marker at that point, and open an info window displaying the address. Note that the callback is passed as a function literal.
var map = new GMap2(document.getElementById("map_canvas"));
var geocoder = new GClientGeocoder();
function showAddress(address) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml(address);
}
}
);
}
View example (geocoding-simple.html)
You can also modify the Maps API geocoder to prefer results within a given
viewport (expressed as a bounding box of type GLatLngBounds)
through the GClientGeocoder.setViewport() method. You can
return results tailored to a particular domain (country) using the
GClientGeocoder.setBaseCountryCode() method. Geocoding requests
can be sent for every domain in which the main Google Maps application
offers geocoding. For example, searches for "Toledo" will return different
results within the domain of Spain (http://maps.google.es) specified by a country code of "es"
than within the default domain within the United States (http://maps.google.com).
If you would like to access structured information about an address,
GClientGeocoder also provides a getLocations()
method that returns a JSON object consisting of the following information:
Statusrequest -- The request type. In this case, it is always
geocode.code -- A response code (similar to HTTP status codes)
indicating whether the geocode request was successful or not.
See the full list of status codes.Placemark -- Multiple placemarks may be returned
if the geocoder finds multiple matches.address -- A nicely formatted and properly capitalized version of the address.AddressDetails -- The address formatted as xAL, or
eXtensible
Address Language, an international standard for address formatting.Accuracy -- An attribute indicating how accurately we
were able to geocode the given address. See a
list of possible values.Point -- A point in 3D space.coordinates -- The longitude, latitude, and
altitude of the address. In this case, the altitude is always set to 0.Here we show the JSON object returned by the geocoder for the address of Google's headquarters:
{
"name": "1600 Amphitheatre Parkway, Mountain View, CA, USA",
"Status": {
"code": 200,
"request": "geocode"
},
"Placemark": [
{
"address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"AddressDetails": {
"Country": {
"CountryNameCode": "US",
"AdministrativeArea": {
"AdministrativeAreaName": "CA",
"SubAdministrativeArea": {
"SubAdministrativeAreaName": "Santa Clara",
"Locality": {
"LocalityName": "Mountain View",
"Thoroughfare": {
"ThoroughfareName": "1600 Amphitheatre Pkwy"
},
"PostalCode": {
"PostalCodeNumber": "94043"
}
}
}
}
},
"Accuracy": 8
},
"Point": {
"coordinates": [-122.083739, 37.423021, 0]
}
}
]
}
In this example, we use the getLocations() method to geocode
addresses, and extract the nicely formatted version of the address and the
two-letter country from the JSON and display it in the info window.
var map;
var geocoder;
function addAddressToMap(response) {
map.clearOverlays();
if (!response || response.Status.code != 200) {
alert("\"" + address + "\" not found");
} else {
place = response.Placemark[0];
point = new GLatLng(place.Point.coordinates[1],
place.Point.coordinates[0]);
marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml(place.address + '<br>' +
'<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
}
}
View example (geocoding-extraction.html)
The term geocoding generally refers to translating a human-readable address into a point on the map. The process of doing the converse, translating a point into a human-readable address, is known as reverse geocoding.
The GClientGeocoder.getLocations() method supports both standard
and reverse geocoding. If you pass this method a GLatLng object
instead of a String address, the geocoder will perform a reverse lookup
and return a structured JSON object of the closest addressable location. Note
that the closest addressable location may be some distance from the original
latitude and longitude values of the query, if the supplied GLatLng
is not an exact match for any addressable locations.
Note: reverse geocoding is not an exact
science. The geocoder will attempt to find the closest addressable location
within a certain tolerance; if no match is found, the geocoder will usually
return a G_GEO_UNKNOWN_ADDRESS (602) status code.
var map;
var geocoder;
var address;
function initialize() {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(40.730885,-73.997383), 15);
map.addControl(new GLargeMapControl);
GEvent.addListener(map, "click", getAddress);
geocoder = new GClientGeocoder();
}
function getAddress(overlay, latlng) {
if (latlng != null) {
address = latlng;
geocoder.getLocations(latlng, showAddress);
}
}
function showAddress(response) {
map.clearOverlays();
if (!response || response.Status.code != 200) {
alert("Status Code:" + response.Status.code);
} else {
place = response.Placemark[0];
point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml(
'<b>orig latlng:</b>' + response.name + '<br/>' +
'<b>latlng:</b>' + place.Point.coordinates[1] + "," + place.Point.coordinates[0] + '<br>' +
'<b>Status Code:</b>' + response.Status.code + '<br>' +
'<b>Status Request:</b>' + response.Status.request + '<br>' +
'<b>Address:</b>' + place.address + '<br>' +
'<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
'<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
}
}
View example (geocoding-reverse.html)
GClientGeocoder is equipped with a client-side cache by
default. The cache stores geocoder responses, enabling faster responses
if addresses are re-geocoded. You can turn off caching by passing null
to the setCache() method of the GClientGeocoder
object. However, we recommend that you leave caching on as it improves
performance. To change the cache being used by GClientGeocoder,
call setCache() and pass in the new cache. To
empty the contents of the current cache, call the reset()
method on the geocoder or on the cache directly.
Developers are encouraged to build their own client-side caches.
In this example, we construct a cache that contains pre-computed geocoder
responses to six capital cities in countries covered by geocoding API.
First, we build an array of geocode responses. Next, we create a custom
cache that extends a standard GeocodeCache. Once the cache is defined,
we call the setCache() method. There is no strict checking
of objects stored in the cache, so you may store other information
(such as population size) in the cache as well.
// Builds an array of geocode responses for the 6 capitals
var city = [
{
name: "Washington, DC",
Status: {
code: 200,
request: "geocode"
},
Placemark: [
{
address: "Washington, DC, USA",
population: "0.563M",
AddressDetails: {
Country: {
CountryNameCode: "US",
AdministrativeArea: {
AdministrativeAreaName: "DC",
Locality: {
LocalityName: "Washington"
}
}
},
Accuracy: 4
},
Point: {
coordinates: [-77.036667, 38.895000, 0]
}
}
]
},
... // etc., and so on for other cities
];
var map;
var geocoder;
// CapitalCitiesCache is a custom cache that extends the standard GeocodeCache.
// We call apply(this) to invoke the parent's class constructor.
function CapitalCitiesCache() {
GGeocodeCache.apply(this);
}
// Assigns an instance of the parent class as a prototype of the
// child class, to make sure that all methods defined on the parent
// class can be directly invoked on the child class.
CapitalCitiesCache.prototype = new GGeocodeCache();
// Override the reset method to populate the empty cache with
// information from our array of geocode responses for capitals.
CapitalCitiesCache.prototype.reset = function() {
GGeocodeCache.prototype.reset.call(this);
for (var i in city) {
this.put(city[i].name, city[i]);
}
}
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(37.441944, -122.141944), 6);
// Here we set the cache to use the UsCitiesCache custom cache.
geocoder = new GClientGeocoder();
geocoder.setCache(new CapitalCitiesCache());
View example (geocoding-cache.html)
Google provides a direct geocoding service via HTTP as well. This geocoding service
is distinct from the JavaScript Google Maps API. Using the HTTP service is not recommended
for dynamic or live retrieval of geocoding requests; instead use the JavaScript client-side
geocoder documented within this chapter. However, the HTTP geocoder is useful for populating
a static set of data, for debugging purposes, or for cases where a JavaScript
GClientGeocoder object is not available.
See the HTTP Geocoding Service for more information.
Use of the Street View Panorama object requires support for the Flash plugin on the client's browser.
Google Street View provides panoramic 360 degree views from designated roads throughout the coverage area for Google Maps. A sample Street View image is shown below.
Google Street View uses the Flash® plugin supported on most browsers to display these interactive images. The Google Maps API now provides a Street View service for obtaining and manipulating the imagery used in Google Maps Street View!
GStreetviewPanorama ObjectStreet View images are supported through use of the GStreetviewPanorama object, which
provides an API interface to a Street View Flash® viewer. To incorporate Street View into your
Maps API application, you will need to follow these simple steps:
<div> element) to hold
the Street View Flash® viewer.GStreetviewPanorama object and place it within the container.603 error value.The GStreetviewPanorama object requires a container element within its
constructor. It also, optionally, allows you to set its location using the
GStreetviewPanoramaOptions parameter. You may call
setLocationAndPOV() on the object after construction to change its location
and POV.
Note: although Street View functionality is designed to be used in conjunction with a map, this usage is not required. You may use a standalone Street View object without a map.
More information on containers and setting locations and points of view is described below.
The Street View Flash viewer requires a container DOM node in which to
display its content, often a <div> element. For optimum display of
Panorama images, we recommend a minimum size of 200 pixels by 200 pixels. Large viewers
are also discouraged as they may cause the flash viewer to consume too much memory
and could adversely affect the performance of the browser.
The GStreetviewPanorama constructor requires a container
parameter identifying the initial container element within which to display the
Street View Flash viewer. You may hide() the GStreetviewPanorama
object to temporarily disable its display or show() the object to
reenable visual display of the viewer.
If at any time you wish to change the container for the Street View Flash viewer,
send it a setContainer() method, passing it the new element within which
it should be attached. If the container is resized, you can send the
GStreetviewPanorama object a checkResize() method to force
it to resize to fit its new dimensions.
If you wish to remove the Street View Flash viewer entirely from the DOM and release its
memory, pass the object the remove() method. You must call this method
before removing the Street View object's container element from the DOM; not doing so will
result in memory leaks and/or JavaScript errors on the client's browser.
A Street View image consists of both a location (corresponding to a
GLatLng) and a particular orientation (a GPov) which
together identify the view for the image display. Both of these parameters
can be specified upon construction of the Street View object using the optional
GStreetviewPanoramaOptions parameter.
The list of currently supported cities for Street View is available at the Google Maps Help Center. There are three basic ways to determine if a location supports Street View data:
GLatLng of a known-valid Street View location.GStreetviewOverlay tile overlay and visually
inspect the road network. Roads which support Street View are highlighted in blue on the
overlay. You can then use click events or geocoding logic to pass supported locations
to GStreetviewPanorama objects. (See
Street View Overlays.)GStreetviewClient object to perform queries for
Street View objects given passed GLatLngs. The GStreetviewClient
object supports a number of queries to find panorama data. (See
Street View Client Querying.)Note that the last two methods are inexact: the Street View service does not require
(and generally does not receive) exact latitudes and longitudes in these cases, but rather
searches for the existence of panorama data "near" a given GLatLng.
The following example uses a GStreetviewPanoramaOptions to specify the initial
latitude and longitude to use for the Street View. The POV is left blank, indicating a default
view to the north.
var fenwayPark = new GLatLng(42.345573,-71.098326);
panoramaOptions = { latlng:fenwayPark };
var myPano = new GStreetviewPanorama(document.getElementById("pano"), panoramaOptions);
View example (streetview-simple.html)
As Street View requires support for the Flash® plugin, your code should check whether
that plugin is available for use within the user's browser. You can do so within your
application by registering an event listener for the error event on the
GStreetviewPanorama object. The error event passes an
error code which you can evaluate.
The sample code below performs a quick check for support of the Flash plugin and brings up an alert dialog box if Flash is not supported.
var fenwayPark = new GLatLng(42.345573,-71.098326);
panoramaOptions = { latlng:fenwayPark };
myPano = new GStreetviewPanorama(document.getElementById("pano"), panoramaOptions);
GEvent.addListener(myPano, "error", handleNoFlash);
function handleNoFlash(errorCode) {
if (errorCode == 603) {
alert("Error: Flash doesn't appear to be supported by your browser");
return;
}
}
The Street View location defines the placement of the camera locus for an image, but
it does not define the orientation of the camera for that image. For that purpose, the
GPov object literal defines three properties:
yaw defines the rotation angle around the camera locus in
degrees relative from true north. Yaw angles are measured clockwise (90 degrees is
true east).pitch defines the angle variance "up" or "down" from the camera's
initial default pitch, which is often (but not always) flat horizontal. (For example,
an image taken on a hill will likely exhibit a default pitch that is not horizontal.)
Pitch angles are measured with negative values looking up (to -90 degrees straight up and
orthogonal to the default pitch) and positive values looking down (to +90 degrees straight down
and orthogonal to the default pitch).zoom defines the zoom level of this view (effectively proscribing the
"field of view") with 0 being fully zoomed-out. Different Street View locations may provide higher or lower zoom levels.By default, these values are all 0 and define a flat horizontal view directly north with the widest possible field of view.
As described earlier, you may set both the location and GPov for a
panorama object upon its construction using the GStreetviewPanoramaOptions parameter.
fenwayPark = new GLatLng(42.345573,-71.098326);
myPOV = {yaw:370.64659986187695,pitch:-20};
svOpts = {latlng:fenwayPark, pov:myPOV};
var myPano = new GStreetviewPanorama(document.getElementById("pano"), svOpts);
You may also set both the location and POV using the setLocationAndPOV()
method after construction of the GStreetviewPanorama object. In the
following example, we create a GStreetviewPanorama object, and then
set its location and POV to a specific value.
var myPano = new GStreetviewPanorama(document.getElementById("pano"));
fenwayPark = new GLatLng(42.345573,-71.098326);
myPOV = {yaw:370.64659986187695,pitch:-20};
myPano.setLocationAndPOV(fenwayPark, myPOV);
View example (streetview-object.html)
The simplest way to determine if a road supports Street View is through the GStreetviewOverlay
object. Simply create an overlay of this type and add it to the map; roads which contain Street View data will
show up highlighted on the map using blue outlines.
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
svOverlay = new GStreetviewOverlay();
map.addOverlay(svOverlay);
View example (streetview-layer.html)
Once you know that a geographic area supports Street View, you can add logic which responds to
clicks on valid Street View roads by populating the GStreetviewPanorama object.
var myPano = new GStreetviewPanorama(document.getElementById("pano"));
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(42.345573,-71.098326), 14);
svOverlay = new GStreetviewOverlay();
map.addOverlay(svOverlay);
GEvent.addListener(map,"click", function(overlay,latlng) {
myPano.setLocationAndPOV(latlng);
});
View example (streetview-click.html)
If you know that a particular location supports Street View, you can save the location information and POV and place that information within the object itself.
Determining whether a road supports Street View by visual inspection of the
GStreetviewOverlay is not often feasible, or desirable from a user's
perspective. For that reason, the API provides a service which programmatically
requests and retrieves Street View data. This service is facilitated through use
of the GStreetviewClient object.
The GStreetviewClient object performs Panorama data lookups using
Google's Street View service. Because this lookup is asynchronous, the methods of this
class require callback functions to execute upon receipt of the data. All of the given
callbacks pass null if no value is returned, so you should check
for that case within your callback functions.
The GStreetviewClient method getNearestPanoramaLatLng()
retrieves the GLatLng of a nearby Panorama image from a given
location (itself passed as a GLatLng).
Both getNearestPanorama() and getPanoramaById() instead
retrieve GStreetviewData objects, which store metadata about the particular
Panorama object. That data is described in the section below.
The structure of a GStreetviewData object consists of three properties:
location and copyright (which contain information about the
specific image being shown), and links (which provides information about
adjacent Panorama objects). The structure of these properties is described below:
# The location property uses the GStreetviewLocation object literal
location: {
latlng: GLatLng,
pov: {
yaw: String,
pitch: String,
zoom: String
},
description: String,
panoId: String
}
copyright: String
# The links property uses the GStreetviewLink object literal
links[]: {
yaw: String,
description: String,
panoId: String
}
(Full descriptions of the GStreetviewLocation and GStreetviewLink
object literals are shown in the Maps API Reference.)
Note: the GStreetviewData.location property
should not be confused with the window.location property. If you are
trying to extract data from this object's location property, ensure
that you have actually received a response back from the Street View server (see below).
Otherwise, the location property will default to window.location
and you will get unexpected behavior.
If a request to a GStreetviewClient object is successful, it will pass
either a GLatLng or a GStreetviewData object to the specified
callback function. Because retrieving Street View data is asynchronous, however, the
client object may not retrieve these data objects, so your code should not depend on them
being present. Instead, you should always check the code value returned from
any request, which is guaranteed to be returned. The code snippet below illustrates this
concept.
panoClient = new GStreetviewClient();
panoClient.getPanoramaById(panoData.location.panoId, processReturnedData);
function processReturnedData(panoData) {
if (panoData.code != 200) {
GLog.write('showPanoData: Server rejected with code: ' + panoData.code);
return;
}
// Code to actually process the GStreetviewData object is contained here
}
A full response containing a sample GStreetviewData structure is shown below:
{
location: {
latlng: GLatLng("42.345566, -71.098354")
pov: {
yaw: "370.64659986187695"
pitch: "-20"
zoom: "1"
}
description: "Yawkey Way"
panoId: "-KNGDaZvSQjMqug7ISM_CA"
}
copyright: "© 2008 Google"
links:[ {
yaw: "0"
description: "Yawkey Way"
panoId: "S142iWXa_4Fi7L7d8HKhuQ"
},
{
yaw: "0"
description: "Yawkey Way"
panoId: "2vFI79AjOpHTAYJSCKquFg"
}
]
}
The sample application below displays an initial Panorama object, extracts its ID, and stores
the linked Panorama object in the returned GStreetviewData object, and displays the
data set associated with that Street View object. Each time the user clicks "Next," the process
repeats, allowing a user to "walk" through a set of adjacent Panorama objects.
var map;
var myPano;
var panoClient;
var nextPanoId;
function initialize() {
var fenwayPark = new GLatLng(42.345573,-71.098326);
var fenwayPOV = {yaw:370.64659986187695,pitch:-20};
panoClient = new GStreetviewClient();
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(fenwayPark, 15);
GEvent.addListener(map, "click", function(overlay,latlng) {
panoClient.getNearestPanorama(latlng, showPanoData);
});
myPano = new GStreetviewPanorama(document.getElementById("pano"));
myPano.setLocationAndPOV(fenwayPark, fenwayPOV);
GEvent.addListener(myPano, "error", handleNoFlash);
panoClient.getNearestPanorama(fenwayPark, showPanoData);
}
function showPanoData(panoData) {
if (panoData.code != 200) {
GLog.write('showPanoData: Server rejected with code: ' + panoData.code);
return;
}
nextPanoId = panoData.links[[0[].panoId;
var displayString = [[
"Panorama ID: " + panoData.location.panoId,
"LatLng: " + panoData.location.latlng,
"Copyright: " + panoData.copyright,
"Description: " + panoData.location.description,
"Next Pano ID: " + panoData.links[[0[].panoId
[].join("
");
map.openInfoWindowHtml(panoData.location.latlng, displayString);
GLog.write('Viewer moved to' + panoData.location.latlng);
myPano.setLocationAndPOV(panoData.location.latlng);
}
function next() {
// Get the next panoId
// Note that this is not sophisticated. At the end of the block, it will get stuck
panoClient.getPanoramaById(nextPanoId, showPanoData);
}
function handleNoFlash(errorCode) {
if (errorCode == 603) {
alert("Error: Flash doesn't appear to be supported by your browser");
return;
}
}
View example (streetview-data.html)
The Google Maps API allows developers to manipulate an instance of the Google Earth Plugin
within their Maps API applications. The Google Earth map layer is loaded using a separate
GMapType that looks and behaves like the standalone Google Earth application,
allowing you to rotate perspectives, see elevations, and view Google Earth KML information
within the browser.
Note: the Google Earth Plugin must be installed on the user's
computer to use this Google Earth GMapType. Currently, this plugin is available for Microsoft Windows and Apple Mac OS X. For full system requirements, see the
Google Earth API Developer's Guide.
The Google Earth Plugin can also be controlled through its own API, which is separate and distinct from the Google Maps API. Consult the Google Earth API Developer's Guide for full information on using the plugin and using the Google Earth API.
To install the plugin, visit the Google Earth API intallation instructions, or browse to any web site using the Google Earth Plugin. In your application, end users who do not have the plugin installed will be presented with a download link when switching to the Google Earth GMapType. Upon successful installation, the Google Earth Plugin will be loaded automatically (or upon page reload in some browsers).
To add the Google Earth instance to your map, simply add the G_SATELLITE_3D_MAP
to your map with GMap2.addMapType(). You can then either display
this map type directly via GMap2.setMapType() or allow the user to select it
within a GMapTypeControl by adding a map type control via
GMap2.addControl().
The following code adds the G_SATELLITE_3D_MAP map type
and then explicitly loads Google Earth within the map container.
var map = new GMap2(document.getElementById("map_canvas"),{ size: new GSize(640,480) } );
map.setCenter(new GLatLng(42.366662,-71.106262), 11);
// Enable the Earth map type
map.addMapType(G_SATELLITE_3D_MAP);
var mapControl = new GMapTypeControl();
map.addControl(mapControl);
map.setMapType(G_SATELLITE_3D_MAP);
View example (services-earth-plugin.html)
It is also possible to access Google Earth API objects from the Maps API. To access the root GEPlugin object of the 3D map type, call GMap2.getEarthInstance:
map.getEarthInstance(function(ge) {
// Direct Earth API calls can go here
ge.getLayerRoot().enableLayerById(
ge.LAYER_BORDERS, true); // Turn on borders and labels
});
To give your users the ability to search for local businesses, you can use the GoogleBar to embed a local search control into your site. The GoogleBar has been updated with a new UI and has also added advertising results which can be configured to earn revenue for your API site.
To use the GoogleBar, you first need to specify its behavior
using the GGoogleBarOptions object, which you pass to the
GMap2 constructor. Once the map is constructed, you enable
the GoogleBar by calling GMap2.enableGoogleBar(). The GoogleBar
has been revamped to have a new look and feel and add
advertising revenue streams to Maps API sites.
Note: because the redesigned GoogleBar
behaves differently than its previous version, we've provided
its new user interface as an "opt-in" setting. To enable the new GoogleBar,
set the style property to "new" within the
GGoogleBarOptions object. In the near future, we will enable
this behavior by default.
The following example sets up a GoogleBar with the new look and feel:
var map;
if (GBrowserIsCompatible()) {
var mapOptions = {
googleBarOptions : {
style : "new",
}
}
map = new GMap2(document.getElementById("map_canvas"), mapOptions);
map.setCenter(new GLatLng(33.956461,-118.396225), 13);
map.setUIToDefault();
map.enableGoogleBar();
}
View example (control-googlebar.html)
Note that results from this control will contain advertising. If you want to collect revenue from advertising search results from the GoogleBar, see Gaining Advertising Revenue below.
Google now provides several AdSense for Maps products to monetize your Google Maps API application:
GoogleBarTo gain revenue from this advertising, you link these AdSense for Maps objects to an AdSense account which has been enabled with AdSense for Search or AdSense for Content, respectively.
These methods of advertising are fundamentally different and require
different Google AdSense products. Displaying ads in the GoogleBar
responds to direct user searches, so your AdSense account should be enabled
for AdSense for Search. Displaying ads in a panel on the map based on a viewer's
viewport requires that your AdSense account be enabled for AdSense for Content.
If you don't yet have an AdSense account, sign up for an account. Once you have done so (or if you already have an account) make sure you've also enabled the account with AdSense for Search and/or AdSense for Content.
Once you have an Adsense for Search or AdSense for Content account, you will have received an AdSense for Search (AFS) or AdSense for Content (AFC) publisher ID. This publisher ID is used within your code to link any advertising shown to your AdSense account.
GoogleBarTo begin gaining advertising revenue from user searches using the GoogleBar,
specify your publisher ID within the client property of the
GGoogleBarAdsOptions object when constructing your map. You will begin
receiving advertising revenue for any clicks on local results within your API
application. Optionally, you may also specify an AdSense for Search channel
if you've set that up. (More information on advertising channels is located
here.)
Additionally, you may also specify the adsafe (Ad Safety Level)
to associate with your advertising and the language in which
to display results.
The following sample shows a GoogleBar set up to receive advertising revenue. Note that you should use your own publisher ID in your application.
var map;
if (GBrowserIsCompatible()) {
var mapOptions = {
googleBarOptions : {
style : "new",
adsOptions: {
client: "partner-google-maps-api",
channel: "AdSense for Search channel",
adsafe: "high",
language: "en"
}
}
}
map = new GMap2(document.getElementById("map_canvas"), mapOptions);
map.setCenter(new GLatLng(33.956461,-118.396225), 13);
map.setUIToDefault();
map.enableGoogleBar();
}
View example (control-googlebar-ads.html)
For more information, see the
GGoogleBarAdsOptions
API reference.
The Maps Ad Unit is a new advertising option within the AdSense for Maps
portfolio, created by specifying an option within the GAdsManager
constructor. The Maps Ad Unit displays a small panel containing advertising
tailored to what is viewed on the map.
You enable the Maps Ad Unit by specifying an 'adunit' style within the
GAdsManagerOptions object. Make sure to also specify specify your publisher ID within
the GAdsManager constructor as well. You will begin
receiving advertising revenue for any clicks on ads within the Maps Ad Unit in your API
application. Optionally, you may also specify an AdSense for Content channel
if you've set that up. (More information on advertising channels is located
here.)
The following sample shows a GAdsManager set up to
receive advertising revenue. Note that you should use your own publisher ID
in your application.
var publisher_id = yourPublisherID;
var adsManagerOptions = {
maxAdsOnMap : 2,
style: 'adunit',
// The channel field is optional - replace this field with a channel number
// for Google AdSense tracking
channel: 'your_channel_id'
};
adsManager = new GAdsManager(map, publisher_id, adsManagerOptions);
adsManager.enable();
View example (adsmanager-adunit.html)
For more information, see the
GAdsManager
API reference.
The Google Maps API supports the KML and GeoRSS data formats for displaying
geographic information. These data formats are added to a map using the
GGeoXml object, whose constructor takes the URL of a publicly
accessible XML file. GGeoXml placemarks are rendered as GMarkers,
while GGeoXml polylines and polygons are rendered as Google Maps
API polylines and polygons. <GroundOverlay> elements within KML files are
rendered as GGroundOverlay elements on the map.
GGeoXml objects are added to a map using the addOverlay()
method. (You can remove them from the map using removeOverlay().)
Both KML and GeoRSS XML files are supported. Note that GGeoXml
is a modularized object within the Google Maps API and is not fully loaded until
it is first used. As a result, only call its constructor after the page has fully
loaded. This is usually accomplished by calling the GGeoXml constructor
within the <body>'s onload handler.
// The GGeoXml constructor takes a URL pointing to a KML or GeoRSS file.
// You add the GGeoXml object to the map as an overlay, and remove it as an overlay as well.
// The Maps API determines implicitly whether the file is a KML or GeoRSS file.
var map;
var geoXml;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
geoXml = new GGeoXml("http://mapgadgets.googlepages.com/cta.kml");
map.addControl(new GLargeMapControl());
map.setCenter(new GLatLng(41.875696,-87.624207), 11);
map.addControl(new GLargeMapControl());
map.addOverlay(geoXml);
}
}
View GeoRSS example (geoxml-rss.html)
View KML examples (geoxml-kml.html)
The Google Maps API allows you to add traffic information to your maps
using the GTrafficOverlay object, which
implements the GOverlay interface. You add traffic information to
your map using the GMap2.addOverlay() method. GTrafficOverlay
has two methods (hide() and show()) for toggling
display of the traffic overlay. Traffic information
is displayed only for supported cities.
You may optionally pass options to the GTrafficOverlay
constructor using the GTrafficOverlayOptions object literal.
// The GTrafficOverlay is unique in that only one object of that type
// should be added to a map. Adding multiple traffic overlays produces
// no added benefit.
var map;
var trafficInfo;
function initialize() {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(49.496675,-102.65625), 3);
var trafficOptions = {incidents:true};
trafficInfo = new GTrafficOverlay(trafficOptions);
map.addOverlay(trafficInfo);
}
View Traffic example (trafficOverlay.html)
You can add the ability to calculate directions (using a variety of methods of transportation)
by using the GDirections object. The GDirections
object requests and receives direction results using either
query strings (e.g. "New York, NY to Chicago, IL") or provided textual lat/lons (e.g. "40.712882,
-73.967257 to 41.943181,-87.770677"). The GDirections object also supports multi-part
directions using a series of waypoints. Directions may be displayed as either a polyline
drawing the route on a map, as a series of textual description within a <div>
element (e.g. "Turn right onto the Williamsburg Bridge ramp") or both.
To use directions in the Google Maps API, create an object of type GDirections and
designate a GMap2 object and/or <div> to receive and display results.
By default, the map is centered and bounded by the returned route(s) (though you can change this
with parameters within a GDirectionOptions object).
Directions are requested using the GDirections.load() method. This method
takes a query string and a set of optional GDirectionsOptions parameters. The
following options are available:
locale specifies the language to use for returning the results,
overriding the Maps API hl parameter,
if supplied. If neither locale nore an hl parameter is
specified, the browser's default language is used.travelMode specifies the method of transporation to use when calculating results.avoidHighways specifies that highways should be avoided when computing directions.getPolyline specifies that the directions object should return polyline data for
drawing the returned directions. By default, the GDirections object only returns
polyline data if there is a map object to display it. If you set this value true
and don't provide a map, you should handle the polyline data directly.getSteps specifies that the directions object should return textual directions,
even if no <div> panel is supplied to display these directions. If your set
this value true and don't provide a panel, you should handle the step data directly.preserveViewport specifies that the map shouldn't automatically center and zoom to
the bounding box of the returned directions; instead, the map will remain centered on the current
viewport.By default, directions are assumed to be driving directions though you may request
other modes of travel by passing a GTravelMode when calling the
Directions.load() method. The following travel modes are supported:
G_TRAVEL_MODE_DRIVING indicates standard driving directions using the road networkG_TRAVEL_MODE_WALKING requests walking directions via pedestrian paths & sidewalks
(where available.)Note: Walking directions may sometimes not include clear
pedestrian paths, so walking directions are only supported if you have supplied a
<div> in the GDirections constructor; this <div>
is used to display a warning to the user in the returned turn-by-turn textual
directions. If you do not have such a <div>, a request for walking directions
will return an error.
If the GDirections object was constructed with a supplied GMap2
object, then the returned directions will contain a polyline overlay. If the GDirections
object was constructed with a supplied <div> element, then the returned
directions will contain a GRoute object, containing a set of GStep
objects. (If the directions consist of multi-point directions, the returned directions will
contain multiple GRoute objects, each consisting of a series of GStep
objects.)
Note that the directions object is not populated with this return information immediately. For this reason,
the GDirections object defines a "load" event which you can intercept to determine this state.
Once directions are returned, by default, the map will display a polyline showing the route, while
textual directions will display within the <div> supplied for that purpose.
The GDirections object will also internally store results which you can retrieve using
GDirections.getPolyline() and/or GDirections.getRoute(i:Number)
methods. Steps within a route can be retrieved using the GRoute.getStep(i:Number)
method and the HTML summary of that step can be retrieved using GStep.getDescriptionHtml().
(See Routes and Steps below.)
The GDirections object also fires three events which you can intercept:
load": This event is triggered when a directions result successfully returns,
but before any overlay elements are added to the map/panel.addoverlay": This event is triggered after the polyline and/or
textual directions components are added to the map and/or DIV elements.error": This event is triggered if a directions request
results in an error. Callers can use GDirections.getStatus() to
get more information about the error.
// Create a directions object and register a map and DIV to hold the
// resulting computed directions
var map;
var directionsPanel;
var directions;
function initialize() {
map = new GMap2(document.getElementById("map_canvas"));
directionsPanel = document.getElementById("my_textual_div");
map.setCenter(new GLatLng(49.496675,-102.65625), 3);
directions = new GDirections(map, directionsPanel);
directions.load("from: 500 Memorial Drive, Cambridge, MA to: 4 Yawkey Way, Boston, MA 02215 (Fenway Park)");
}
View example (directions-simple.html)
The following example is identical to the first, except that the directions are called
passing a G_TRAVEL_MODE_WALKING:
View example (directions-walking.html)
The GDirections object also supports multi-point directions,
which can be constructed using the GDirections.loadFromWaypoints()
method. This method takes an array of textual input addresses or textual
lat/lon points. Each separate waypoint is computed as a separate route and returned in a separate
GRoute object, each of which contains a series of GStep objects.
GRoute objects store the number of steps (of type
GStep for that route, the starting and ending geocode
for that route, and other computed information such as distance, duration,
and exact lat/lon of the endpoint (which may be different than the ending
geocode if the geocode does not lie on a road segment). Each GStep
object as well contains the description for that text (e.g.
"Merge onto US-101 S via the ramp to San Jose") plus computed information
including the distance, duration, and exact lat/lon as well.
For full documentation of the various objects, methods and events in the Directions API package, consult the API Reference.