Skip to content

Commit 1219a55

Browse files
feat: Creates three new Routes library doc samples. (#728)
* feat: Adds multiple Routes library doc demos. Change-Id: Icb584fcf362f89b74437fae0ae00f6ce4c444b21 * Remove commented code Removed a block of commented code that was left in by mistake. * Rename directions panel container to directions container * Refactor map initialization and directions panel * Incorporated review comments Updated comments and cleaned up request structure. * Update samples/routes-get-directions-panel/index.html Co-authored-by: noelle-jung <[email protected]> * Update samples/routes-get-directions-panel/index.ts Co-authored-by: noelle-jung <[email protected]> * Clean up CSS spacing Removed commented-out CSS for map height and adjusted formatting. * Refactor library imports to use Promise.all * Optimize Google Maps library imports Refactor library imports to use Promise.all for better performance. * Remove commented portion Refactor library imports for Google Maps API to use Promise.all for improved performance. * Remove empty line in style.css * Fix import type for routes library in initMap * Fix type for routes library import * Refactor fetchFields calls to use Promise.all --------- Co-authored-by: noelle-jung <[email protected]>
1 parent 41da486 commit 1219a55

File tree

18 files changed

+796
-0
lines changed

18 files changed

+796
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Google Maps JavaScript Sample
2+
3+
This sample is generated from @googlemaps/js-samples located at
4+
https://github.com/googlemaps-samples/js-api-samples.
5+
6+
## Setup
7+
8+
### Before starting run:
9+
10+
`$npm i`
11+
12+
### Run an example on a local web server
13+
14+
First `cd` to the folder for the sample to run, then:
15+
16+
`$npm start`
17+
18+
### Build an individual example
19+
20+
From `samples/`:
21+
22+
`$npm run build --workspace=sample-name/`
23+
24+
### Build all of the examples.
25+
26+
From `samples/`:
27+
`$npm run build-all`
28+
29+
## Feedback
30+
31+
For feedback related to this sample, please open a new issue on
32+
[GitHub](https://github.com/googlemaps-samples/js-api-samples/issues).
33+
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<!doctype html>
2+
<!--
3+
@license
4+
Copyright 2025 Google LLC. All Rights Reserved.
5+
SPDX-License-Identifier: Apache-2.0
6+
-->
7+
<!--[START maps_routes_get_directions_panel]-->
8+
<html>
9+
10+
<head>
11+
<title>Get directions with step by step panel</title>
12+
13+
<link rel="stylesheet" type="text/css" href="./style.css" />
14+
<script type="module" src="./index.js"></script>
15+
</head>
16+
17+
<body>
18+
<div class="container">
19+
<div class="map-container">
20+
<div id="map"></div>
21+
</div>
22+
<div class="directions-container">
23+
<div id="directions">
24+
<p>Directions</p>
25+
</div>
26+
</div>
27+
</div>
28+
<!-- prettier-ignore -->
29+
<script>(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)) })
30+
({ key: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "beta" });</script>
31+
</body>
32+
33+
</html>
34+
<!--[END maps_routes_get_directions_panel]-->
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
/*
2+
* @license
3+
* Copyright 2025 Google LLC. All Rights Reserved.
4+
* SPDX-License-Identifier: Apache-2.0
5+
*/
6+
// [START maps_routes_get_directions_panel]
7+
// Initialize and add the map.
8+
let map;
9+
let mapPolylines: google.maps.Polyline[] = [];
10+
let markers: google.maps.marker.AdvancedMarkerElement[] = [];
11+
let center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA
12+
13+
// Initialize and add the map.
14+
async function initMap(): Promise<void> {
15+
// Request the needed libraries.
16+
//@ts-ignore
17+
const [{Map}, {Route}] = await Promise.all([
18+
google.maps.importLibrary('maps') as Promise<google.maps.MapsLibrary>,
19+
google.maps.importLibrary('routes') as Promise<google.maps.RoutesLibrary>
20+
]);
21+
22+
map = new Map(document.getElementById("map") as HTMLElement, {
23+
zoom: 12,
24+
center,
25+
mapTypeControl: false,
26+
mapId: 'DEMO_MAP_ID',
27+
});
28+
29+
// Define a simple directions request.
30+
const request = {
31+
origin: 'Mountain View, CA',
32+
destination: 'Sausalito, CA',
33+
intermediates: ['Half Moon Bay, CA', 'Pacifica Esplanade Beach'],
34+
travelMode: 'DRIVING',
35+
fields: ['legs', 'path'],
36+
};
37+
38+
// Call computeRoutes to get the directions.
39+
const { routes } = await Route.computeRoutes(request);
40+
41+
// Display the raw JSON for the result in the console.
42+
console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`);
43+
44+
// Use createPolylines to create polylines for the route.
45+
mapPolylines = routes[0].createPolylines();
46+
// Add polylines to the map.
47+
mapPolylines.forEach((polyline) => polyline.setMap(map));
48+
49+
fitMapToPath(routes[0].path!);
50+
51+
// Add markers to all the points.
52+
const markers = await routes[0].createWaypointAdvancedMarkers({ map });
53+
54+
// [START maps_routes_get_directions_panel_steps]
55+
// Render navigation instructions
56+
const directionsPanel = document.getElementById("directions");
57+
58+
if (!routes || routes.length === 0) {
59+
if (directionsPanel) {
60+
directionsPanel.textContent = "No routes available.";
61+
}
62+
return;
63+
}
64+
65+
const route = routes[0];
66+
if (!route.legs || route.legs.length === 0) {
67+
if (directionsPanel) {
68+
directionsPanel.textContent = "The route has no legs.";
69+
}
70+
return;
71+
}
72+
73+
const fragment = document.createDocumentFragment();
74+
75+
route.legs.forEach((leg, index) => {
76+
const legContainer = document.createElement("div");
77+
legContainer.className = "directions-leg";
78+
79+
// Leg Title
80+
const legTitleElement = document.createElement("h3");
81+
legTitleElement.textContent = `Leg ${index + 1} of ${route.legs.length}`;
82+
legContainer.appendChild(legTitleElement);
83+
84+
if (leg.steps && leg.steps.length > 0) {
85+
// Add steps to an ordered list
86+
const stepsList = document.createElement("ol");
87+
stepsList.className = "directions-steps";
88+
89+
leg.steps.forEach((step, stepIndex) => {
90+
const stepItem = document.createElement("li");
91+
stepItem.className = "direction-step";
92+
93+
const directionWrapper = document.createElement("div");
94+
directionWrapper.className = "direction";
95+
96+
// Maneuver
97+
if (step.maneuver) {
98+
const maneuverNode = document.createElement("p");
99+
maneuverNode.textContent = step.maneuver;
100+
maneuverNode.className = "maneuver";
101+
directionWrapper.appendChild(maneuverNode);
102+
}
103+
104+
// Distance and Duration
105+
if (step.localizedValues) {
106+
const distanceNode = document.createElement("p");
107+
distanceNode.textContent = `${step.localizedValues.distance} (${step.localizedValues.staticDuration})`;
108+
distanceNode.className = "distance";
109+
directionWrapper.appendChild(distanceNode);
110+
}
111+
112+
// Instructions
113+
if (step.instructions) {
114+
const instructionsNode = document.createElement("p");
115+
instructionsNode.textContent = step.instructions;
116+
instructionsNode.className = "instruction";
117+
directionWrapper.appendChild(instructionsNode);
118+
}
119+
120+
stepItem.appendChild(directionWrapper);
121+
stepsList.appendChild(stepItem);
122+
});
123+
legContainer.appendChild(stepsList);
124+
}
125+
126+
fragment.appendChild(legContainer);
127+
directionsPanel?.appendChild(fragment);
128+
});
129+
130+
}
131+
// [END maps_routes_get_directions_panel_steps]
132+
// Helper function to fit the map to the path.
133+
async function fitMapToPath(path) {
134+
const { LatLngBounds } = await google.maps.importLibrary('core') as google.maps.CoreLibrary;
135+
const bounds = new LatLngBounds();
136+
path.forEach((point) => {
137+
bounds.extend(point);
138+
});
139+
map.fitBounds(bounds);
140+
}
141+
142+
initMap();
143+
// [END maps_routes_get_directions_panel]
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"name": "@js-api-samples/routes-get-directions-panel",
3+
"version": "1.0.0",
4+
"scripts": {
5+
"build": "tsc && bash ../jsfiddle.sh routes-get-directions-panel && bash ../app.sh routes-get-directions-panel && bash ../docs.sh routes-get-directions-panel && npm run build:vite --workspace=. && bash ../dist.sh routes-get-directions-panel",
6+
"test": "tsc && npm run build:vite --workspace=.",
7+
"start": "tsc && vite build --base './' && vite",
8+
"build:vite": "vite build --base './'",
9+
"preview": "vite preview"
10+
},
11+
"dependencies": {
12+
13+
}
14+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
* @license
3+
* Copyright 2025 Google LLC. All Rights Reserved.
4+
* SPDX-License-Identifier: Apache-2.0
5+
*/
6+
/* [START maps_routes_get_directions_panel] */
7+
/*
8+
* Always set the map height explicitly to define the size of the div element
9+
* that contains the map.
10+
*/
11+
.container {
12+
display: flex;
13+
flex-direction: row;
14+
height: 100%;
15+
width: 100%;
16+
}
17+
18+
.directions-panel-container, .map-container {
19+
height: 100%;
20+
width: 50%;
21+
font-family: monospace;
22+
}
23+
24+
.directions-panel-container {
25+
overflow-y: auto;
26+
}
27+
28+
/*
29+
* Always set the map height explicitly to define the size of the div element
30+
* that contains the map.
31+
*/
32+
#map {
33+
height: 100%;
34+
}
35+
36+
.direction {
37+
display: flex;
38+
flex-direction: row;
39+
gap: 1em;
40+
}
41+
42+
.maneuver {
43+
width: 25%
44+
}
45+
46+
.distance {
47+
width: 25%
48+
}
49+
50+
.instruction {
51+
width: 50%;
52+
}
53+
54+
/*
55+
* Optional: Makes the sample page fill the window.
56+
*/
57+
html,
58+
body {
59+
height: 100%;
60+
margin: 0;
61+
padding: 0;
62+
}
63+
/* [END maps_routes_get_directions_panel] */
64+
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"compilerOptions": {
3+
"module": "esnext",
4+
"target": "esnext",
5+
"strict": true,
6+
"noImplicitAny": false,
7+
"lib": [
8+
"es2015",
9+
"esnext",
10+
"es6",
11+
"dom",
12+
"dom.iterable"
13+
],
14+
"moduleResolution": "Node",
15+
"jsx": "preserve"
16+
}
17+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Google Maps JavaScript Sample
2+
3+
This sample is generated from @googlemaps/js-samples located at
4+
https://github.com/googlemaps-samples/js-api-samples.
5+
6+
## Setup
7+
8+
### Before starting run:
9+
10+
`$npm i`
11+
12+
### Run an example on a local web server
13+
14+
First `cd` to the folder for the sample to run, then:
15+
16+
`$npm start`
17+
18+
### Build an individual example
19+
20+
From `samples/`:
21+
22+
`$npm run build --workspace=sample-name/`
23+
24+
### Build all of the examples.
25+
26+
From `samples/`:
27+
`$npm run build-all`
28+
29+
## Feedback
30+
31+
For feedback related to this sample, please open a new issue on
32+
[GitHub](https://github.com/googlemaps-samples/js-api-samples/issues).
33+
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<!doctype html>
2+
<!--
3+
@license
4+
Copyright 2025 Google LLC. All Rights Reserved.
5+
SPDX-License-Identifier: Apache-2.0
6+
-->
7+
<!--[START maps_routes_get_directions]-->
8+
<html>
9+
<head>
10+
<title>Get directions</title>
11+
12+
<link rel="stylesheet" type="text/css" href="./style.css" />
13+
<script type="module" src="./index.js"></script>
14+
</head>
15+
<body>
16+
<div id="map"></div>
17+
<!-- prettier-ignore -->
18+
<script>(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))})
19+
({key: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "beta"});</script>
20+
</body>
21+
</html>
22+
<!--[END maps_routes_get_directions]-->

0 commit comments

Comments
 (0)