English | Site Directory

Google Maps API

Google Maps API Premier

Same great maps plus a SLA, support, and control over ads

Services

Services Overview

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.

XML and Data Parsing

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

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.

Note that geocoding is a time and resource intensive task. Whenever possible, pre-geocode your addresses (using the HTTP geocoder or other geocoding service), and store your results using a Geocoding Cache.

The Geocoding Object

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

Extracting Structured Addresses

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:

  • Status
    • request -- 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)

Geocoding Caches

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)

Geocoding via HTTP

You may also access the Maps API geocoder directly using server-side scripting. This method is not recommended over using the client-side geocoder; however, it is useful for debugging purposes or for cases where a JavaScript GClientGeocoder object is not available.

To access the Maps API Geocoder, send a request to http://maps.google.com/maps/geo? with the following parameters in the URI:

  • q (required) -- The address that you want to geocode.
  • key (required) -- Your API key.
  • output (required) -- The format in which the output should be generated. The options are xml, kml, csv, or (default) json.
  • ll (optional)-- The {latitude,longitude} of the viewport center expressed as a comma-separated string (e.g. "ll=40.479581%2C-117.773438" ). This parameter only has meaning if the spn parameter is also passed to the geocoder.
  • spn (optional)-- The "span" of the viewport expressed as a comma-separated string of {latitude,longitude} (e.g. "spn11.1873%2C22.5" ). This parameter only has meaning if the ll parameter is also passed to the geocoder.<
  • gl (optional) -- The country code, specified as a ccTLD ("top-level domain") two-character value.

In this example, we request the geographic coordinates of Google's headquarters:

http://maps.google.com/maps/geo?q=1600+Amphitheatre+Parkway,+Mountain+View,+CA&output=xml&key=abcdefg

If you specify json as the output, the response is formatted as a JSON object. If you specify xml or kml, the response is returned in KML. The XML and KML outputs are identical except for the MIME types.

For example, this is the response that the geocoder returns for "1600 amphitheatre mountain view ca".

<kml xmlns="http://earth.google.com/kml/2.0">
  <Response>
    <name>1600 amphitheatre mountain view ca</name>
    <Status>
      <code>200</code>
      <request>geocode</request>
    </Status>
    <Placemark>
      <address> 
        1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA
      </address>
      <AddressDetails Accuracy="8">
        <Country>
          <CountryNameCode>US</CountryNameCode>
 	  <AdministrativeArea>
            <AdministrativeAreaName>CA</AdministrativeAreaName>
           <SubAdministrativeArea>
             <SubAdministrativeAreaName>Santa Clara</SubAdministrativeAreaName>
             <Locality>
               <LocalityName>Mountain View</LocalityName>
    	       <Thoroughfare>
                 <ThoroughfareName>1600 Amphitheatre Pkwy</ThoroughfareName>
               </Thoroughfare>
               <PostalCode>
                 <PostalCodeNumber>94043</PostalCodeNumber>
               </PostalCode>
             </Locality>
           </SubAdministrativeArea>
         </AdministrativeArea>
       </Country>
     </AddressDetails>
     <Point>
       <coordinates>-122.083739,37.423021,0</coordinates>
     </Point>
   </Placemark>
  </Response>
</kml>

If you prefer a shorter response that is easier to parse and don't need special features like multiple results or pretty formatting, we also provide a csv output. A reply returned in the csv format consists of four numbers, separated by commas:

  1. HTTP status code
  2. accuracy (See accuracy constants)
  3. latitude
  4. longitude

The following examples shows replies for three addresses, in increasing order of accuracy: "State St, Troy, NY", "2nd st & State St, Troy, NY" and "7 State St, Troy, NY"

200,6,42.730070,-73.690570
200,7,42.730210,-73.691800
200,8,42.730287,-73.692511

Using Street View Objects

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!

The GStreetviewPanorama Object

Street 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:

  1. Create a container (usually a <div> element) to hold the Street View Flash® viewer.
  2. Create a GStreetviewPanorama object and place it within the container.
  3. Initialize the Street View object to refer to a specific location and display an initial "point of view" (POV).
  4. Handle unsupported browsers by checking for the FLASH_UNAVAILABLE 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.

More information on containers and setting locations and points of view is described below.

Street View Containers

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 if you wish to remove the container element from the DOM; not doing so will result in memory leaks on the client's browser.

Street View Locations

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:

  • You can store the GLatLng of a known-valid Street View location.
  • You can examine the 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.)
  • You can use the 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)

Street View Error Handling

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 == FLASH_UNAVAILABLE) {
    alert("Error: Flash doesn't appear to be supported by your browser");
    return;
  }
}  

Street View Points of View (POV)

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.

Setting the Panorama 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)

Using the Street View Overlay

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.

Street View Client Querying

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.

Performing Street View Lookups

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.

Handling Client Responses

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)

Local Search

If you would like to add local search capabilities to your site, you can use the Google AJAX Search API to embed a local search control into your site. This control is a subclass of the GControl object and is a good example of creating a custom control.

Before adding this control to your Maps API application, you need to add the Google AJAX Search API URL, and use your maps API key for that service. You also need to load the stylesheets for that control object as well, as shown below:

// Load the Code
<script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=ABCDEF"
      type="text/javascript"></script>
<script src="http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js" 
      type="text/javascript"></script>

// Load the Style Sheets
<style type="text/css">
  @import url("http://www.google.com/uds/css/gsearch.css");
  @import url("http://www.google.com/uds/solutions/localsearch/gmlocalsearch.css");
</style>

Alternatively, you could use the AJAX Loader to load all of these modules via the common loader.

Once you have performed these preparatory tasks, loading the control itself is relatively straightforward:

// create your map
var map = new GMap2(document.getElementById("map_canvas"));

// create a local search control and add it to your map
var lsc = new google.maps.LocalSearch(); 
map.addControl(new google.maps.LocalSearch());

View example (control-localsearch.html)

More information about the Local Search Control is located on the Google AJAX Search API Reference

KML/GeoRSS Overlays

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)

Traffic Overlays

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.

// 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 = new GTrafficOverlay();

function initialize() {
  map = new GMap2(document.getElementById("map_canvas")); 
  map.setCenter(new GLatLng(49.496675,-102.65625), 3); 
  map.addOverlay(trafficInfo);
} 

View Traffic example (trafficOverlay.html)

Driving Directions

You can add driving directions using the Google Maps API by using the GDirections object. The GDirections objects 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 driving directions using a series of points. 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).

Driving directions are requested using the GDirections.load() method. This method takes a query string and a set of optional GDirectionsOptions parameters. 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, the GDirections object will 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().

// 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("New York, NY to Chicago, IL");
}

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.

The GDirections object 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.

For full documentation of the various objects, methods and events in the Directions API package, consult the API Reference.

View example (directions-simple.html)

View example (directions-advanced.html)