A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developers.google.com/maps/documentation/javascript/directions below:

Directions Service | Maps JavaScript API

Skip to main content Directions Service

Stay organized with collections Save and categorize content based on your preferences.

Important: Using this service requires enabling the Directions API (Legacy) on your project. Note: Server-side libraries

This page describes the client-side service available with the Maps JavaScript API. If you want to work with Google Maps web services on your server, take a look at the Node.js Client for Google Maps Services. The page at that link also introduces the Java Client, Python Client and Go Client for Google Maps Services.

Overview Also see the Maps JavaScript API Reference: 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 an efficient path. Travel time is the primary factor which is optimized, but other factors such as distance, number of turns and many more may be taken into account. You may either handle these directions results yourself or use the DirectionsRenderer object to render these results.

When specifying the origin or destination in a directions request, you can specify a query string (for example, "Chicago, IL" or "Darwin, NSW, Australia"), a LatLng value, or a Place object.

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 (for example, "Turn right onto the Williamsburg Bridge ramp").

Getting started

Before using the Directions service in the Maps JavaScript API, first ensure that the Directions API (Legacy) is enabled in the Google Cloud console, in the same project you set up for the Maps JavaScript API.

To view your list of enabled APIs:

  1. Go to the Google Cloud console.
  2. Click the Select a project button, then select the same project you set up for the Maps JavaScript API and click Open.
  3. From the list of APIs on the Dashboard, look for Directions API (Legacy).
  4. If you see the API in the list, you’re all set. If the API is not listed, enable it at https://console.cloud.google.com/apis/library/directions-backend.googleapis.com
Pricing and policies Pricing

To learn about pricing and usage policies for the JavaScript Directions service, see Usage and Billing for the Directions API (Legacy).

Policies

Use of the Directions service must be in accordance with the policies described for the Directions API (Legacy).

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 separate routes[].

To use directions in the Maps JavaScript API, 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 | google.maps.Place,
  destination: LatLng | String | google.maps.Place,
  travelMode: TravelMode,
  transitOptions: TransitOptions,
  drivingOptions: DrivingOptions,
  unitSystem: UnitSystem,
  waypoints[]: DirectionsWaypoint,
  optimizeWaypoints: Boolean,
  provideRouteAlternatives: Boolean,
  avoidFerries: Boolean,
  avoidHighways: Boolean,
  avoidTolls: Boolean,
  region: String
}

These fields are explained below:

Note: The durationInTraffic field is now deprecated. It was previously the recommended way for Google Maps Platform Premium Plan customers to specify whether the result should include a duration that takes into account current traffic conditions. You should now use the drivingOptions field instead.

Below is a sample DirectionsRequest:

{
  origin: 'Chicago, IL',
  destination: 'Los Angeles, CA',
  waypoints: [
    {
      location: 'Joplin, MO',
      stopover: false
    },{
      location: 'Oklahoma City, OK',
      stopover: true
    }],
  provideRouteAlternatives: false,
  travelMode: 'DRIVING',
  drivingOptions: {
    departureTime: new Date(/* now, or future date */),
    trafficModel: 'pessimistic'
  },
  unitSystem: google.maps.UnitSystem.IMPERIAL
}
Travel Modes

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

Consult the Google Maps Platform Coverage Details to determine to what extent a country supports directions. If you request directions for a region in which that direction type is not available, the response will return the DirectionsStatus="ZERO_RESULTS".

Note: Walking directions may not include clear pedestrian paths, so walking directions will return warnings in the DirectionsResult. These warnings must always be displayed to the user. If you do not use the default DirectionsRenderer then you are responsible for ensuring the warnings are displayed.

Transit Options

The available options for a directions request vary between travel modes. When requesting transit directions, the avoidHighways, avoidTolls, waypoints[] and optimizeWaypoints options will be ignored. You can specify transit specific routing options through the TransitOptions object literal.

Transit directions are time sensitive. Directions will only be returned for times in the future.

The TransitOptions object literal contains the following fields:

{
  arrivalTime: Date,
  departureTime: Date,
  modes[]: TransitMode,
  routingPreference: TransitRoutePreference
}

These fields are explained below:

A sample DirectionsRequest by transit is shown below:

{
  origin: 'Hoboken NJ',
  destination: 'Carroll Gardens, Brooklyn',
  travelMode: 'TRANSIT',
  transitOptions: {
    departureTime: new Date(1337675679473),
    modes: ['BUS'],
    routingPreference: 'FEWER_TRANSFERS'
  },
  unitSystem: google.maps.UnitSystem.IMPERIAL
}
Driving Options

