Directions Service (Complex)

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>Directions Service (Complex)</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <!-- jsFiddle will insert css and js -->
  </head>
  <body>
    <div id="floating-panel">
      <b>Start: </b>
      <select id="start">
        <option value="penn station, new york, ny">Penn Station</option>
        <option value="grand central station, new york, ny">
          Grand Central Station
        </option>
        <option value="625 8th Avenue, New York, NY, 10018">
          Port Authority Bus Terminal
        </option>
        <option value="staten island ferry terminal, new york, ny">
          Staten Island Ferry Terminal
        </option>
        <option value="101 E 125th Street, New York, NY">
          Harlem - 125th St Station
        </option>
      </select>
      <b>End: </b>
      <select id="end">
        <option value="260 Broadway New York NY 10007">City Hall</option>
        <option value="W 49th St & 5th Ave, New York, NY 10020">
          Rockefeller Center
        </option>
        <option value="moma, New York, NY">MOMA</option>
        <option value="350 5th Ave, New York, NY, 10118">
          Empire State Building
        </option>
        <option value="253 West 125th Street, New York, NY">
          Apollo 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 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.
     ...

CSS

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

JavaScript

/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
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 existing 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,
      travelMode: google.maps.TravelMode.WALKING,
    })
    .then((result) => {
      // Route the directions and pass the response to a function to create
      // markers for each step.
     ...