routes-compute-routes

Sample code supporting Google Maps Platform JavaScript API documentation. author(s): Geo Developer IX Documentation Team

HTML

<!doctype html>
<!--
 @license
 Copyright 2025 Google LLC. All Rights Reserved.
 SPDX-License-Identifier: Apache-2.0
-->

<html>
  <head>
    <title>Get routes</title>

    <script>
      // prettier-ignore
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
            });
    </script>
  </head>

  <body>
    <div class="main-content">
      <div class="alert" id="alert">
        <p>error</p>
        <button class="button-secondary close">&times;</button>
      </div>
      <div class="control-panel">
        <form id="compute-routes-form">
          <section>
            <h2>Input locations</h2>
            <div class="row">
              <div class="location-input-wrapper">
                <label class="text">Origin*</label>
                <div id="origin-input"></div>
              </div>
              <div class="heading-wrapper">
                <label for="heading_org" class="text">Heading</label>
                <input
                  type="text"
                  id="heading_org"
                  name="heading_org"
                  value="" />
              </div>
            </div>
            <div class="row">
              <div class="location-options-wrapper">
                <input
                  type="checkbox"
                  id="origin_stopover"
                  name="origin_stopover" />
                <label...

CSS

/*
 * @license
 * Copyright 2025 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

html,
body {
  height: 100%;
  font-size: 100%;
  font-family: 'Google Sans', sans-serif;
  margin: 0;
  background-color: #fff;
}

* {
  box-sizing: border-box;
}

h2,
h3 {
  color: #222;
  font-style: normal;
  font-weight: normal;
  line-height: 1.4;
  margin-bottom: 0.5rem;
  margin-top: 0.2rem;
}

h2 {
  font-weight: bold;
  font-size: 1rem;
}

h3 {
  font-size: 0.8rem;
}

p {
  font-size: 0.8rem;
  margin: 0 0 0.6rem 0;
}

label {
  color: #4d4d4d;
  display: inline-block;
  margin: 0;
  position: relative;
  z-index: 2;
  font-size: 0.875rem;
}

input[type='text'] {
  height: 50px;
  width: 100%;
  padding: 0.5rem;
  border-radius: 4px;
  border: 1px solid #ccc;
}

ul {
  list-style: none;
  padding-inline-start: 0.25rem;
}

select {
  appearance: none;
  background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgeD0iMTJweCIgeT0iMHB4IiB3aWR0aD0iMjRweCIgaGVpZ2h0PSIzcHgiIHZpZXdCb3g9IjAgMCA2IDMiIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDYgMyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+PHBvbHlnb24gcG9pbnRzPSI1Ljk5MiwwIDIuOTkyLDMgLTAuMDA4LDAgIi8+PC9zdmc+);
  background-position: 100% center;
  background-repeat: no-repeat;
  padding-right: 1.5rem;

  &:disabled {
    background-color: #ddd;
    cursor: default;
  }

  &[multiple] {
    height: auto;
  }
}

select,
input[type='datetime-local'] {
  height: 2.3125rem;
  width: 100%;
  border-style: solid;
  border-width: 1px;
  border-color: #ccc;
  border-radius: 4px;
  padding: 0.3rem;
  font-family: inherit;
  font-size: 0.8rem;
}

button {
  min-height: 3rem;
  min-width: 3rem;
  cursor: pointer;
  font-family: inherit;
  font-weight: normal;
  font-size: 0.875rem;
  line-height: normal;
  padding: 0 1.5rem;
  position: relative;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  border-radius: 4px;
  transition:
    background-color...

JavaScript

'use strict';
/*
 * @license
 * Copyright 2025 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

let markers = [];
let polylines = [];

const originAutocompleteSelection = {
  predictionText: null,
  location: null,
};
const destinationAutocompleteSelection = {
  predictionText: null,
  location: null,
};

async function init() {
  const [
    { InfoWindow },
    { AdvancedMarkerElement },
    { PlaceAutocompleteElement },
    { ComputeRoutesExtraComputation, ReferenceRoute, Route, RouteLabel },
  ] = await Promise.all([
    google.maps.importLibrary('maps'),
    google.maps.importLibrary('marker'),
    google.maps.importLibrary('places'),
    google.maps.importLibrary('routes'),
  ]);

  const map = document.getElementById('map');

  attachSubmitListener();
  initializeLocationInputs();
  attachMapClickListener();
  attachTravelModeListener();
  attachAlertWindowListener();
  attachDepartureTimeListener();

  function attachSubmitListener() {
    const computeRoutesForm = document.getElementById('compute-routes-form');

    computeRoutesForm.addEventListener('submit', (event) => {
      event.preventDefault();
      void sendRequest(new FormData(computeRoutesForm));
    });
  }

  async function sendRequest(formData) {
    clearMap();

    try {
      const { routes } = await Route.computeRoutes(
        buildComputeRoutesJsRequest(formData)
      );

      if (!routes) {
        console.log('No routes returned.');
        return;
      }

      console.log('Routes:');
      routes.forEach((route) => {
        console.log(route.toJSON());
      });

      await Promise.all(
        routes.map((route) =>
          drawRoute(
            route,
            !!route.routeLabels?.includes(RouteLabel.DEFAULT_ROUTE)
          )
        )
      );
    } catch (error) {
      console.error(error);
      setErrorMessage(error.message || 'Unknown error.');
    }
  }

  function buildComputeRoutesJsRequest(formData) {
    const travelMode =...