Waypoints in Directions (Official)

Sample code for Google Maps Platform JavaScript API author(s): Justin Poehnelt

by Annie Lagang

HTML

<!DOCTYPE html>
<!--
 @license
 Copyright 2019 Google LLC. All Rights Reserved.
 SPDX-License-Identifier: Apache-2.0
-->
<html>
  <head>
    <title>Waypoints in Directions</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <!-- jsFiddle will insert css and js -->
  </head>
  <body>
    <div id="container">
      <div id="map"></div>
      <div id="sidebar">
        <div>
          <b>Start:</b>
          <select id="start">
            <option value="50.401217,-4.093757">LatLng 50.400392, -4.092913</option>
          </select>
          <br />
          <b>Waypoints:</b> <br />
          <i>(Ctrl+Click or Cmd+Click for multiple selection)</i> <br />
          <select multiple id="waypoints">
            <option value="50.403018,-4.099785">LatLng 50.403018, -4.099785</option>
            <option value="50.400305,-4.093425">LatLng 50.400305, -4.093425</option>
          </select>
          <br />
          <b>End:</b>
          <select id="end">
            <option value="50.400392,-4.092913">LatLng 50.401217, -4.093757</option>
          </select>
          <br />
          <input type="submit" id="submit" />
          <p>Total Distance: <span id="total"></span></p>
        </div>
        <div id="directions-panel"></div>
      </div>
    </div>

    <!-- 
      The `defer` attribute causes the callback 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>

CSS

/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
/* 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;
}

JavaScript

/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
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: 53.991281, lng: -2.479680 }, // UK location
  });

  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) {
      let latLngArray = checkboxArray[i].value.split(',');
      let lat = parseFloat(latLngArray[0]);
      let lng = parseFloat(latLngArray[1]);
    
      waypts.push({
        location: new google.maps.LatLng(lat, lng),
        stopover: true,
      });
    }
  }
  
  console.log(waypts);

	let startArray = document.getElementById("start").value.split(',');
  let startLat = parseFloat(startArray[0]);
  let startLng = parseFloat(startArray[1]);
  
  let endArray = document.getElementById("end").value.split(',');
  let endLat = parseFloat(endArray[0]);
  let endLng = parseFloat(endArray[1]);
  
  console.log('start array', startArray);
  console.log('end array', endArray);
  console.log('start LatLng obj', new google.maps.LatLng(startLat, startLng));
  console.log('end LatLng obj', new google.maps.LatLng(endLat, endLng));

  directionsService
    .route({
      origin: new google.maps.LatLng(new google.maps.LatLng(startLat, startLng)),
      destination: new google.maps.LatLng(new google.maps.LatLng(endLat, endLng)),
      waypoints: waypts,
      //optimizeWaypoints: true,
      travelMode: google.maps.TravelMode.DRIVING,
   ...