My favorites | English | Sign in

Google Maps JavaScript API V3 (Labs)

Maps API V3 Services

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 provides a geocoder class for geocoding addresses dynamically from user input. If instead, you wish to geocode static, known addresses, see the HTTP Geocoding Service documentation. (Note that if you wish to use the HTTP service, you will need to sign up for an API key.)

Geocoding Requests

Accessing the Geocoding service is asynchronous, since the Google Maps API needs to make a call to an external server. For that reason, you need to pass a callback method to execute upon completion of the request. This callback method processes the result(s). Note that the geocoder may return more than one result.

You access the Google Maps API geocoding service within your code via the google.maps.Geocoder object. The Geocoder.geocode() method initiates a request to the geocoding service, passing it a GeocodeRequest object literal containing the input terms and a callback method to execute upon receipt of the response.

The GeocodeRequest object literal contains the following fields:

{
 address: string,
 latLng: LatLng,
 bounds: LatLngBounds,
 language: string,
 region: string,
}

These fields are explained below.

  • address (required) — The address that you want to geocode.*
  • latLng (required*) — The LatLng for which you wish to obtain the closest, human-readable address.
  • bounds (optional) — The LatLngBounds within which to bias geocode results more prominently. (For more information see Viewport Biasing below.)
  • language (optional) — The language in which to return results.
  • region (optional) — The region code, specified as a IANA language region subtag. In most cases, these tags map directly to familiar ccTLD ("top-level domain") two-character values. (For more information see Region Code Biasing below.)

* Note: You may pass either an address or a latLng to lookup. (If you pass a latLng, the geocoder performs what is known as a reverse geocode. See Reverse Geocoding for more information.)

The bounds and region parameters will only influence, not fully restrict, results from the geocoder.

Geocoding Responses

The Geocoding service requires a callback method to execute upon retrieval of the geocoder's results. This callback should pass two parameters to hold the results and a status code, in that order. Since the Geocoder may return more than one entry, the GeocodeResults object literal is an array.

Geocoding Results

The GeocodeResults object literal is a JSON object of the following form:

results[]: {
 types[]: google.maps.GeocoderLocationType,
 formatted_address: String,
 address_components[]: {
   short_name: String,
   long_name: String,
   types[]: String
 },
 geometry: {
   location: LatLng,
   location_type: String
   viewport: LatLngBounds,
   bounds: LatLngBounds
 }
}