You can specify routing options for driving directions through the DrivingOptions object.

The DrivingOptions object contains the following fields:

{
  departureTime: Date,
  trafficModel: TrafficModel
}

These fields are explained below:

Caution: If you do not specify a departure time, the route and duration chosen are based on road network and average time-independent traffic conditions, not current road conditions. Consequently, routes may include roads that are temporarily closed. Results for a given request may vary over time due to changes in the road network, updated average traffic conditions, and the distributed nature of the service. Results may also vary between nearly-equivalent routes at any time or frequency. Note: To ensure that your request uses live traffic information, set the departureTime to now. Requests using traffic information are billed at a higher rate. Learn more about how Google Maps Platform products are billed.

Below is a sample DirectionsRequest for driving directions:

{
  origin: 'Chicago, IL',
  destination: 'Los Angeles, CA',
  travelMode: 'DRIVING',
  drivingOptions: {
    departureTime: new Date(Date.now() + N),  // for the time N milliseconds from now.
    trafficModel: 'optimistic'
  }
}
Unit Systems

By default, directions are calculated and displayed using the unit system of the origin's country or region. (Note: Origins expressed using latitude/longitude coordinates rather than addresses always default to metric units.) 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 can override this unit system by setting one explicitly within the request using one of the following UnitSystem values:

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 https://maps.googleapis.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 https://maps.googleapis.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 two-character (non-numeric) Unicode 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).

When using the region parameter:

Region biasing is supported only for the countries and regions supporting directions. Consult Google Maps Platform Coverage Details to see international coverage for the Directions API (Legacy).

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:

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

function initMap() {
  var directionsService = new google.maps.DirectionsService();
  var directionsRenderer = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = {
    zoom:7,
    center: chicago
  }
  var map = new google.maps.Map(document.getElementById('map'), mapOptions);
  directionsRenderer.setMap(map);
}

function calcRoute() {
  var start = document.getElementById('start').value;
  var end = document.getElementById('end').value;
  var request = {
    origin: start,
    destination: end,
    travelMode: 'DRIVING'
  };
  directionsService.route(request, function(result, status) {
    if (status == 'OK') {
      directionsRenderer.setDirections(result);
    }
  });
}

In the HTML body:

<div>
<strong>Start: </strong>
<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>
<strong>End: </strong>
<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

The following example shows directions using different modes of travel between the Haight-Ashbury to Ocean Beach in San Francisco, CA:

function initMap() {
  var directionsService = new google.maps.DirectionsService();
  var directionsRenderer = new google.maps.DirectionsRenderer();
  var haight = new google.maps.LatLng(37.7699298, -122.4469157);
  var oceanBeach = new google.maps.LatLng(37.7683909618184, -122.51089453697205);
  var mapOptions = {
    zoom: 14,
    center: haight
  }
  var map = new google.maps.Map(document.getElementById('map'), mapOptions);
  directionsRenderer.setMap(map);
}

function calcRoute() {
  var selectedMode = document.getElementById('mode').value;
  var request = {
      origin: haight,
      destination: oceanBeach,
      // Note that JavaScript allows us to access the constant
      // using square brackets and a string value as its
      // "property."
      travelMode: google.maps.TravelMode[selectedMode]
  };
  directionsService.route(request, function(response, status) {
    if (status == 'OK') {
      directionsRenderer.setDirections(response);
    }
  });
}

In the HTML body:

<div>
<strong>Mode of Travel: </strong>
<select id="mode" onchange="calcRoute();">
  <option value="DRIVING">Driving</option>
  <option value="WALKING">Walking</option>
  <option value="BICYCLING">Bicycling</option>
  <option value="TRANSIT">Transit</option>
</select>
</div>

View example

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, 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.) In the case of transit directions, the time will be displayed in the time zone at that transit stop.

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

function initMap() {
  var directionsService = new google.maps.DirectionsService();
  var directionsRenderer = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = {
    zoom:7,
    center: chicago
  }
  var map = new google.maps.Map(document.getElementById('map'), mapOptions);
  directionsRenderer.setMap(map);
  directionsRenderer.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: 'DRIVING'
  };
  directionsService.route(request, function(response, status) {
    if (status == 'OK') {
      directionsRenderer.setDirections(response);
    }
  });
}

In the HTML body:

<div id="map" style="float:left;width:70%;height:100%"></div>
<div id="directionsPanel" style="float:right;width:30%;height:100%"></div>

View example

The DirectionsResult 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 the following fields:

