functioninitMap():void{constdirectionsService=newgoogle.maps.DirectionsService();constdirectionsRenderer=newgoogle.maps.DirectionsRenderer();constmap=newgoogle.maps.Map(document.getElementById("map")asHTMLElement,{zoom:6,center:{lat:41.85,lng:-87.65},});directionsRenderer.setMap(map);(document.getElementById("submit")asHTMLElement).addEventListener("click",()=>{calculateAndDisplayRoute(directionsService,directionsRenderer);});}functioncalculateAndDisplayRoute(directionsService:google.maps.DirectionsService,directionsRenderer:google.maps.DirectionsRenderer){constwaypts:google.maps.DirectionsWaypoint[]=[];constcheckboxArray=document.getElementById("waypoints")asHTMLSelectElement;for(leti=0;i < checkboxArray.length;i++){if(checkboxArray.options[i].selected){waypts.push({location:(checkboxArray[i]asHTMLOptionElement).value,stopover:true,});}}directionsService.route({origin:(document.getElementById("start")asHTMLInputElement).value,destination:(document.getElementById("end")asHTMLInputElement).value,waypoints:waypts,optimizeWaypoints:true,travelMode:google.maps.TravelMode.DRIVING,}).then((response)=>{directionsRenderer.setDirections(response);constroute=response.routes[0];constsummaryPanel=document.getElementById("directions-panel")asHTMLElement;summaryPanel.innerHTML="";// For each route, display summary information.for(leti=0;i < route.legs.length;i++){constrouteSegment=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));}declareglobal{interfaceWindow{initMap:()=>void;}}window.initMap=initMap;
functioninitMap(){constdirectionsService=newgoogle.maps.DirectionsService();constdirectionsRenderer=newgoogle.maps.DirectionsRenderer();constmap=newgoogle.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);});}functioncalculateAndDisplayRoute(directionsService,directionsRenderer){constwaypts=[];constcheckboxArray=document.getElementById("waypoints");for(leti=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);constroute=response.routes[0];constsummaryPanel=document.getElementById("directions-panel");summaryPanel.innerHTML="";// For each route, display summary information.for(leti=0;i < route.legs.length;i++){constrouteSegment=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;
/* Optional: Makes the sample page fill the window. */html,body{height:100%;margin:0;padding:0;}#container{height:100%;display:flex;}#sidebar{flex-basis:15rem;flex-grow:1;padding:1rem;max-width:30rem;height:100%;box-sizing:border-box;overflow:auto;}#map{flex-basis:0;flex-grow:4;height:100%;}#directions-panel{margin-top:10px;}
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.
[null,null,["Last updated 2025-08-28 UTC."],[[["\u003cp\u003eThis example showcases the functionality of the \u003ccode\u003eDirectionsService\u003c/code\u003e object in the Google Maps JavaScript API to calculate and display routes with waypoints.\u003c/p\u003e\n"],["\u003cp\u003eUsers can select a starting point, an ending point, and multiple waypoints from dropdown menus to define their desired route.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eoptimizeWaypoints\u003c/code\u003e option is used to find the most efficient order for visiting the selected waypoints.\u003c/p\u003e\n"],["\u003cp\u003eThe calculated route, including the total distance and directions for each segment, is displayed on a map and in a separate panel.\u003c/p\u003e\n"],["\u003cp\u003eThe example code is provided in both JavaScript and TypeScript for developers to understand and implement the functionality in their applications.\u003c/p\u003e\n"]]],["This code utilizes the `DirectionsService` to calculate and display a route on a Google Map. Users select a start, end, and multiple waypoints from dropdown menus. Upon submission, the `calculateAndDisplayRoute` function fetches directions from the `DirectionsService`, including the selected waypoints. The route is then rendered on the map, and summary details (route segments, start/end addresses, distances) are displayed in a designated panel. The code also optimizes the order of the waypoints.\n"],null,["This example demonstrates the use of the `DirectionsService` object\nto fetch directions for a route including waypoints.\n\nRead the [documentation](/maps/documentation/javascript/directions#Waypoints). \n\nTypeScript \n\n```typescript\nfunction initMap(): void {\n const directionsService = new google.maps.DirectionsService();\n const directionsRenderer = new google.maps.DirectionsRenderer();\n const map = new google.maps.Map(\n document.getElementById(\"map\") as HTMLElement,\n {\n zoom: 6,\n center: { lat: 41.85, lng: -87.65 },\n }\n );\n\n directionsRenderer.setMap(map);\n\n (document.getElementById(\"submit\") as HTMLElement).addEventListener(\n \"click\",\n () =\u003e {\n calculateAndDisplayRoute(directionsService, directionsRenderer);\n }\n );\n}\n\nfunction calculateAndDisplayRoute(\n directionsService: google.maps.DirectionsService,\n directionsRenderer: google.maps.DirectionsRenderer\n) {\n const waypts: google.maps.DirectionsWaypoint[] = [];\n const checkboxArray = document.getElementById(\n \"waypoints\"\n ) as HTMLSelectElement;\n\n for (let i = 0; i \u003c checkboxArray.length; i++) {\n if (checkboxArray.options[i].selected) {\n waypts.push({\n location: (checkboxArray[i] as HTMLOptionElement).value,\n stopover: true,\n });\n }\n }\n\n directionsService\n .route({\n origin: (document.getElementById(\"start\") as HTMLInputElement).value,\n destination: (document.getElementById(\"end\") as HTMLInputElement).value,\n waypoints: waypts,\n optimizeWaypoints: true,\n travelMode: google.maps.TravelMode.DRIVING,\n })\n .then((response) =\u003e {\n directionsRenderer.setDirections(response);\n\n const route = response.routes[0];\n const summaryPanel = document.getElementById(\n \"directions-panel\"\n ) as HTMLElement;\n\n summaryPanel.innerHTML = \"\";\n\n // For each route, display summary information.\n for (let i = 0; i \u003c route.legs.length; i++) {\n const routeSegment = i + 1;\n\n summaryPanel.innerHTML +=\n \"\u003cb\u003eRoute Segment: \" + routeSegment + \"\u003c/b\u003e\u003cbr\u003e\";\n summaryPanel.innerHTML += route.legs[i].start_address + \" to \";\n summaryPanel.innerHTML += route.legs[i].end_address + \"\u003cbr\u003e\";\n summaryPanel.innerHTML += route.legs[i].distance!.text + \"\u003cbr\u003e\u003cbr\u003e\";\n }\n })\n .catch((e) =\u003e window.alert(\"Directions request failed due to \" + status));\n}\n\ndeclare global {\n interface Window {\n initMap: () =\u003e void;\n }\n}\nwindow.initMap = initMap;https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/samples/directions-waypoints/index.ts#L8-L84\n```\n| **Note:** Read the [guide](/maps/documentation/javascript/using-typescript) on using TypeScript and Google Maps.\n\nJavaScript \n\n```javascript\nfunction initMap() {\n const directionsService = new google.maps.DirectionsService();\n const directionsRenderer = new google.maps.DirectionsRenderer();\n const map = new google.maps.Map(document.getElementById(\"map\"), {\n zoom: 6,\n center: { lat: 41.85, lng: -87.65 },\n });\n\n directionsRenderer.setMap(map);\n document.getElementById(\"submit\").addEventListener(\"click\", () =\u003e {\n calculateAndDisplayRoute(directionsService, directionsRenderer);\n });\n}\n\nfunction calculateAndDisplayRoute(directionsService, directionsRenderer) {\n const waypts = [];\n const checkboxArray = document.getElementById(\"waypoints\");\n\n for (let i = 0; i \u003c checkboxArray.length; i++) {\n if (checkboxArray.options[i].selected) {\n waypts.push({\n location: checkboxArray[i].value,\n stopover: true,\n });\n }\n }\n\n directionsService\n .route({\n origin: document.getElementById(\"start\").value,\n destination: document.getElementById(\"end\").value,\n waypoints: waypts,\n optimizeWaypoints: true,\n travelMode: google.maps.TravelMode.DRIVING,\n })\n .then((response) =\u003e {\n directionsRenderer.setDirections(response);\n\n const route = response.routes[0];\n const summaryPanel = document.getElementById(\"directions-panel\");\n\n summaryPanel.innerHTML = \"\";\n\n // For each route, display summary information.\n for (let i = 0; i \u003c route.legs.length; i++) {\n const routeSegment = i + 1;\n\n summaryPanel.innerHTML +=\n \"\u003cb\u003eRoute Segment: \" + routeSegment + \"\u003c/b\u003e\u003cbr\u003e\";\n summaryPanel.innerHTML += route.legs[i].start_address + \" to \";\n summaryPanel.innerHTML += route.legs[i].end_address + \"\u003cbr\u003e\";\n summaryPanel.innerHTML += route.legs[i].distance.text + \"\u003cbr\u003e\u003cbr\u003e\";\n }\n })\n .catch((e) =\u003e window.alert(\"Directions request failed due to \" + status));\n}\n\nwindow.initMap = initMap;https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/directions-waypoints/docs/index.js#L7-L64\n```\n| **Note:** The JavaScript is compiled from the TypeScript snippet.\n\nCSS \n\n```css\n/* Optional: Makes the sample page fill the window. */\nhtml,\nbody {\n height: 100%;\n margin: 0;\n padding: 0;\n}\n\n#container {\n height: 100%;\n display: flex;\n}\n\n#sidebar {\n flex-basis: 15rem;\n flex-grow: 1;\n padding: 1rem;\n max-width: 30rem;\n height: 100%;\n box-sizing: border-box;\n overflow: auto;\n}\n\n#map {\n flex-basis: 0;\n flex-grow: 4;\n height: 100%;\n}\n\n#directions-panel {\n margin-top: 10px;\n}\nhttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/directions-waypoints/docs/style.css#L7-L39\n```\n\nHTML \n\n```html\n\u003chtml\u003e\n \u003chead\u003e\n \u003ctitle\u003eWaypoints in Directions\u003c/title\u003e\n\n \u003clink rel=\"stylesheet\" type=\"text/css\" href=\"./style.css\" /\u003e\n \u003cscript type=\"module\" src=\"./index.js\"\u003e\u003c/script\u003e\n \u003c/head\u003e\n \u003cbody\u003e\n \u003cdiv id=\"container\"\u003e\n \u003cdiv id=\"map\"\u003e\u003c/div\u003e\n \u003cdiv id=\"sidebar\"\u003e\n \u003cdiv\u003e\n \u003cb\u003eStart:\u003c/b\u003e\n \u003cselect id=\"start\"\u003e\n \u003coption value=\"Halifax, NS\"\u003eHalifax, NS\u003c/option\u003e\n \u003coption value=\"Boston, MA\"\u003eBoston, MA\u003c/option\u003e\n \u003coption value=\"New York, NY\"\u003eNew York, NY\u003c/option\u003e\n \u003coption value=\"Miami, FL\"\u003eMiami, FL\u003c/option\u003e\n \u003c/select\u003e\n \u003cbr /\u003e\n \u003cb\u003eWaypoints:\u003c/b\u003e \u003cbr /\u003e\n \u003ci\u003e(Ctrl+Click or Cmd+Click for multiple selection)\u003c/i\u003e \u003cbr /\u003e\n \u003cselect multiple id=\"waypoints\"\u003e\n \u003coption value=\"montreal, quebec\"\u003eMontreal, QBC\u003c/option\u003e\n \u003coption value=\"toronto, ont\"\u003eToronto, ONT\u003c/option\u003e\n \u003coption value=\"chicago, il\"\u003eChicago\u003c/option\u003e\n \u003coption value=\"winnipeg, mb\"\u003eWinnipeg\u003c/option\u003e\n \u003coption value=\"fargo, nd\"\u003eFargo\u003c/option\u003e\n \u003coption value=\"calgary, ab\"\u003eCalgary\u003c/option\u003e\n \u003coption value=\"spokane, wa\"\u003eSpokane\u003c/option\u003e\n \u003c/select\u003e\n \u003cbr /\u003e\n \u003cb\u003eEnd:\u003c/b\u003e\n \u003cselect id=\"end\"\u003e\n \u003coption value=\"Vancouver, BC\"\u003eVancouver, BC\u003c/option\u003e\n \u003coption value=\"Seattle, WA\"\u003eSeattle, WA\u003c/option\u003e\n \u003coption value=\"San Francisco, CA\"\u003eSan Francisco, CA\u003c/option\u003e\n \u003coption value=\"Los Angeles, CA\"\u003eLos Angeles, CA\u003c/option\u003e\n \u003c/select\u003e\n \u003cbr /\u003e\n \u003cinput type=\"submit\" id=\"submit\" /\u003e\n \u003c/div\u003e\n \u003cdiv id=\"directions-panel\"\u003e\u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n\n \u003c!-- \n The `defer` attribute causes the script to execute after the full HTML\n document has been parsed. For non-blocking uses, avoiding race conditions,\n and consistent behavior across browsers, consider loading using Promises. See\n https://developers.google.com/maps/documentation/javascript/load-maps-js-api\n for more information.\n --\u003e\n \u003cscript\n src=\"https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly\"\n defer\n \u003e\u003c/script\u003e\n \u003c/body\u003e\n\u003c/html\u003ehttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/directions-waypoints/docs/index.html#L8-L66\n```\n\nTry Sample \n[JSFiddle.net](https://jsfiddle.net/gh/get/library/pure/googlemaps/js-samples/tree/master/dist/samples/directions-waypoints/jsfiddle) [Google Cloud Shell](https://ssh.cloud.google.com/cloudshell/editor?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Fgooglemaps%2Fjs-samples&cloudshell_git_branch=sample-directions-waypoints&cloudshell_tutorial=cloud_shell_instructions.md&cloudshell_workspace=.)\n\nClone Sample\n\n\nGit and Node.js are required to run this sample locally. Follow these [instructions](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) to install Node.js and NPM. The following commands clone, install dependencies and start the sample application. \n\n git clone -b sample-directions-waypoints https://github.com/googlemaps/js-samples.git\n cd js-samples\n npm i\n npm start\n\n\nOther samples can be tried by switching to any branch beginning with `sample-`\u003cvar translate=\"no\"\u003eSAMPLE_NAME\u003c/var\u003e. \n\n git checkout sample-\u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-nx\"\u003eSAMPLE_NAME\u003c/span\u003e\u003c/var\u003e\n npm i\n npm start"]]