These fields are explained below:

  • types[] is an array indicating the type of the returned result. This array contains a set of one or more tags identifying the type of feature returned in the result. For example, a geocode of "Chicago" returns "locality" which indicates that "Chicago" is a city, and also returns "political" which indicates it is a political entity.

  • formatted_address is a string containing the human-readable address of this location. Often this address is equivalent to the "postal address," which sometimes differs from country to country. (Note that some countries, such as Great Britain, do not allow distribution of true postal addresses due to licensing restrictions.) This address is generally composed of one or more address components. For example, the address "111 8th Avenue, New York, NY" contains separate address components for "111 8th Avenue" (a street address), "New York" (the city) and "NY" (the US state). These address components are noted below. (For more information on types, see Types below.

  • address_component[] is an array containing the separate address components, as explained above.

  • geometry contains the following information:

    • location contains the geocoded latitude,longitude value. Note that we return this location as a LatLng object, not as a formatted string.
    • location_type stores additional data about the specified location. The following values are currently supported:

      • google.maps.GeocoderLocationType.ROOFTOP indicates that the returned result reflects a precise geocode.
      • google.maps.GeocoderLocationType.RANGE_INTERPOLATED indicates that the returned result reflects an approximation (usually on a road) interpolated between two precise points (such as intersections). Interpolated results are generally returned when rooftop geocodes are unavailable for a street address.
      • google.maps.GeocoderLocationType.GEOMETRIC_CENTER indicates that the returned result is the geometric center of a result such as a polyline (for example, a street) or polygon (region).
      • google.maps.GeocoderLocationType.APPROXIMATE indicates that the returned result is approximate.
    • viewport stores the recommended viewport for the returned result.
    • bounds (optionally returned) stores the LatLngBounds which can fully contain the returned result. Note that these bounds may not match the recommended viewport. (For example, San Francisco includes the Farallon islands, which are technically part of the city, but should not be returned in the viewport.)

Address Component Types

The types[] array within the returned result indicates the address type. These types may also be returned within address_components[] arrays to indicate the type of the particular address component. Addresses within the geocoder may have multiple types; the types may be considered "tags". For example, many cities are tagged with the political and locality type.

The following types are supported and returned by the HTTP Geocoder:

  • street_address indicates a precise street address.
  • route indicates a named route (such as "US 101").
  • intersection indicates a major intersection, usually of two major roads.
  • political indicates a political entity. Usually, this type indicates a polygon of some civil administration.
  • country indicates the national political entity, and is typically the highest order type returned by the Geocoder.
  • administrative_area_level_1 indicates a first-order civil entity below the country level. Within the United States, these administrative levels are states. Not all nations exhibit these administrative levels.
  • administrative_area_level_2 indicates a second-order civil entity below the country level. Within the United States, these administrative levels are counties. Not all nations exhibit these administrative levels.
  • administrative_area_level_3 indicates a third-order civil entity below the country level. This type indicates a minor civil division. Not all nations exhibit these administrative levels.
  • colloquial_area indicates a commonly-used alternative name for the entity.
  • locality indicates an incorporated city or town political entity.
  • sublocality indicates an first-order civil entity below a locality
  • neighborhood indicates a named neighborhood
  • premise indicates a named location, usually a building or collection of buildings with a common name
  • subpremise indicates a first-order entity below a named location, usually a singular building within a collection of buildings with a common name
  • postal_code indicates a postal code as used to address postal mail within the country.
  • natural_feature indicates a prominent natural feature.
  • airport indicates an airport.
  • park indicates a named park.

In addition to the above, address components may exhibit the following types:

  • post_box indicates a specific postal box.
  • street_number indicates the precise street number.
  • floor indicates the floor of a building address.
  • room indicates the room of a building address.

Status Codes

The status code may return one of the following values:

  • google.maps.GeocoderStatus.OK indicates that the geocode was successful.
  • google.maps.GeocoderStatus.ZERO_RESULTS indicates that the geocode was successful but returned no results. This may occur if the geocode was passed a non-existent address or a latng in a remote location.
  • google.maps.GeocoderStatus.OVER_QUERY_LIMIT indicates that you are over your quota.
  • google.maps.GeocoderStatus.REQUEST_DENIED indicates that your request was denied for some reason.
  • google.maps.GeocoderStatus.INVALID_REQUEST generally indicates that the query (address or latLng) is missing.

In this example, we geocode an address and place a marker at the returned latitude and longitude values. Note that the handler is passed as an anonymous function literal.

  var geocoder;
  var map;
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  }

  function codeAddress() {
    var address = document.getElementById("address").value;
    if (geocoder) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          map.setCenter(results[0].geometry.location);
          var marker = new google.maps.Marker({
              map: map, 
              position: results[0].geometry.location
          });
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }
  }

<body onload="initialize()">
 <div id="map_canvas" style="width: 320px; height: 480px;"></div>
  <div>
    <input id="address" type="textbox" value="Sydney, NSW">
    <input type="button" value="Encode" onclick="codeAddress()">
  </div>
</body>

View example (geocoding-simple.html)

Reverse Geocoding (Address Lookup)

The term geocoding generally refers to translating a human-readable address into a location on a map. The process of doing the converse, translating a location on the map into a human-readable address, is known as reverse geocoding.

The Geocoder supports reverse geocoding directly. Instead of supplying a textual address, supply a comma-separated latitude/longitude pair in the latLng parameter.

