Search Google Code

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.

Geocoding via HTTP

To access the Maps API geocoder directly using server-side scripting, send a request to http://maps.google.com/maps/geo? with the following parameters in the URI:

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

The Geocoding Object

You can also access the Google Maps API geocoder 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:

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)

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.

// 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 = new GGeoXml("http://mapgadgets.googlepages.com/cta.kml");

function onLoad() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas")); 
    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:

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)