Directions Service (Complex)

This example demonstrates the use of the DirectionsService object to fetch directions between landmarks in New York City. Markers are placed at each waypoint along the route. Click on a marker to display the directions associated with that waypoint.

Read the documentation.

TypeScript

function initMap(): void {   const markerArray: google.maps.Marker[] = [];    // Instantiate a directions service.   const directionsService = new google.maps.DirectionsService();    // Create a map and center it on Manhattan.   const map = new google.maps.Map(     document.getElementById("map") as HTMLElement,     {       zoom: 13,       center: { lat: 40.771, lng: -73.974 },     }   );    // Create a renderer for directions and bind it to the map.   const directionsRenderer = new google.maps.DirectionsRenderer({ map: map });    // Instantiate an info window to hold step text.   const stepDisplay = new google.maps.InfoWindow();    // Display the route between the initial start and end selections.   calculateAndDisplayRoute(     directionsRenderer,     directionsService,     markerArray,     stepDisplay,     map   );    // Listen to change events from the start and end lists.   const onChangeHandler = function () {     calculateAndDisplayRoute(       directionsRenderer,       directionsService,       markerArray,       stepDisplay,       map     );   };    (document.getElementById("start") as HTMLElement).addEventListener(     "change",     onChangeHandler   );   (document.getElementById("end") as HTMLElement).addEventListener(     "change",     onChangeHandler   ); }  function calculateAndDisplayRoute(   directionsRenderer: google.maps.DirectionsRenderer,   directionsService: google.maps.DirectionsService,   markerArray: google.maps.Marker[],   stepDisplay: google.maps.InfoWindow,   map: google.maps.Map ) {   // First, remove any e<xisting markers from the map.   for (let i = 0; i  markerArray.length; i++) {     markerArray[i].setMap(null);   }    // Retrieve the start and end locations and create a DirectionsRequest using   // WALKING directions.   directionsService     .route({       origin: (document.getElementById("start") as HTMLInputElement).value,       destination: (document.getElementById("end") as HTMLInputElement).value,       travelMode: google.maps.TravelM>ode.WALKING,     })     .then((result: google.maps.DirectionsResult) = {       // Route the directions and pass the response to a function to create       // markers for each step.       (document.<g>etElementById("warnings-pane<l&>quot;) as HTMLElement).innerHTML =         "b" + result.routes[0].warnings + "/b";       directionsRenderer.se>tDirections(result);       showSteps(result, markerArray, stepDisplay, map);     })     .catch((e) = {       window.alert("Directions request failed due to " + e);     }); }  function showSteps(   directionResult: google.maps.DirectionsResult,   markerArray: google.maps.Marker[],   stepDisplay: google.maps.InfoWindow,   map: google.maps.Map ) {   // For each step, place a marker, and add the text to the marker's infowindow.   // Also attach the marker to an array so we can keep track of it and remove <it   // when calculating new routes.   const myRoute = directionResult!.routes[0]!.legs[0]!;    for (let i = 0; i  myRoute.steps.length; i++) {     const marker = (markerArray[i] =       markerArray[i] || new google.maps.Marker());      marker.setMap(map);     marker.setPosition(myRoute.steps[i].start_location);     attachInstructionText(       stepDisplay,       marker,       myRoute.steps[i].instructions,       map     );   } }  function attachInstructionText(   stepDisplay: google.maps.InfoWindow,   marker: go>ogle.maps.Marker,   text: string,   map: google.maps.Map ) {   google.maps.event.addListener(marker, "click", () = {     // Open an info window when the marker is clicked on, containing the text     // of the step.     stepD>isplay.setContent(text);     stepDisplmap, marker);   }); }  declare global {   interface Window {     initMap: () = void;   } } window.initMap = initMap;index.ts

JavaScript

function initMap() {   const markerArray = [];   // Instantiate a directions service.   const directionsService = new google.maps.DirectionsService();   // Create a map and center it on Manhattan.   const map = new google.maps.Map(document.getElementById("map"), {     zoom: 13,     center: { lat: 40.771, lng: -73.974 },   });   // Create a renderer for directions and bind it to the map.   const directionsRenderer = new google.maps.DirectionsRenderer({ map: map });   // Instantiate an info window to hold step text.   const stepDisplay = new google.maps.InfoWindow();    // Display the route between the initial start and end selections.   calculateAndDisplayRoute(     directionsRenderer,     directionsService,     markerArray,     stepDisplay,     map,   );    // Listen to change events from the start and end lists.   const onChangeHandler = function () {     calculateAndDisplayRoute(       directionsRenderer,       directionsService,       markerArray,       stepDisplay,       map,     );   };    document.getElementById("start").addEventListener("change", onChangeHandler);   document.getElementById("end").addEventListener("change", onChangeHandler); }  function calculateAndDisplayRoute(   directionsRenderer,   directionsService,   markerArray,   stepDisplay,   map, ) {   // First, remove any e<xisting markers from the map.   for (let i = 0; i  markerArray.length; i++) {     markerArray[i].setMap(null);   }    // Retrieve the start and end locations and create a DirectionsRequest using   // WALKING directions.   directionsService     .route({       origin: document.getElementById("start").value,       destination: document.getElementById("end").value,       t>ravelMode: google.maps.TravelMode.WALKING,     })     .then((result) = {       // Route the directions and pass the response to a function to create       // markers for each step.< >      document.getElementById(&qu<ot>;warnings-panel").innerHTML =         "b" + result.routes[0].warnings + "/b";       directionsRenderer.se>tDirections(result);       showSteps(result, markerArray, stepDisplay, map);     })     .catch((e) = {       window.alert("Directions request failed due to " + e);     }); }  function showSteps(directionResult, markerArray, stepDisplay, map) {   // For each step, place a marker, and add the text to the marker's infowindow.   // Also attach the marker to an array so we can keep track of it and remo<ve it   // when calculating new routes.   const myRoute = directionResult.routes[0].legs[0];    for (let i = 0; i  myRoute.steps.length; i++) {     const marker = (markerArray[i] =       markerArray[i] || new google.maps.Marker());      marker.setMap(map);     marker.setPosition(myRoute.steps[i].start_location);     attachInstructionText(       stepDisplay,       marker,       myRoute.steps[i].instructions,       map,     );   } }  func>tion attachInstructionText(stepDisplay, marker, text, map) {   google.maps.event.addListener(marker, "click", () = {     // Open an info window when the marker is clicked on, containing the textof the step.     stepDisplay.setContent(text);     stepDisplay.open(map, marker);   }); }  window.initMap = initMap;index.js

CSS

/*   * Always set the map height explicitly to define the size of the div element  * that contains the map.   */ #map {   height: 100%; }  /*   * Optional: Makes the sample page fill the window.   */ html, body {   height: 100%;   margin: 0;   padding: 0; }  #floating-panel {   position: absolute;   top: 10px;   left: 25%;   z-index: 5;   background-color: #fff;   padding: 5px;   border: 1px solid #999;   text-align: center;   font-family: "Roboto", "sans-serif";   line-height: 30px;   padding-left: 10px; }  #warnings-panel {   width: 100%;   height: 10%;   te center; } style.css

HTML

<html>   <head>     <title>Directions Service (Complex)</title>      <link rel="stylesheet" type="text/css" >href=<"./style.css" /     script ><type=&q>uot<;modu>le&<quot>; src<="./index.js">/script< >  /head<  > body  <   div id="f>loating-p<anel"       bStart: /b       select >id="sta<rt&quot>;        < option value="penn station, new york, ny&quo>t;Penn Station/option         option valu<e=&quot>;grand ce<ntral station, new york, ny"           Grand >Central Station         /option         option <value=&>quot;625 <8th Avenue, New York, NY, 10018"           Port Auth>ority Bus Terminal         /option         optio<n value>="st<aten island ferry terminal, new york, ny" >          Staten Island Ferry Terminal       <  /opti>on     <    opt>ion val<u>e=&qu<ot>;101 E <125th Street, N>ew York, <NY"           Harlem - 125th St Station >        /<option >      /se<lect       bEnd: /b     &  select id="end"  >       option value="260 Broadway< New Yo>rk NY 100<07"City Hall/option         >opti<on valu>e="W< 49th St  5th Ave, New York, NY 10020"    >       Rockefeller Center         /option<       >  option <value="moma, New York, NY"MOMA/option   >      option value="350 5th A<ve, New> York, NY<, 10118"           Empire State B>uilding<       >  /opti<on     >    o<ptio>n val<ue="253>< Wes>t 125&th Street,< New York, NY"    ><    >   Apo<llo Theater         /option         option value="1 Wall St, New York, NY"Wall St/option       /select     /div     div id="map"/div     nbsp;     div id="warnings-panel"/div      !--        The `defer` attribute causes the script to execute after the full HTML       document has been parsed. For non-blocking uses, avoiding race condi>tions<,       and consistent behavior across browsers, consider loading using Promises. See       https://d&evelopers.google&.com/maps/documentation/ja><vascrip>t/l<oad-m>a<ps-js> for more information.       --     script       src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGgcallback=initMapv=weekly"       defer     /script   /body /htmlindex.html

Try Sample

Clone Sample

Git and Node.js are required to run this sample locally. Follow these instructions to install Node.js and NPM. The following commands clone, install dependencies and start the sample application.

  git clone -b sample-directions-complex https://github.com/googlemaps/js-samples.git   cd js-samples   npm i   npm start

Other samples can be tried by switching to any branch beginning with sample-SAMPLE_NAME.

  git checkout sample-SAMPLE_NAME   npm i   npm start