The following example geocodes a latitude/longitude value and centers the map at that location, bringing up an info window with the formatted address. We return the second result, which is less specific than the first (in this case, a neighborhood name):

  var geocoder;
  var map;
  var infowindow = new google.maps.InfoWindow();
  var marker;
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(40.730885,-73.997383);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  }

  function codeLatLng() {
    var input = document.getElementById("latlng").value;
    var latlngStr = input.split(",",2);
    var lat = latlngStr[0];
    var lng = latlngStr[1];
    var latlng = new google.maps.LatLng(lat, lng);
    if (geocoder) {
      geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[1]) {
            map.setZoom(11);
            marker = new google.maps.Marker({
                position: latlng, 
                map: map
            }); 
            infowindow.setContent(results[1].formatted_address);
            infowindow.open(map, marker);
          }
        } else {
          alert("Geocoder failed due to: " + status);
        }
      });
    }
  }

Note that in the previous example we showed the second result (by selecting results[1]. The reverse geocoder often returns more than one result. Geocoding "addresses" are not just postal addresses, but any way to geographically name a location. For example, when geocoding a point in the city of Chicago, the geocoded point may be labeled as a street address, as the city (Chicago), as its state (Illinois) or as a country (The United States). All are addresses to the geocoder. The reverse geocoder returns all of these results.

The reverse geocoder matches political entities (countries, provinces, cities and neighborhoods), street addresses, and postal codes.

The full list of addresses returned by the previous query are shown below.

results[0].formatted_address: "275-291 Bedford Ave, Brooklyn, NY 11211, USA",
results[1].formatted_address: "Williamsburg, NY, USA",
results[2].formatted_address: "New York 11211, USA",
results[3].formatted_address: "Kings, New York, USA",
results[4].formatted_address: "Brooklyn, New York, USA",
results[5].formatted_address: "New York, New York, USA",
results[6].formatted_address: "New York, USA",
results[7].formatted_address: "United States"

Addresses are returned in the order of best to least matches. Generally, the more exact address is the most prominent result, as it is in this case. Note that we return different types of addresses, from the most specific street address to less specific political entities such as neighborhoods, cities, counties, states, etc. If you wish to match a more general address, you may wish to inspect the results[].types field.

Note: Reverse geocoding is not an exact science. The geocoder will attempt to find the closest addressable location within a certain tolerance.

View example (geocoding-reverse.html)

Viewport Biasing

You can also instruct the Geocoding Service to prefer results within a given viewport (expressed as a bounding box). You do so by setting the bounds parameter within the GeocodeRequest object literal to define the bounds of this viewport.

For example, a geocode for "Winnetka" generally returns this suburb of Chicago:

{
  "types":["locality","political"],
  "formatted_address":"Winnetka, IL, USA",
  "address_components":[{
    "long_name":"Winnetka",
    "short_name":"Winnetka",
    "types":["locality","political"]
  },{
    "long_name":"Illinois",
    "short_name":"IL",
    "types":["administrative_area_level_1","political"]
  },{
    "long_name":"United States",
    "short_name":"US",
    "types":["country","political"]
  }],
  "geometry":{
    "location":[ -87.7417070, 42.1083080],
    "location_type":"APPROXIMATE"
  }
}

However, specifying a bounds parameter defining a bounding box for the San Fernando Valley of Los Angeles results in this geocode returning the neighborhood named "Winnetka" in that location:

{
  "types":["sublocality","political"],
  "formatted_address":"Winnetka, California, USA",
  "address_components":[{
    "long_name":"Winnetka",
    "short_name":"Winnetka",
    "types":["sublocality","political"]
  },{
    "long_name":"Los Angeles",
    "short_name":"Los Angeles",
    "types":["administrative_area_level_3","political"]
  },{
    "long_name":"Los Angeles",
    "short_name":"Los Angeles",
    "types":["administrative_area_level_2","political"]
  },{
    "long_name":"California",
    "short_name":"CA",
    "types":["administrative_area_level_1","political"]
  },{
    "long_name":"United States",
    "short_name":"US",
    "types":["country","political"]
  }],
  "geometry":{
    "location": [34.213171,-118.571022],
    "location_type":"APPROXIMATE"
  }
}    

Region Code Biasing

You can also set the Geocoding Service to return results biased to a particular region explicitly using the region parameter. This parameter takes a region code, specified as a IANA language region subtag. In most cases, these tags map directly to familiar ccTLD ("top-level domain") two-character values such as "uk" in "co.uk" for example. In some cases, the region tag also supports ISO-3166-1 codes, which sometimes differ from ccTLD values ("GB" for "Great Britain" for example).

Geocoding requests can be sent for every domain in which the main Google Maps application offers geocoding.

For example, a geocode for "Toldeo" returns this result, as the default domain for the Geocoding Service is set to the United States:

{
  "types":["locality","political"],
  "formatted_address":"Toledo, OH, USA",
  "address_components":[{
    "long_name":"Toledo",
    "short_name":"Toledo",
    "types":["locality","political"]
  },{
    "long_name":"Ohio",
    "short_name":"OH",
    "types":["administrative_area_level_1","political"]
  },{
    "long_name":"United States",
    "short_name":"US",
    "types":["country","political"]
  }]
}

A geocode for "Toledo" with the region field set to 'es' (Spain) will return the Spanish city:

{
  "types":["locality","political"],
  "formatted_address":"Toledo, España",
  "address_components":[{
    "long_name":"Toledo",
    "short_name":"Toledo",
    "types":["locality","political"]
  },{
    "long_name":"Toledo",
    "short_name":"TO",
    "types":["administrative_area_level_2","political"]
  },{
    "long_name":"Castilla-La Mancha",
    "short_name":"CM",
    "types":["administrative_area_level_1","political"]
  },{
    "long_name":"España",
    "short_name":"ES",
    "types":["country","political"]
  }]
}

Directions

You can calculate directions (using a variety of methods of transportation) by using the DirectionsService object. This object communicates with the Google Maps API Directions Service which receives direction requests and returns computed results. You may either handle these directions results yourself or use the DirectionsRenderer object to render these results.

Directions may specify origins and destinations either as text strings (e.g. "Chicago, IL" or "Darwin, NSW, Australia") or as LatLng values. The Directions service can return multi-part directions using a series of waypoints. Directions are displayed as a polyline drawing the route on a map, or additionally as a series of textual description within a <div> element (e.g. "Turn right onto the Williamsburg Bridge ramp").

Directions Requests

Accessing the Directions service is asynchronous, since the Google Maps API needs to make a call to an external server. For that reason, you need to pass a callback method to execute upon completion of the request. This callback method should process the result(s). Note that the Directions service may return more than one possible itinerary as an array of trips[].

To use directions in V3, create an object of type DirectionsService and call DirectionsService.route() to initiate a request to the Directions service, passing it a DirectionsRequest object literal containing the input terms and a callback method to execute upon receipt of the response.

The DirectionsRequest object literal contains the following fields:

{
  origin: LatLng | String,
  destination: LatLng | String,
  travelMode: DirectionsTravelMode,
  unitSystem: DirectionsUnitSystem,
  waypoints[]: DirectionsWaypoint,
  provideTripAlternatives: Boolean,
  region: String
}

These fields are explained below:

  • origin (required) specifies the start location from which to calculate directions. This value may either be specified as a String (e.g. "Chicago, IL") or as a LatLng value.
  • destination (required) specifies the end location to which to calculate directions. This value may either be specified as a String (e.g. "Chicago, IL") or as a LatLng value.
  • travelMode (required) specifies what mode of transport to use when calculating directions. Valid values are specified in Travel Modes below.
  • unitSystem (optional) specifies what unit system to use when displaying results. Valid values are specified in Unit Systems below.

  • waypoints[] (optional) specifies an array of DirectionsWaypoints. Waypoints alter a route by routing it through the specified location(s). A waypoint is specified as an object literal with fields shown below:

    • location specifies the location of the waypoint, either as a LatLng or as a String which will be geocoded.
    • stopover is a boolean which indicates that the waypoint is a stop on the route, which has the effect of splitting the route into two routes.

    (For more information on waypoints, see Using Waypoints in Trips below.)

  • provideTripAlternatives (optional) when set to true specifies that the Directions service may provide more than one trip alternative in the response. Note that providing trip alternatives may increase the response time from the server.
  • region (optional) specifies the region code, specified as a ccTLD ("top-level domain") two-character value. (For more information see Region Biasing below.)

A sample DirectionsRequest is shown below:

{
  origin: "Chicago, IL",
  destination: "Los Angeles, CA",
  waypoints: [
    {
      location:"Joplin, MO", 
      stopover:false
    },{
      location:"Oklahoma City, OK",
      stopover:true
    }],
  provideTripAlternatives: false,
  travelMode: DirectionsTravelMode.DRIVING,
  unitSystem: DirectionsUnitSystem.IMPERIAL
}

Travel Modes

When you calculate directions, you need to specify which transportation mode to use. The following travel modes are currently supported:

  • DirectionsTravelMode.DRIVING indicates standard driving directions using the road network.
  • DirectionsTravelMode.WALKING requests walking directions via pedestrian paths & sidewalks (where available).

Note: Walking directions may sometimes not include clear pedestrian paths, so walking directions will return warnings in the DirectionsResult which you must display if you are not using the default DirectionsRenderer.

Unit Systems

By default, directions are calculated and displayed using the unit system of the origin's country or region. For example, a route from "Chicago, IL" to "Toronto, ONT" will display results in miles, while the reverse route will display results in kilometers. You may override this unit system by setting one explicitly within the request using one of the following DirectionsUnitSystem values:

  • DirectionsUnitSystem.METRIC specifies usage of the metric system. Distances are shown using kilometers.
  • DirectionsUnitSystem.IMPERIAL specifies usage of the Imperial (English) system. Distances are shown using miles.

Note: this unit system setting only affects the text displayed to the user. The directions result also contains distance values, not shown to the user, which are always expressed in meters.

Region Biasing for Directions

The Google Maps API Directions Service returns address results influenced by the domain (region or country) from which you loaded the JavaScript bootstrap. (Since most users load http://maps.google.com/ this sets an implicit domain to the United States.) If you load the bootstrap from a different supported domain, you will get results influenced by that domain. For example, searches for "San Francisco" may return different results from applications loading http://maps.google.com/ (the United States) than one loading http://maps.google.es/ (Spain).

You can also set the Directions service to return results biased to a particular region using the region parameter. This parameter takes a region code, specified as a IANA language region subtag. In most cases, these tags map directly to ccTLD ("top-level domain") two-character values such as "uk" in "co.uk" for example. In some cases, the region tag also supports ISO-3166-1 codes, which sometimes differ from ccTLD values ("GB" for "Great Britain" for example).

Consult the Google Maps coverage spreadsheet to determine to what extent a country supports directions.

Rendering Directions

Initiating a directions request to the DirectionsService with the route() method requires passing a callback which executes upon completion of the service request. This callback will return a DirectionsResult and a DirectionsStatus code in the response.

Status of Directions Query

The DirectionsStatus may return the following values:

  • OK indicates the response contains a valid DirectionsResult.
  • NOT_FOUND indicates at least one of the locations specified in the requests's origin, destination, or waypoints could not be geocoded.
  • ZERO_RESULTS indicates no route could be found between the origin and destination.
  • MAX_WAYPOINTS_EXCEEDED indicates that too many DirectionsWaypoints were provided in the DirectionsRequest. The maximum allowed waypoints is 23, plus the origin, and destination.
  • INVALID_REQUEST indicates that the provided DirectionsRequest was invalid.
  • OVER_QUERY_LIMIT indicates the webpage has sent too many requests within the allowed time period.
  • REQUEST_DENIED indicates the webpage is not allowed to use the directions service.
  • UNKNOWN_ERROR indicates a directions request could not be processed due to a server error. The request may succeed if you try again.

You should ensure that the directions query returned valid results by checking this value before processing the result.

Displaying the DirectionsResult

The DirectionsResult contains the result of the directions query, which you may either handle yourself, or pass to a DirectionsRenderer object, which can automatically handle displaying the result on a map.

To display a DirectionsResult using a DirectionsRenderer, you simply need to do the following:

  1. Create a DirectionsRenderer object.
  2. Call setMap() on the renderer to bind it to the passed map.
  3. Call setDirections() on the renderer, passing it the DirectionsResult as noted above. Because the renderer is an MVCObject, it will automatically detect any changes to its properties and update the map when its associated directions have changed.

The following example calculates directions between two locations on Route 66, where the origin and destination are set by the given "start" and "end" values in the dropdown lists. The DirectionsRenderer handles display of the polyline between the indicated locations, and the placement of markers at the origin, destination, and any waypoints, if applicable.

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var myOptions = {
    zoom:7,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: chicago
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  directionsDisplay.setMap(map);
}
  
function calcRoute() {
  var start = document.getElementById("start").value;
  var end = document.getElementById("end").value;
  var request = {
    origin:start, 
    destination:end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(result);
    }
  });
}

