Skip to content

Commit 6d5ce9f

Browse files
feat: Adds alternative routes sample (#750)
* feat: Adds new samples to support Routes GA launch. Change-Id: I7cc50235247b8f7787577d3a584107068866ebe5 * Clean up initMap by removing unused code Removed commented-out code for importing Map library. * Remove unused library variable definition. Co-authored-by: noelle-jung <[email protected]> * Update samples/routes-get-alternatives/style.css Co-authored-by: noelle-jung <[email protected]> * Update samples/routes-get-alternatives/index.ts Co-authored-by: noelle-jung <[email protected]> * Update samples/routes-get-alternatives/index.ts Co-authored-by: noelle-jung <[email protected]> --------- Co-authored-by: noelle-jung <[email protected]>
1 parent 5e83ed0 commit 6d5ce9f

File tree

6 files changed

+210
-0
lines changed

6 files changed

+210
-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: 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_alternatives]-->
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+
<gmp-map center="37.447646, -122.113878" zoom="10"></gmp-map>
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_alternatives]-->
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
"use strict";
2+
/*
3+
* @license
4+
* Copyright 2025 Google LLC. All Rights Reserved.
5+
* SPDX-License-Identifier: Apache-2.0
6+
*/
7+
// [START maps_routes_get_alternatives]
8+
// Initialize and add the map.
9+
let mapPolylines: google.maps.Polyline[] = [];
10+
const mapElement = document.querySelector('gmp-map') as google.maps.MapElement;
11+
let innerMap;
12+
13+
// Initialize and add the map.
14+
async function initMap() {
15+
// Request the needed libraries.
16+
await google.maps.importLibrary('maps') as google.maps.MapsLibrary;
17+
18+
innerMap = mapElement.innerMap;
19+
innerMap.setOptions({
20+
mapTypeControl: false,
21+
mapId: 'DEMO_MAP_ID',
22+
});
23+
24+
// Call the function after the map is loaded.
25+
google.maps.event.addListenerOnce(innerMap, 'idle', () => {
26+
getDirections();
27+
});
28+
29+
}
30+
31+
async function getDirections() {
32+
//@ts-ignore
33+
// Request the needed libraries.
34+
const [{ Route, RouteLabel }] = await Promise.all([
35+
google.maps.importLibrary('routes')
36+
]);
37+
// [START maps_routes_get_alternatives_request_full]
38+
// [START maps_routes_get_alternatives_request]
39+
// Build a request.
40+
const request = {
41+
origin: 'San Francisco, CA',
42+
destination: 'Sunset Dr Pacific Grove, CA 93950',
43+
travelMode: 'DRIVING',
44+
computeAlternativeRoutes: true,
45+
fields: ['path', 'routeLabels', 'viewport'], // Request the routeLabels field.
46+
};
47+
// [END maps_routes_get_alternatives_request]
48+
49+
// [START maps_routes_get_alternatives_compute]
50+
// Call computeRoutes to get the directions.
51+
const result = await Route.computeRoutes(request);
52+
if (!result.routes || result.routes.length === 0) {
53+
console.warn("No routes found");
54+
return;
55+
}
56+
57+
let primaryRoute;
58+
59+
for (const route of result.routes) {
60+
// Save the primary route for last so it's drawn on top.
61+
if (
62+
// Check for the default route.
63+
route.routeLabels?.includes(RouteLabel.DEFAULT_ROUTE)
64+
) {
65+
primaryRoute = route;
66+
} else {
67+
drawRoute(route, false);
68+
}
69+
}
70+
71+
if (primaryRoute) {
72+
drawRoute(primaryRoute, true);
73+
await primaryRoute.createWaypointAdvancedMarkers({ map: innerMap });
74+
innerMap.fitBounds(primaryRoute.viewport, 100);
75+
}
76+
// [END maps_routes_get_alternatives_compute]
77+
// [END maps_routes_get_alternatives_request_full]
78+
79+
// Display the raw JSON for the result in the console.
80+
console.log(`Response:\n ${JSON.stringify(result, null, 2)}`);
81+
}
82+
83+
function drawRoute(route, isPrimaryRoute) {
84+
mapPolylines = mapPolylines.concat(
85+
route.createPolylines({
86+
polylineOptions: isPrimaryRoute
87+
? { map: innerMap }
88+
: {
89+
map: innerMap,
90+
strokeColor: "#669DF6",
91+
strokeOpacity: 0.5,
92+
strokeWidth: 8,
93+
},
94+
colorScheme: innerMap.get("colorScheme"),
95+
}),
96+
);
97+
}
98+
99+
initMap();
100+
// [END maps_routes_get_alternatives]
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-alternatives",
3+
"version": "1.0.0",
4+
"scripts": {
5+
"build": "tsc && bash ../jsfiddle.sh routes-get-alternatives && bash ../app.sh routes-get-alternatives && bash ../docs.sh routes-get-alternatives && npm run build:vite --workspace=. && bash ../dist.sh routes-get-alternatives",
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: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
* @license
3+
* Copyright 2025 Google LLC. All Rights Reserved.
4+
* SPDX-License-Identifier: Apache-2.0
5+
*/
6+
/* [START maps_routes_get_alternatives] */
7+
/*
8+
* Always set the map height explicitly to define the size of the div element
9+
* that contains the map.
10+
*/
11+
#map {
12+
height: 100%;
13+
}
14+
15+
/*
16+
* Optional: Makes the sample page fill the window.
17+
*/
18+
html,
19+
body {
20+
height: 100%;
21+
margin: 0;
22+
padding: 0;
23+
}
24+
/* [END maps_routes_get_alternatives] */
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+
}

0 commit comments

Comments
 (0)