Skip to content

Commit f0315d6

Browse files
feat: Adds sample to demonstrate customizing route markers. (#765)
* feat: Adds sample to demonstrate custom markers. Change-Id: Ia545556f6c9cd9564ba486f9af9942cac3c47522 * fix: properly closes region tag Oops! * remove duplicate comment Co-authored-by: noelle-jung <[email protected]> * removed unnecessary code for markers Co-authored-by: noelle-jung <[email protected]> --------- Co-authored-by: noelle-jung <[email protected]>
1 parent 9bbfa6b commit f0315d6

File tree

6 files changed

+234
-0
lines changed

6 files changed

+234
-0
lines changed

samples/routes-markers/README.md

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+

samples/routes-markers/index.html

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_markers]-->
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="12"></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_markers]-->

samples/routes-markers/index.ts

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
/*
2+
* @license
3+
* Copyright 2025 Google LLC. All Rights Reserved.
4+
* SPDX-License-Identifier: Apache-2.0
5+
*/
6+
// [START maps_routes_markers]
7+
let mapPolylines: google.maps.Polyline[] = [];
8+
const mapElement = document.querySelector('gmp-map') as google.maps.MapElement;
9+
let innerMap;
10+
11+
// Initialize and add the map.
12+
async function initMap() {
13+
// Request the needed libraries.
14+
await google.maps.importLibrary('maps');
15+
16+
innerMap = await mapElement.innerMap;
17+
innerMap.setOptions({
18+
mapTypeControl: false,
19+
mapId: 'DEMO_MAP_ID',
20+
});
21+
22+
// Call the function after the map is loaded.
23+
google.maps.event.addListenerOnce(innerMap, 'idle', () => {
24+
getDirections();
25+
});
26+
}
27+
28+
async function getDirections() {
29+
//@ts-ignore
30+
// Request the needed libraries.
31+
const [{ Route }, { PinElement }] = await Promise.all([
32+
google.maps.importLibrary('routes'),
33+
google.maps.importLibrary('marker'),
34+
]);
35+
36+
// [START maps_routes_markers_request_full]
37+
// [START maps_routes_markers_request]
38+
// Define routes request with an intermediate stop.
39+
const request = {
40+
origin: 'Parking lot, Christmas Tree Point Rd, San Francisco, CA 94131',
41+
destination: '100 Spinnaker Dr, Sausalito, CA 94965', // We're having a yummy lunch!
42+
intermediates: [{ location: '300 Finley Rd San Francisco, CA 94129' }], // But first, we golf!
43+
travelMode: 'DRIVING',
44+
fields: ['path', 'legs', 'viewport'],
45+
};
46+
// [END maps_routes_markers_request]
47+
48+
// Call computeRoutes to get the directions.
49+
const result = await Route.computeRoutes(request);
50+
if (!result.routes || result.routes.length === 0) {
51+
console.warn("No routes found");
52+
return;
53+
}
54+
// [END maps_routes_markers_request_full]
55+
56+
// [START maps_routes_markers_style_maker]
57+
// Alter style based on marker index.
58+
function markerOptionsMaker(
59+
defaultOptions: google.maps.marker.AdvancedMarkerElementOptions,
60+
//@ts-ignore
61+
waypointMarkerDetails: google.maps.routes.WaypointMarkerDetails
62+
) {
63+
const { index, totalMarkers, leg } = waypointMarkerDetails;
64+
65+
// Style the origin waypoint.
66+
if (index === 0) {
67+
return {
68+
...defaultOptions,
69+
map: innerMap,
70+
content: new PinElement({
71+
glyph: (index + 1).toString(),
72+
glyphColor: 'white',
73+
background: 'green',
74+
borderColor: 'green',
75+
}).element
76+
}
77+
}
78+
79+
// Style all intermediate waypoints.
80+
if (!(index === 0 || index === totalMarkers - 1)) {
81+
return {
82+
...defaultOptions,
83+
map: innerMap,
84+
content: new PinElement({
85+
glyph: (index + 1).toString(),
86+
glyphColor: 'white',
87+
background: 'blue',
88+
borderColor: 'blue',
89+
}).element
90+
}
91+
}
92+
93+
// Style the destination waypoint.
94+
if (index === totalMarkers - 1) {
95+
return {
96+
...defaultOptions,
97+
map: innerMap,
98+
content: new PinElement({
99+
glyph: (index + 1).toString(),
100+
glyphColor: 'white',
101+
background: 'red',
102+
borderColor: 'red',
103+
}).element
104+
}
105+
}
106+
107+
return { ...defaultOptions, map: innerMap };
108+
}
109+
110+
const markers = await result.routes[0].createWaypointAdvancedMarkers(markerOptionsMaker);
111+
// [END maps_routes_markers_style_maker]
112+
113+
114+
// Fit the map to the route.
115+
innerMap.fitBounds(result.routes[0].viewport);
116+
innerMap.setHeading(270);
117+
118+
// Create polylines and add them to the map.
119+
mapPolylines = result.routes[0].createPolylines();
120+
mapPolylines.forEach((polyline) => polyline.setMap(innerMap));
121+
}
122+
123+
initMap();
124+
// [END maps_routes_markers]
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-markers",
3+
"version": "1.0.0",
4+
"scripts": {
5+
"build": "tsc && bash ../jsfiddle.sh routes-markers && bash ../app.sh routes-markers && bash ../docs.sh routes-markers && npm run build:vite --workspace=. && bash ../dist.sh routes-markers",
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+
}

samples/routes-markers/style.css

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_markers] */
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_markers] */
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)