<div>
<b>Start: </b>
<select id="start" onchange="calcRoute();">
  <option value="chicago, il">Chicago</option>
  <option value="st louis, mo">St Louis</option>
  <option value="joplin, mo">Joplin, MO</option>
  <option value="oklahoma city, ok">Oklahoma City</option>
  <option value="amarillo, tx">Amarillo</option>
  <option value="gallup, nm">Gallup, NM</option>
  <option value="flagstaff, az">Flagstaff, AZ</option>
  <option value="winona, az">Winona</option>
  <option value="kingman, az">Kingman</option>
  <option value="barstow, ca">Barstow</option>
  <option value="san bernardino, ca">San Bernardino</option>
  <option value="los angeles, ca">Los Angeles</option>
</select>
<b>End: </b>
<select id="end" onchange="calcRoute();">
  <option value="chicago, il">Chicago</option>
  <option value="st louis, mo">St Louis</option>
  <option value="joplin, mo">Joplin, MO</option>
  <option value="oklahoma city, ok">Oklahoma City</option>
  <option value="amarillo, tx">Amarillo</option>
  <option value="gallup, nm">Gallup, NM</option>
  <option value="flagstaff, az">Flagstaff, AZ</option>
  <option value="winona, az">Winona</option>
  <option value="kingman, az">Kingman</option>
  <option value="barstow, ca">Barstow</option>
  <option value="san bernardino, ca">San Bernardino</option>
  <option value="los angeles, ca">Los Angeles</option>
