It's the 15th anniversary of Google Maps Platform - Check out the latest news and announcements

Draggable Directions

This example demonstrates the use of the DirectionsService object to fetch directions between draggable markers.

Read the documentation.

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("right-panel") as HTMLElement
  });

  directionsRenderer.addListener("directions_changed", () => {
    computeTotalDistance(directionsRenderer.getDirections());
  });

  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
    },
    (
      result: google.maps.DirectionsResult,
      status: google.maps.DirectionsStatus
    ) => {
      if (status === "OK") {
        display.setDirections(result);
      } else {
        alert("Could not display directions due to: " + status);
      }
    }
  );
}

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

  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";
}

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("right-panel")
  });
  directionsRenderer.addListener("directions_changed", () => {
    computeTotalDistance(directionsRenderer.getDirections());
  });
  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
    },
    (result, status) => {
      if (status === "OK") {
        display.setDirections(result);
      } else {
        alert("Could not display directions due to: " + status);
      }
    }
  );
}

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

  for (let i = 0; i < myroute.legs.length; i++) {
    total += myroute.legs[i].distance.value;
  }
  total = total / 1000;
  document.getElementById("total").innerHTML = total + " km";
}

CSS

#right-panel {
  font-family: "Roboto", "sans-serif";
  line-height: 30px;
  padding-left: 10px;
}

#right-panel select,
#right-panel input {
  font-size: 15px;
}

#right-panel select {
  width: 100%;
}

#right-panel i {
  font-size: 12px;
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#map {
  height: 100%;
  float: left;
  width: 63%;
  height: 100%;
}

#right-panel {
  float: right;
  width: 34%;
  height: 100%;
}

.panel {
  height: 100%;
  overflow: auto;
}

HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Draggable Directions</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=&v=weekly"
      defer
    ></script>
    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script src="./app.js"></script>
  </head>
  <body>
    <div id="map"></div>
    <div id="right-panel">
      <p>Total Distance: <span id="total"></span></p>
    </div>
  </body>
</html>

All

<!DOCTYPE html>
<html>
  <head>
    <title>Draggable Directions</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=&v=weekly"
      defer
    ></script>
    <style type="text/css">
      #right-panel {
        font-family: "Roboto", "sans-serif";
        line-height: 30px;
        padding-left: 10px;
      }

      #right-panel select,
      #right-panel input {
        font-size: 15px;
      }

      #right-panel select {
        width: 100%;
      }

      #right-panel i {
        font-size: 12px;
      }

      html,
      body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

      #map {
        height: 100%;
        float: left;
        width: 63%;
        height: 100%;
      }

      #right-panel {
        float: right;
        width: 34%;
        height: 100%;
      }

      .panel {
        height: 100%;
        overflow: auto;
      }
    </style>
    <script>
      "use strict";

      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("right-panel")
        });
        directionsRenderer.addListener("directions_changed", () => {
          computeTotalDistance(directionsRenderer.getDirections());
        });
        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
          },
          (result, status) => {
            if (status === "OK") {
              display.setDirections(result);
            } else {
              alert("Could not display directions due to: " + status);
            }
          }
        );
      }

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

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

        total = total / 1000;
        document.getElementById("total").innerHTML = total + " km";
      }
    </script>
  </head>
  <body>
    <div id="map"></div>
    <div id="right-panel">
      <p>Total Distance: <span id="total"></span></p>
    </div>
  </body>
</html>
"use strict"; 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("right-panel") }); directionsRenderer.addListener("directions_changed", () => { computeTotalDistance(directionsRenderer.getDirections()); }); 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 }, (result, status) => { if (status === "OK") { display.setDirections(result); } else { alert("Could not display directions due to: " + status); } } ); } function computeTotalDistance(result) { let total = 0; const myroute = result.routes[0]; for (let i = 0; i < myroute.legs.length; i++) { total += myroute.legs[i].distance.value; } total = total / 1000; document.getElementById("total").innerHTML = total + " km"; }
#right-panel { font-family: "Roboto", "sans-serif"; line-height: 30px; padding-left: 10px; } #right-panel select, #right-panel input { font-size: 15px; } #right-panel select { width: 100%; } #right-panel i { font-size: 12px; } html, body { height: 100%; margin: 0; padding: 0; } #map { height: 100%; float: left; width: 63%; height: 100%; } #right-panel { float: right; width: 34%; height: 100%; } .panel { height: 100%; overflow: auto; }
<!DOCTYPE html> <html> <head> <title>Draggable Directions</title> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBIwzALxUPNbatRBj3Xi1Uhp0fFzwWNBkE&callback=initMap&libraries=&v=weekly" defer ></script> <!-- jsFiddle will insert css and js --> </head> <body> <div id="map"></div> <div id="right-panel"> <p>Total Distance: <span id="total"></span></p> </div> </body> </html>

Create a starter application from sample

A skeleton starter application using TypeScript, Webpack, and Babel can be generated from this sample using one of the methods below.

Run Locally

Node.js is required to run this sample locally. Follow these instructions to install Node.js and NPM.

npm i -g '@googlemaps/js-samples'
googlemaps-js-samples init directions-draggable DESTINATION_FOLDER

Run in Google Cloud Shell

Google Cloud Shell is an interactive shell environment for Google Cloud Platform that makes it easy for you to learn and experiment with GCP and manage your projects and resources from your web browser.

Run in Cloud Shell