functioninitMap():void{constmap=newgoogle.maps.Map(document.getElementById("map")asHTMLElement,{zoom:4,center:{lat:-24.345,lng:134.46},// Australia.});constdirectionsService=newgoogle.maps.DirectionsService();constdirectionsRenderer=newgoogle.maps.DirectionsRenderer({draggable:true,map,panel:document.getElementById("panel")asHTMLElement,});directionsRenderer.addListener("directions_changed",()=>{constdirections=directionsRenderer.getDirections();if(directions){computeTotalDistance(directions);}});displayRoute("Perth, WA","Sydney, NSW",directionsService,directionsRenderer);}functiondisplayRoute(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);});}functioncomputeTotalDistance(result:google.maps.DirectionsResult){lettotal=0;constmyroute=result.routes[0];if(!myroute){return;}for(leti=0;i < myroute.legs.length;i++){total+=myroute.legs[i]!.distance!.value;}total=total/1000;(document.getElementById("total")asHTMLElement).innerHTML=total+" km";}declareglobal{interfaceWindow{initMap:()=>void;}}window.initMap=initMap;
functioninitMap(){constmap=newgoogle.maps.Map(document.getElementById("map"),{zoom:4,center:{lat:-24.345,lng:134.46},// Australia.});constdirectionsService=newgoogle.maps.DirectionsService();constdirectionsRenderer=newgoogle.maps.DirectionsRenderer({draggable:true,map,panel:document.getElementById("panel"),});directionsRenderer.addListener("directions_changed",()=>{constdirections=directionsRenderer.getDirections();if(directions){computeTotalDistance(directions);}});displayRoute("Perth, WA","Sydney, NSW",directionsService,directionsRenderer,);}functiondisplayRoute(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);});}functioncomputeTotalDistance(result){lettotal=0;constmyroute=result.routes[0];if(!myroute){return;}for(leti=0;i < myroute.legs.length;i++){total+=myroute.legs[i].distance.value;}total=total/1000;document.getElementById("total").innerHTML=total+" km";}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%;}
<html> <head> <title>Draggable Directions</title> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <div id="container"> <div id="map"></div> <div id="sidebar"> <p>Total Distance: <span id="total"></span></p> <div id="panel"></div> </div> </div> <!-- The `defer` attribute causes the script to execute after the full HTML document has been parsed. For non-blocking uses, avoiding race conditions, and consistent behavior across browsers, consider loading using Promises. See https://developers.google.com/maps/documentation/javascript/load-maps-js-api for more information. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly" defer ></script> </body> </html>
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.
[[["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-20 UTC."],[[["\u003cp\u003eThis example shows how to use the \u003ccode\u003eDirectionsService\u003c/code\u003e to get directions between two points, with draggable markers.\u003c/p\u003e\n"],["\u003cp\u003eUsers can drag the route to change it, and the total distance will be updated automatically.\u003c/p\u003e\n"],["\u003cp\u003eThe example uses waypoints to specify intermediate locations on the route.\u003c/p\u003e\n"],["\u003cp\u003eIt's implemented in both TypeScript and JavaScript, with code snippets provided.\u003c/p\u003e\n"],["\u003cp\u003eThe example also showcases the integration of Google Maps with a simple HTML, CSS, and JavaScript webpage.\u003c/p\u003e\n"]]],["The code initializes a Google Map and uses `DirectionsService` to calculate routes between \"Perth, WA\" and \"Sydney, NSW,\" with \"Adelaide, SA\" and \"Broken Hill, NSW\" as waypoints, in driving mode, avoiding tolls. `DirectionsRenderer` displays the route on the map and allows dragging. The code also computes and displays the total distance of the route and updates when directions are changed by using the `directions_changed` event. The associated CSS and HTML files configure the layout for the map and side panel.\n"],null,["This example demonstrates the use of the `DirectionsService` object\nto fetch directions between draggable markers.\n\nRead the\n[documentation](/maps/documentation/javascript/directions#DraggableDirections). \n\nTypeScript \n\n```typescript\nfunction initMap(): void {\n const map = new google.maps.Map(\n document.getElementById(\"map\") as HTMLElement,\n {\n zoom: 4,\n center: { lat: -24.345, lng: 134.46 }, // Australia.\n }\n );\n\n const directionsService = new google.maps.DirectionsService();\n const directionsRenderer = new google.maps.DirectionsRenderer({\n draggable: true,\n map,\n panel: document.getElementById(\"panel\") as HTMLElement,\n });\n\n directionsRenderer.addListener(\"directions_changed\", () =\u003e {\n const directions = directionsRenderer.getDirections();\n\n if (directions) {\n computeTotalDistance(directions);\n }\n });\n\n displayRoute(\n \"Perth, WA\",\n \"Sydney, NSW\",\n directionsService,\n directionsRenderer\n );\n}\n\nfunction displayRoute(\n origin: string,\n destination: string,\n service: google.maps.DirectionsService,\n display: google.maps.DirectionsRenderer\n) {\n service\n .route({\n origin: origin,\n destination: destination,\n waypoints: [\n { location: \"Adelaide, SA\" },\n { location: \"Broken Hill, NSW\" },\n ],\n travelMode: google.maps.TravelMode.DRIVING,\n avoidTolls: true,\n })\n .then((result: google.maps.DirectionsResult) =\u003e {\n display.setDirections(result);\n })\n .catch((e) =\u003e {\n alert(\"Could not display directions due to: \" + e);\n });\n}\n\nfunction computeTotalDistance(result: google.maps.DirectionsResult) {\n let total = 0;\n const myroute = result.routes[0];\n\n if (!myroute) {\n return;\n }\n\n for (let i = 0; i \u003c myroute.legs.length; i++) {\n total += myroute.legs[i]!.distance!.value;\n }\n\n total = total / 1000;\n (document.getElementById(\"total\") as HTMLElement).innerHTML = total + \" km\";\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-draggable/index.ts#L8-L86\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 map = new google.maps.Map(document.getElementById(\"map\"), {\n zoom: 4,\n center: { lat: -24.345, lng: 134.46 }, // Australia.\n });\n const directionsService = new google.maps.DirectionsService();\n const directionsRenderer = new google.maps.DirectionsRenderer({\n draggable: true,\n map,\n panel: document.getElementById(\"panel\"),\n });\n\n directionsRenderer.addListener(\"directions_changed\", () =\u003e {\n const directions = directionsRenderer.getDirections();\n\n if (directions) {\n computeTotalDistance(directions);\n }\n });\n displayRoute(\n \"Perth, WA\",\n \"Sydney, NSW\",\n directionsService,\n directionsRenderer,\n );\n}\n\nfunction displayRoute(origin, destination, service, display) {\n service\n .route({\n origin: origin,\n destination: destination,\n waypoints: [\n { location: \"Adelaide, SA\" },\n { location: \"Broken Hill, NSW\" },\n ],\n travelMode: google.maps.TravelMode.DRIVING,\n avoidTolls: true,\n })\n .then((result) =\u003e {\n display.setDirections(result);\n })\n .catch((e) =\u003e {\n alert(\"Could not display directions due to: \" + e);\n });\n}\n\nfunction computeTotalDistance(result) {\n let total = 0;\n const myroute = result.routes[0];\n\n if (!myroute) {\n return;\n }\n\n for (let i = 0; i \u003c myroute.legs.length; i++) {\n total += myroute.legs[i].distance.value;\n }\n\n total = total / 1000;\n document.getElementById(\"total\").innerHTML = total + \" km\";\n}\n\nwindow.initMap = initMap;https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/directions-draggable/docs/index.js#L7-L70\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}\nhttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/directions-draggable/docs/style.css#L7-L35\n```\n\nHTML \n\n```html\n\u003chtml\u003e\n \u003chead\u003e\n \u003ctitle\u003eDraggable 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 \u003cp\u003eTotal Distance: \u003cspan id=\"total\"\u003e\u003c/span\u003e\u003c/p\u003e\n \u003cdiv id=\"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-draggable/docs/index.html#L8-L36\n```\n\nTry Sample \n[JSFiddle.net](https://jsfiddle.net/gh/get/library/pure/googlemaps/js-samples/tree/master/dist/samples/directions-draggable/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-draggable&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-draggable 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"]]