</select>
</div>

View example (directions-simple.html)

A DirectionsRenderer not only handles display of the polyline and any associated markers, but also can handle the textual display of directions as a series of steps. To do so, simply call setPanel() on your DirectionsRenderer, passing it the <div> in which to display this information. Doing so also ensures that you display the appropriate copyright information, and any warnings which may be associated with the result.

Textual directions will be provided using the browser's preferred language setting, or the language specified when loading the API JavaScript using the language parameter. (For more information, see Localization.)

The following example is identical to that shown above, but includes a <div> panel in which to display directions:

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var myOptions = {
    zoom:7,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: chicago
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}
  
function calcRoute() {
  var start = document.getElementById("start").value;
  var end = document.getElementById("end").value;
  var request = {
    origin:start, 
    destination:end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}

// select UI elements omitted
<div><div id="map_canvas" style="float:left;width:70%; height:100%"></div>
<div id="directionsPanel" style="float:right;width:30%;height 100%"></div>   

View example (directions-panel.html)

The Directions Results Object

When sending a directions request to the DirectionsService, you receive a response consisting of a status code, and a result, which is a DirectionsResult object. The DirectionsResult is an object literal with a single field:

  • trips[] contains an array of DirectionsTrip objects. Each trip indicates a way to get from the origin to the destination provided in the DirectionsRequest. Generally, only one trip is returned for any given request, unless the request's provideTripAlternatives field is set to true, in which, multiple trips may be returned.

Directions Trips

A DirectionsTrip contains a single result from the specified origin and destination. This trip may consist of one or more routes (of type DirectionsRoute) depending on whether any waypoints were specified. As well, the trip also contains copyright and warning information which must be displayed to the user in addition to the routing information.

The DirectionsTrip is an object literal with the following fields:

  • routes[] contains an array of DirectionsRoute objects, each of which contains information about a route from two locations within the given trip. A separate route will be present for each waypoint or destination specified. (A trip with no waypoints will contain exactly one DirectionsRoute.) Each route consists of a series of DirectionSteps.
  • copyrights contains the copyrights text to be displayed for this trip. If you do not use the provided DirectionsRenderer object, you must handle and display this information yourself.
  • warnings[] contains an array of warnings to be displayed when showing these directions. If you do not use the provided DirectionsRenderer object, you must handle and display these warnings yourself.

Directions Routes

A DirectionsRoute defines a single leg of a journey from the origin to the destination in the calculated route. For trips that contain no waypoints, the trip will consist of a single "route," but for trips that define one or more waypoints, the trip will consist of one or more routes, corresponding to the specific leg of the journey.

The DirectionsRoute is an object literal with the following fields:

  • steps[] contains an array of DirectionsStep objects denoting information about each separate step of the route.
  • distance indicates the total distance covered by this route, as a DirectionsDistance object of the following form:

    • value indicates the distance in meters
    • text contains a string representation of the distance, which by default is displayed in units as used at the origin. (For example, miles will be used for any origin within the United States.) You may override this unit system by specifically setting a DirectionsUnitSystem in the original query. Note that regardless of what unit system you use, the distance.value field always contains a value expressed in meters.

    These fields may be undefined if the distance is unknown.

  • duration indicates the total duration of this route, as a DirectionsDuration object of the following form:

    • value indicates the duration in seconds.
    • text contains a string representation of the duration.

    These fields may be undefined if the duration is unknown.

  • start_geocode contains a GeocoderResponse denoting the precise geocode of the given origin. Because the DirectionsService calculates directions between locations by using the nearest transportation option (usually a road) at the start and end points, start_geocode indicates the actual geocoded origin, which may be different than the first step if, for example, the road is not near the origin.
  • end_geocode contains a GeocoderResponse denoting the precise geocode of the given destination. Because the DirectionsService calculates directions between locations by using the nearest transportation option (usually a road) at the start and end points, end_geocode indicates the actual geocoded destination, which may be different than the last step if, for example, the road is not near the destination.

Directions Steps

A DirectionsStep is the most atomic unit of a direction's trip, containing a single step describing a specific, single instruction on the journey. E.g. "Turn left at W. 4th St." The step not only describes the instruction but also contains distance and duration information relating to how this step relates to the following step. For example, a step denoted as "Merge onto I-80 West" may contain a duration of "37 miles" and "40 minutes," indicating that the next step is 37 miles/40 minutes from this step.

The DirectionsStep is an object literal with the following fields:

  • instructions contains instructions for this step within a text string.
  • distance contains the distance covered by this step until the next step, as a DirectionsDistance object. (See the description in DirectionsRoute above.) This field may be undefined if the distance is unknown.
  • duration contains the typical time required to perform the step, until the next step, as a DirectionsDuration object. (See the description in DirectionsRoute above.) This field may be undefined if the duration is unknown.
  • start_point contains the LatLng of the starting point of this step.
  • end_point contains the LatLng of the ending point of this step.

Inspecting DirectionsResults

The DirectionsResults components — DirectionsTrip, DirectionsRoute and DirectionsStep — may be inspected and used when parsing any directions response.

The following example plots walking directions to certain tourist attractions in New York City. We inspect the route's DirectionsStep to add markers for each step, and attach information to an InfoWindow with instructional text for that step.

Note: since we are calculating walking directions, we also display any warnings to the user in a separate <div> panel.

var map;
var directionDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];