Note: The via_waypoint property is deprecated in alternative routes. Version 3.27 is the last version of the API that adds extra via waypoints in alternative routes. For versions 3.28 and higher of the API, you can continue to implement draggable directions using the Directions service by disabling the dragging of alternative routes. Only the main route should be draggable. Users can drag the main route until it matches an alternative route.

Directions Geocoded Waypoints

A DirectionsGeocodedWaypoint contains details about the geocoding of origin, destination and waypoints.

The DirectionsGeocodedWaypoint is an object literal with the following fields:

Directions Routes

Note: The legacy DirectionsTrip object has been renamed DirectionsRoute. Note that a route now refers to the entire start to end journey, rather than simply a leg of a parent trip.

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

The DirectionsRoute is an object literal with the following fields:

Directions Legs

Note: The legacy DirectionsRoute object has been renamed DirectionsLeg.

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

The DirectionsLeg is an object literal with the following fields:

Directions Steps

A DirectionsStep is the most atomic unit of a direction's route, 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.

When using the Directions service to search for transit directions, the steps array will include additional Transit Specific Information in the form of a transit object. If the directions include multiple modes of transportation, detailed directions will be provided for walking or driving steps in a steps[] array. For example, a walking step will include directions from the start and end locations: "Walk to Innes Ave & Fitch St". That step will include detailed walking directions for that route in the steps[] array, such as: "Head north-west", "Turn left onto Arelious Walker", and "Turn left onto Innes Ave".

The DirectionsStep is an object literal with the following fields:

Transit Specific Information

Transit directions return additional information that is not relevant for other modes of transportation. These additional properties are exposed through the TransitDetails object, returned as a property of DirectionsStep. From the TransitDetails object you can access additional information for the TransitStop, TransitLine, TransitAgency, and VehicleType objects as described below.

Transit Details

The TransitDetails object exposes the following properties:

Transit Line

The TransitLine object exposes the following properties:

Vehicle Type

The VehicleType object exposes the following properties:

Value Definition VehicleType.RAIL Rail. VehicleType.METRO_RAIL Light rail transit. VehicleType.SUBWAY Underground light rail. VehicleType.TRAM Above ground light rail. VehicleType.MONORAIL Monorail. VehicleType.HEAVY_RAIL Heavy rail. VehicleType.COMMUTER_TRAIN Commuter rail. VehicleType.HIGH_SPEED_TRAIN High speed train. VehicleType.BUS Bus. VehicleType.INTERCITY_BUS Intercity bus. VehicleType.TROLLEYBUS Trolleybus. VehicleType.SHARE_TAXI Share taxi is a kind of bus with the ability to drop off and pick up passengers anywhere on its route. VehicleType.FERRY Ferry. VehicleType.CABLE_CAR A vehicle that operates on a cable, usually on the ground. Aerial cable cars may be of the type VehicleType.GONDOLA_LIFT. VehicleType.GONDOLA_LIFT An aerial cable car. VehicleType.FUNICULAR A vehicle that is pulled up a steep incline by a cable. A Funicular typically consists of two cars, with each car acting as a counterweight for the other. VehicleType.OTHER All other vehicles will return this type. Inspecting DirectionsResults

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

Important: If you are rendering transit directions manually instead of using the DirectionsRenderer object, you must display the names and URLs of the transit agencies servicing the trip results.

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 directionsRenderer;
var directionsService;
var stepDisplay;
var markerArray = [];

function initMap() {
  // 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 mapOptions = {
    zoom: 13,
    center: manhattan
  }
  map = new google.maps.Map(document.getElementById('map'), mapOptions);

  // Create a renderer for directions and bind it to the map.
  var rendererOptions = {
    map: map
  }
  directionsRenderer = 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: '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 == "OK") {
      var warnings = document.getElementById("warnings_panel");
      warnings.innerHTML = "" + response.routes[0].warnings + "";
      directionsRenderer.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.routes[0].legs[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);
  });
}

In the HTML body:

<div>
<strong>Start: </strong>
<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>
<strong>End: </strong>
<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

Using Waypoints in Routes Caution: Requests using more than 10 waypoints, or waypoint optimization, are billed at a higher rate. Learn more about how Google Maps Platform products are billed.

As noted within the DirectionsRequest, you may also specify waypoints (of type DirectionsWaypoint) when calculating routes using the Directions service for walking, bicycling or driving directions. Waypoints are not available for transit directions. Waypoints allow you to calculate routes through additional locations, in which case the returned route passes through the given waypoints.

A waypoint consists of the following fields:

Caution: Setting the stopover to false to avoid stopovers results in directions that are very strict in their interpretation of the waypoint. This may result in severe detours on the route or ZERO_RESULTS in the response status code if the Directions Service is unable to create directions through that point.