function initialize() {
  // Instantiate a directions service.
  directionsService = new google.maps.DirectionsService();
    
  // Create a map and center it on Manhattan.
  var manhattan = new google.maps.LatLng(40.7711329, -73.9741874);
  var myOptions = {
    zoom: 13,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: manhattan
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    
  // Create a renderer for directions and bind it to the map.
  var rendererOptions = {
    map: map
  }
  directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)
    
  // Instantiate an info window to hold step text.
  stepDisplay = new google.maps.InfoWindow();
}

function calcRoute() {
  
  // First, clear out any existing markerArray
  // from previous calculations.
  for (i = 0; i < markerArray.length; i++) {
    markerArray[i].setMap(null);
  }

  // Retrieve the start and end locations and create
  // a DirectionsRequest using WALKING directions.
  var start = document.getElementById("start").value;
  var end = document.getElementById("end").value;
  var request = {
      origin: start,
      destination: end,
      travelMode: google.maps.DirectionsTravelMode.WALKING
  };

  // Route the directions and pass the response to a
  // function to create markers for each step.
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      var warnings = document.getElementById("warnings_panel");
      warnings.innerHTML = "" + response.trips[0].warnings + "";
      directionsDisplay.setDirections(response);
      showSteps(response);
    }
  });
}

function showSteps(directionResult) {
  // For each step, place a marker, and add the text to the marker's
  // info window. Also attach the marker to an array so we
  // can keep track of it and remove it when calculating new
  // routes.
  var myRoute = directionResult.trips[0].routes[0];

  for (var i = 0; i < myRoute.steps.length; i++) {
      var marker = new google.maps.Marker({
        position: myRoute.steps[i].start_point, 
        map: map
      });
      attachInstructionText(marker, myRoute.steps[i].instructions);
      markerArray[i] = marker;
  }
}

function attachInstructionText(marker, text) {
  google.maps.event.addListener(marker, 'click', function() {
    stepDisplay.setContent(text);
    stepDisplay.open(map, marker);
  });
}

<div>
<b>Start: </b>
<select id="start">
  <option value="penn station, new york, ny">Penn Station</option>
  <option value="grand central station, new york, ny">Grand Central Station</option>
  <option value="625 8th Avenue New York NY 10018">Port Authority Bus Terminal</option>
  <option value="staten island ferry terminal, new york, ny">Staten Island Ferry Terminal</option>
  <option value="101 E 125th Street, New York, NY">Harlem - 125th St Station</option>
</select>
<b>End: </b>
<select id="end" onchange="calcRoute();">
  <option value="260 Broadway New York NY 10007">City Hall</option>
  <option value="W 49th St & 5th Ave, New York, NY 10020">Rockefeller Center</option>
  <option value="moma, New York, NY">MOMA</option>
  <option value="350 5th Ave, New York, NY, 10118">Empire State Building</option>
  <option value="253 West 125th Street, New York, NY">Apollo Theatre</option>
  <option value="1 Wall St, New York, NY">Wall St</option>
</select>
<div>

View example (directions-complex.html)

Using Waypoints in Trips

As noted within the DirectionsRequest, you may also specify waypoints (of type DirectionsWaypoint) when calculating trips using the Directions service. Waypoints allow you to calculate trips through additional locations, in which case the returned trip passes through the given waypoints in their provided order.