By default, the Directions service calculates a route through the provided waypoints in their given order. Optionally, you may pass optimizeWaypoints: true within the DirectionsRequest to allow the Directions service to optimize the provided route by rearranging the waypoints in a more efficient order. (This optimization is an application of the traveling salesperson problem.) Travel time is the primary factor which is optimized, but other factors such as distance, number of turns and many more may be taken into account when deciding which route is the most efficient. All waypoints must be stopovers for the Directions service to optimize their route.

If you instruct the Directions service to optimize the order of its waypoints, their order will be returned in the waypoint_order field within the DirectionsResult object.

The following example calculates cross-country routes 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_address and routes.end_address to provide us with the text for each route's start and end point.

TypeScript
function initMap(): void {
  const directionsService = new google.maps.DirectionsService();
  const directionsRenderer = new google.maps.DirectionsRenderer();
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 6,
      center: { lat: 41.85, lng: -87.65 },
    }
  );

  directionsRenderer.setMap(map);

  (document.getElementById("submit") as HTMLElement).addEventListener(
    "click",
    () => {
      calculateAndDisplayRoute(directionsService, directionsRenderer);
    }
  );
}

function calculateAndDisplayRoute(
  directionsService: google.maps.DirectionsService,
  directionsRenderer: google.maps.DirectionsRenderer
) {
  const waypts: google.maps.DirectionsWaypoint[] = [];
  const checkboxArray = document.getElementById(
    "waypoints"
  ) as HTMLSelectElement;

  for (let i = 0; i < checkboxArray.length; i++) {
    if (checkboxArray.options[i].selected) {
      waypts.push({
        location: (checkboxArray[i] as HTMLOptionElement).value,
        stopover: true,
      });
    }
  }

  directionsService
    .route({
      origin: (document.getElementById("start") as HTMLInputElement).value,
      destination: (document.getElementById("end") as HTMLInputElement).value,
      waypoints: waypts,
      optimizeWaypoints: true,
      travelMode: google.maps.TravelMode.DRIVING,
    })
    .then((response) => {
      directionsRenderer.setDirections(response);

      const route = response.routes[0];
      const summaryPanel = document.getElementById(
        "directions-panel"
      ) as HTMLElement;

      summaryPanel.innerHTML = "";

      // For each route, display summary information.
      for (let i = 0; i < route.legs.length; i++) {
        const routeSegment = i + 1;

        summaryPanel.innerHTML +=
          "<b>Route Segment: " + routeSegment + "</b><br>";
        summaryPanel.innerHTML += route.legs[i].start_address + " to ";
        summaryPanel.innerHTML += route.legs[i].end_address + "<br>";
        summaryPanel.innerHTML += route.legs[i].distance!.text + "<br><br>";
      }
    })
    .catch((e) => window.alert("Directions request failed due to " + status));
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;
Note: Read the guide on using TypeScript and Google Maps. JavaScript
function initMap() {
  const directionsService = new google.maps.DirectionsService();
  const directionsRenderer = new google.maps.DirectionsRenderer();
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 6,
    center: { lat: 41.85, lng: -87.65 },
  });

  directionsRenderer.setMap(map);
  document.getElementById("submit").addEventListener("click", () => {
    calculateAndDisplayRoute(directionsService, directionsRenderer);
  });
}

function calculateAndDisplayRoute(directionsService, directionsRenderer) {
  const waypts = [];
  const checkboxArray = document.getElementById("waypoints");

  for (let i = 0; i < checkboxArray.length; i++) {
    if (checkboxArray.options[i].selected) {
      waypts.push({
        location: checkboxArray[i].value,
        stopover: true,
      });
    }
  }

  directionsService
    .route({
      origin: document.getElementById("start").value,
      destination: document.getElementById("end").value,
      waypoints: waypts,
      optimizeWaypoints: true,
      travelMode: google.maps.TravelMode.DRIVING,
    })
    .then((response) => {
      directionsRenderer.setDirections(response);

      const route = response.routes[0];
      const summaryPanel = document.getElementById("directions-panel");

      summaryPanel.innerHTML = "";

      // For each route, display summary information.
      for (let i = 0; i < route.legs.length; i++) {
        const routeSegment = i + 1;

        summaryPanel.innerHTML +=
          "<b>Route Segment: " + routeSegment + "</b><br>";
        summaryPanel.innerHTML += route.legs[i].start_address + " to ";
        summaryPanel.innerHTML += route.legs[i].end_address + "<br>";
        summaryPanel.innerHTML += route.legs[i].distance.text + "<br><br>";
      }
    })
    .catch((e) => window.alert("Directions request failed due to " + status));
}

window.initMap = initMap;
Limits and Restrictions for Waypoints

The following usage limits and restrictions apply:

Draggable Directions

Users may modify cycling, walking or driving directions displayed using a DirectionsRenderer dynamically if they are draggable, allowing a user to select and alter routes by clicking and dragging the resulting paths on the map. You indicate whether a renderer's display allows draggable directions by setting its draggable property to true. Transit directions cannot be made draggable.

When directions are draggable, a user may select any point on the path (or waypoint) of the rendered result and move the indicated component to a new location. The DirectionsRenderer will dynamically update to show the modified path. Upon release, a transitional waypoint will be added to the map (indicated by a small white marker). Selecting and moving a path segment will alter that leg of the route, while selecting and moving a waypoint marker (including start and end points) will alter the legs of the route passing through that waypoint.

Because draggable directions are modified and rendered client-side, you may wish to monitor and handle the directions_changed event on the DirectionsRenderer to be notified when the user has modified the displayed directions.

The following code shows a trip from Perth on the west coast of Australia to Sydney on the east coast. The code monitors the directions_changed event to update the total distance of all legs of the journey.

TypeScript
function initMap(): void {
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 4,
      center: { lat: -24.345, lng: 134.46 }, // Australia.
    }
  );

  const directionsService = new google.maps.DirectionsService();
  const directionsRenderer = new google.maps.DirectionsRenderer({
    draggable: true,
    map,
    panel: document.getElementById("panel") as HTMLElement,
  });

  directionsRenderer.addListener("directions_changed", () => {
    const directions = directionsRenderer.getDirections();

    if (directions) {
      computeTotalDistance(directions);
    }
  });

  displayRoute(
    "Perth, WA",
    "Sydney, NSW",
    directionsService,
    directionsRenderer
  );
}

function displayRoute(
  origin: string,
  destination: string,
  service: google.maps.DirectionsService,
  display: google.maps.DirectionsRenderer
) {
  service
    .route({
      origin: origin,
      destination: destination,
      waypoints: [
        { location: "Adelaide, SA" },
        { location: "Broken Hill, NSW" },
      ],
      travelMode: google.maps.TravelMode.DRIVING,
      avoidTolls: true,
    })
    .then((result: google.maps.DirectionsResult) => {
      display.setDirections(result);
    })
    .catch((e) => {
      alert("Could not display directions due to: " + e);
    });
}

function computeTotalDistance(result: google.maps.DirectionsResult) {
  let total = 0;
  const myroute = result.routes[0];

  if (!myroute) {
    return;
  }

  for (let i = 0; i < myroute.legs.length; i++) {
    total += myroute.legs[i]!.distance!.value;
  }

  total = total / 1000;
  (document.getElementById("total") as HTMLElement).innerHTML = total + " km";
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;
Note: Read the guide on using TypeScript and Google Maps. JavaScript
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: { lat: -24.345, lng: 134.46 }, // Australia.
  });
  const directionsService = new google.maps.DirectionsService();
  const directionsRenderer = new google.maps.DirectionsRenderer({
    draggable: true,
    map,
    panel: document.getElementById("panel"),
  });

  directionsRenderer.addListener("directions_changed", () => {
    const directions = directionsRenderer.getDirections();

    if (directions) {
      computeTotalDistance(directions);
    }
  });
  displayRoute(
    "Perth, WA",
    "Sydney, NSW",
    directionsService,
    directionsRenderer,
  );
}

function displayRoute(origin, destination, service, display) {
  service
    .route({
      origin: origin,
      destination: destination,
      waypoints: [
        { location: "Adelaide, SA" },
        { location: "Broken Hill, NSW" },
      ],
      travelMode: google.maps.TravelMode.DRIVING,
      avoidTolls: true,
    })
    .then((result) => {
      display.setDirections(result);
    })
    .catch((e) => {
      alert("Could not display directions due to: " + e);
    });
}

function computeTotalDistance(result) {
  let total = 0;
  const myroute = result.routes[0];

  if (!myroute) {
    return;
  }

  for (let i = 0; i < myroute.legs.length; i++) {
    total += myroute.legs[i].distance.value;
  }

  total = total / 1000;
  document.getElementById("total").innerHTML = total + " km";
}

window.initMap = initMap;
Note: The JavaScript is compiled from the TypeScript snippet. View example Try Sample

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-08-14 UTC.

[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-14 UTC."],[],[]]


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4