The following example calculates cross-country trips across the United States using a variety of start points, end points, and waypoints. (To select multiple waypoints, press Ctrl-Click when selecting items within the list.) Note that we inspect the routes.start_geocode.formatted_address and routes.end_geocode.formatted_address to provide us with the text for each route's start and end point.

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var myOptions = {
    zoom: 6,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: chicago
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  directionsDisplay.setMap(map);
}
  
function calcRoute() {
  var start = document.getElementById("start").value;
  var end = document.getElementById("end").value;
  var waypts = [];
  var checkboxArray = document.getElementById("waypoints");
  for (var i = 0; i < checkboxArray.length; i++) {
    if (checkboxArray.options[i].selected == true) {
      waypts.push({location:checkboxArray[i].value});
    }
  }

  var request = {
      origin: start, 
      destination: end,
      waypoints: waypts,
      travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      var trip = response.trips[0];
      var summaryPanel = document.getElementById("directions_panel");
      summaryPanel.innerHTML = "";
      // For each route, display summary information.
      for (var i = 0; i < trip.routes.length; i++) {
        var tripSegment = i+1;
        summaryPanel.innerHTML += "<b>Trip Segment: " + tripSegment + "</b><br />";
        summaryPanel.innerHTML += trip.routes[i].start_geocode.formatted_address + " to ";
        summaryPanel.innerHTML += trip.routes[i].end_geocode.formatted_address + "<br />";
        summaryPanel.innerHTML += trip.routes[i].distance.text + "<br /><br />";
      }
    }
  });
}

View example (directions-waypoints.html)