diff --git a/dist/index.html b/dist/index.html index b173d804..f5b0414f 100644 --- a/dist/index.html +++ b/dist/index.html @@ -63,6 +63,9 @@

Maps JSAPI Samples

  • react-ui-kit-place-details-latlng-compact
  • react-ui-kit-search-nearby
  • react-ui-kit-search-text
  • +
  • routes-get-directions
  • +
  • routes-get-directions-panel
  • +
  • routes-route-matrix
  • test-example
  • ui-kit-customization
  • ui-kit-place-details
  • diff --git a/dist/samples/routes-get-directions-panel/app/.eslintsrc.json b/dist/samples/routes-get-directions-panel/app/.eslintsrc.json new file mode 100644 index 00000000..4c44dab0 --- /dev/null +++ b/dist/samples/routes-get-directions-panel/app/.eslintsrc.json @@ -0,0 +1,13 @@ +{ + "extends": [ + "plugin:@typescript-eslint/recommended" + ], + "parser": "@typescript-eslint/parser", + "rules": { + "@typescript-eslint/ban-ts-comment": 0, + "@typescript-eslint/no-this-alias": 1, + "@typescript-eslint/no-empty-function": 1, + "@typescript-eslint/explicit-module-boundary-types": 1, + "@typescript-eslint/no-unused-vars": 1 + } +} diff --git a/dist/samples/routes-get-directions-panel/app/README.md b/dist/samples/routes-get-directions-panel/app/README.md new file mode 100644 index 00000000..62904810 --- /dev/null +++ b/dist/samples/routes-get-directions-panel/app/README.md @@ -0,0 +1,33 @@ +# Google Maps JavaScript Sample + +This sample is generated from @googlemaps/js-samples located at +https://github.com/googlemaps-samples/js-api-samples. + +## Setup + +### Before starting run: + +`$npm i` + +### Run an example on a local web server + +First `cd` to the folder for the sample to run, then: + +`$npm start` + +### Build an individual example + +From `samples/`: + +`$npm run build --workspace=sample-name/` + +### Build all of the examples. + +From `samples/`: +`$npm run build-all` + +## Feedback + +For feedback related to this sample, please open a new issue on +[GitHub](https://github.com/googlemaps-samples/js-api-samples/issues). + diff --git a/dist/samples/routes-get-directions-panel/app/index.html b/dist/samples/routes-get-directions-panel/app/index.html new file mode 100644 index 00000000..585672e3 --- /dev/null +++ b/dist/samples/routes-get-directions-panel/app/index.html @@ -0,0 +1,34 @@ + + + + + + + Get directions with step by step panel + + + + + + +
    +
    +
    +
    +
    +
    +

    Directions

    +
    +
    +
    + + + + + + diff --git a/dist/samples/routes-get-directions-panel/app/index.ts b/dist/samples/routes-get-directions-panel/app/index.ts new file mode 100644 index 00000000..5f07ff73 --- /dev/null +++ b/dist/samples/routes-get-directions-panel/app/index.ts @@ -0,0 +1,143 @@ +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +// [START maps_routes_get_directions_panel] +// Initialize and add the map. +let map; +let mapPolylines: google.maps.Polyline[] = []; +let markers: google.maps.marker.AdvancedMarkerElement[] = []; +let center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA + +// Initialize and add the map. +async function initMap(): Promise { + // Request the needed libraries. + //@ts-ignore + const [{Map}, {Route}] = await Promise.all([ + google.maps.importLibrary('maps') as Promise, + google.maps.importLibrary('routes') as Promise + ]); + + map = new Map(document.getElementById("map") as HTMLElement, { + zoom: 12, + center, + mapTypeControl: false, + mapId: 'DEMO_MAP_ID', + }); + + // Define a simple directions request. + const request = { + origin: 'Mountain View, CA', + destination: 'Sausalito, CA', + intermediates: ['Half Moon Bay, CA', 'Pacifica Esplanade Beach'], + travelMode: 'DRIVING', + fields: ['legs', 'path'], + }; + + // Call computeRoutes to get the directions. + const { routes } = await Route.computeRoutes(request); + + // Display the raw JSON for the result in the console. + console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`); + + // Use createPolylines to create polylines for the route. + mapPolylines = routes[0].createPolylines(); + // Add polylines to the map. + mapPolylines.forEach((polyline) => polyline.setMap(map)); + + fitMapToPath(routes[0].path!); + + // Add markers to all the points. + const markers = await routes[0].createWaypointAdvancedMarkers({ map }); + + // [START maps_routes_get_directions_panel_steps] + // Render navigation instructions + const directionsPanel = document.getElementById("directions"); + + if (!routes || routes.length === 0) { + if (directionsPanel) { + directionsPanel.textContent = "No routes available."; + } + return; + } + + const route = routes[0]; + if (!route.legs || route.legs.length === 0) { + if (directionsPanel) { + directionsPanel.textContent = "The route has no legs."; + } + return; + } + + const fragment = document.createDocumentFragment(); + + route.legs.forEach((leg, index) => { + const legContainer = document.createElement("div"); + legContainer.className = "directions-leg"; + + // Leg Title + const legTitleElement = document.createElement("h3"); + legTitleElement.textContent = `Leg ${index + 1} of ${route.legs.length}`; + legContainer.appendChild(legTitleElement); + + if (leg.steps && leg.steps.length > 0) { + // Add steps to an ordered list + const stepsList = document.createElement("ol"); + stepsList.className = "directions-steps"; + + leg.steps.forEach((step, stepIndex) => { + const stepItem = document.createElement("li"); + stepItem.className = "direction-step"; + + const directionWrapper = document.createElement("div"); + directionWrapper.className = "direction"; + + // Maneuver + if (step.maneuver) { + const maneuverNode = document.createElement("p"); + maneuverNode.textContent = step.maneuver; + maneuverNode.className = "maneuver"; + directionWrapper.appendChild(maneuverNode); + } + + // Distance and Duration + if (step.localizedValues) { + const distanceNode = document.createElement("p"); + distanceNode.textContent = `${step.localizedValues.distance} (${step.localizedValues.staticDuration})`; + distanceNode.className = "distance"; + directionWrapper.appendChild(distanceNode); + } + + // Instructions + if (step.instructions) { + const instructionsNode = document.createElement("p"); + instructionsNode.textContent = step.instructions; + instructionsNode.className = "instruction"; + directionWrapper.appendChild(instructionsNode); + } + + stepItem.appendChild(directionWrapper); + stepsList.appendChild(stepItem); + }); + legContainer.appendChild(stepsList); + } + + fragment.appendChild(legContainer); + directionsPanel?.appendChild(fragment); + }); + +} +// [END maps_routes_get_directions_panel_steps] +// Helper function to fit the map to the path. +async function fitMapToPath(path) { + const { LatLngBounds } = await google.maps.importLibrary('core') as google.maps.CoreLibrary; + const bounds = new LatLngBounds(); + path.forEach((point) => { + bounds.extend(point); + }); + map.fitBounds(bounds); +} + +initMap(); +// [END maps_routes_get_directions_panel] diff --git a/dist/samples/routes-get-directions-panel/app/package.json b/dist/samples/routes-get-directions-panel/app/package.json new file mode 100644 index 00000000..05e55e9f --- /dev/null +++ b/dist/samples/routes-get-directions-panel/app/package.json @@ -0,0 +1,14 @@ +{ + "name": "@js-api-samples/routes-get-directions-panel", + "version": "1.0.0", + "scripts": { + "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", + "test": "tsc && npm run build:vite --workspace=.", + "start": "tsc && vite build --base './' && vite", + "build:vite": "vite build --base './'", + "preview": "vite preview" + }, + "dependencies": { + + } +} diff --git a/dist/samples/routes-get-directions-panel/app/style.css b/dist/samples/routes-get-directions-panel/app/style.css new file mode 100644 index 00000000..f4860590 --- /dev/null +++ b/dist/samples/routes-get-directions-panel/app/style.css @@ -0,0 +1,64 @@ +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +/* [START maps_routes_get_directions_panel] */ + /* + * Always set the map height explicitly to define the size of the div element + * that contains the map. + */ +.container { + display: flex; + flex-direction: row; + height: 100%; + width: 100%; + } + +.directions-panel-container, .map-container { + height: 100%; + width: 50%; + font-family: monospace; +} + +.directions-panel-container { + overflow-y: auto; +} + +/* + * Always set the map height explicitly to define the size of the div element + * that contains the map. + */ +#map { + height: 100%; +} + +.direction { + display: flex; + flex-direction: row; + gap: 1em; +} + +.maneuver { + width: 25% +} + +.distance { + width: 25% +} + +.instruction { + width: 50%; +} + +/* + * Optional: Makes the sample page fill the window. + */ +html, +body { + height: 100%; + margin: 0; + padding: 0; +} + /* [END maps_routes_get_directions_panel] */ + diff --git a/dist/samples/routes-get-directions-panel/app/tsconfig.json b/dist/samples/routes-get-directions-panel/app/tsconfig.json new file mode 100644 index 00000000..09179087 --- /dev/null +++ b/dist/samples/routes-get-directions-panel/app/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "esnext", + "target": "esnext", + "strict": true, + "noImplicitAny": false, + "lib": [ + "es2015", + "esnext", + "es6", + "dom", + "dom.iterable" + ], + "moduleResolution": "Node", + "jsx": "preserve" + } + } \ No newline at end of file diff --git a/dist/samples/routes-get-directions-panel/dist/assets/index-CIijyEYV.js b/dist/samples/routes-get-directions-panel/dist/assets/index-CIijyEYV.js new file mode 100644 index 00000000..7a53934e --- /dev/null +++ b/dist/samples/routes-get-directions-panel/dist/assets/index-CIijyEYV.js @@ -0,0 +1,6 @@ +(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))n(e);new MutationObserver(e=>{for(const t of e)if(t.type==="childList")for(const r of t.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&n(r)}).observe(document,{childList:!0,subtree:!0});function i(e){const t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?t.credentials="include":e.crossOrigin==="anonymous"?t.credentials="omit":t.credentials="same-origin",t}function n(e){if(e.ep)return;e.ep=!0;const t=i(e);fetch(e.href,t)}})();/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */let m,h=[],C={lat:37.447646,lng:-122.113878};async function E(){const[{Map:d},{Route:s}]=await Promise.all([google.maps.importLibrary("maps"),google.maps.importLibrary("routes")]);m=new d(document.getElementById("map"),{zoom:12,center:C,mapTypeControl:!1,mapId:"DEMO_MAP_ID"});const i={origin:"Mountain View, CA",destination:"Sausalito, CA",intermediates:["Half Moon Bay, CA","Pacifica Esplanade Beach"],travelMode:"DRIVING",fields:["legs","path"]},{routes:n}=await s.computeRoutes(i);console.log(`Response: + ${JSON.stringify(n,null,2)}`),h=n[0].createPolylines(),h.forEach(c=>c.setMap(m)),N(n[0].path),await n[0].createWaypointAdvancedMarkers({map:m});const e=document.getElementById("directions");if(!n||n.length===0){e&&(e.textContent="No routes available.");return}const t=n[0];if(!t.legs||t.legs.length===0){e&&(e.textContent="The route has no legs.");return}const r=document.createDocumentFragment();t.legs.forEach((c,y)=>{const u=document.createElement("div");u.className="directions-leg";const g=document.createElement("h3");if(g.textContent=`Leg ${y+1} of ${t.legs.length}`,u.appendChild(g),c.steps&&c.steps.length>0){const p=document.createElement("ol");p.className="directions-steps",c.steps.forEach((a,L)=>{const f=document.createElement("li");f.className="direction-step";const l=document.createElement("div");if(l.className="direction",a.maneuver){const o=document.createElement("p");o.textContent=a.maneuver,o.className="maneuver",l.appendChild(o)}if(a.localizedValues){const o=document.createElement("p");o.textContent=`${a.localizedValues.distance} (${a.localizedValues.staticDuration})`,o.className="distance",l.appendChild(o)}if(a.instructions){const o=document.createElement("p");o.textContent=a.instructions,o.className="instruction",l.appendChild(o)}f.appendChild(l),p.appendChild(f)}),u.appendChild(p)}r.appendChild(u),e?.appendChild(r)})}async function N(d){const{LatLngBounds:s}=await google.maps.importLibrary("core"),i=new s;d.forEach(n=>{i.extend(n)}),m.fitBounds(i)}E(); diff --git a/dist/samples/routes-get-directions-panel/dist/assets/index-CJOi4J0_.css b/dist/samples/routes-get-directions-panel/dist/assets/index-CJOi4J0_.css new file mode 100644 index 00000000..e57ca89b --- /dev/null +++ b/dist/samples/routes-get-directions-panel/dist/assets/index-CJOi4J0_.css @@ -0,0 +1,5 @@ +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */.container{display:flex;flex-direction:row;height:100%;width:100%}.directions-panel-container,.map-container{height:100%;width:50%;font-family:monospace}.directions-panel-container{overflow-y:auto}#map{height:100%}.direction{display:flex;flex-direction:row;gap:1em}.maneuver,.distance{width:25%}.instruction{width:50%}html,body{height:100%;margin:0;padding:0} diff --git a/dist/samples/routes-get-directions-panel/dist/index.html b/dist/samples/routes-get-directions-panel/dist/index.html new file mode 100644 index 00000000..531dd62a --- /dev/null +++ b/dist/samples/routes-get-directions-panel/dist/index.html @@ -0,0 +1,34 @@ + + + + + + + Get directions with step by step panel + + + + + + +
    +
    +
    +
    +
    +
    +

    Directions

    +
    +
    +
    + + + + + + diff --git a/dist/samples/routes-get-directions-panel/docs/index.html b/dist/samples/routes-get-directions-panel/docs/index.html new file mode 100644 index 00000000..585672e3 --- /dev/null +++ b/dist/samples/routes-get-directions-panel/docs/index.html @@ -0,0 +1,34 @@ + + + + + + + Get directions with step by step panel + + + + + + +
    +
    +
    +
    +
    +
    +

    Directions

    +
    +
    +
    + + + + + + diff --git a/dist/samples/routes-get-directions-panel/docs/index.js b/dist/samples/routes-get-directions-panel/docs/index.js new file mode 100644 index 00000000..e9ecfe4b --- /dev/null +++ b/dist/samples/routes-get-directions-panel/docs/index.js @@ -0,0 +1,120 @@ +"use strict"; +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +// [START maps_routes_get_directions_panel] +// Initialize and add the map. +let map; +let mapPolylines = []; +let markers = []; +let center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA +// Initialize and add the map. +async function initMap() { + // Request the needed libraries. + //@ts-ignore + const [{ Map }, { Route }] = await Promise.all([ + google.maps.importLibrary('maps'), + google.maps.importLibrary('routes') + ]); + map = new Map(document.getElementById("map"), { + zoom: 12, + center, + mapTypeControl: false, + mapId: 'DEMO_MAP_ID', + }); + // Define a simple directions request. + const request = { + origin: 'Mountain View, CA', + destination: 'Sausalito, CA', + intermediates: ['Half Moon Bay, CA', 'Pacifica Esplanade Beach'], + travelMode: 'DRIVING', + fields: ['legs', 'path'], + }; + // Call computeRoutes to get the directions. + const { routes } = await Route.computeRoutes(request); + // Display the raw JSON for the result in the console. + console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`); + // Use createPolylines to create polylines for the route. + mapPolylines = routes[0].createPolylines(); + // Add polylines to the map. + mapPolylines.forEach((polyline) => polyline.setMap(map)); + fitMapToPath(routes[0].path); + // Add markers to all the points. + const markers = await routes[0].createWaypointAdvancedMarkers({ map }); + // [START maps_routes_get_directions_panel_steps] + // Render navigation instructions + const directionsPanel = document.getElementById("directions"); + if (!routes || routes.length === 0) { + if (directionsPanel) { + directionsPanel.textContent = "No routes available."; + } + return; + } + const route = routes[0]; + if (!route.legs || route.legs.length === 0) { + if (directionsPanel) { + directionsPanel.textContent = "The route has no legs."; + } + return; + } + const fragment = document.createDocumentFragment(); + route.legs.forEach((leg, index) => { + const legContainer = document.createElement("div"); + legContainer.className = "directions-leg"; + // Leg Title + const legTitleElement = document.createElement("h3"); + legTitleElement.textContent = `Leg ${index + 1} of ${route.legs.length}`; + legContainer.appendChild(legTitleElement); + if (leg.steps && leg.steps.length > 0) { + // Add steps to an ordered list + const stepsList = document.createElement("ol"); + stepsList.className = "directions-steps"; + leg.steps.forEach((step, stepIndex) => { + const stepItem = document.createElement("li"); + stepItem.className = "direction-step"; + const directionWrapper = document.createElement("div"); + directionWrapper.className = "direction"; + // Maneuver + if (step.maneuver) { + const maneuverNode = document.createElement("p"); + maneuverNode.textContent = step.maneuver; + maneuverNode.className = "maneuver"; + directionWrapper.appendChild(maneuverNode); + } + // Distance and Duration + if (step.localizedValues) { + const distanceNode = document.createElement("p"); + distanceNode.textContent = `${step.localizedValues.distance} (${step.localizedValues.staticDuration})`; + distanceNode.className = "distance"; + directionWrapper.appendChild(distanceNode); + } + // Instructions + if (step.instructions) { + const instructionsNode = document.createElement("p"); + instructionsNode.textContent = step.instructions; + instructionsNode.className = "instruction"; + directionWrapper.appendChild(instructionsNode); + } + stepItem.appendChild(directionWrapper); + stepsList.appendChild(stepItem); + }); + legContainer.appendChild(stepsList); + } + fragment.appendChild(legContainer); + directionsPanel?.appendChild(fragment); + }); +} +// [END maps_routes_get_directions_panel_steps] +// Helper function to fit the map to the path. +async function fitMapToPath(path) { + const { LatLngBounds } = await google.maps.importLibrary('core'); + const bounds = new LatLngBounds(); + path.forEach((point) => { + bounds.extend(point); + }); + map.fitBounds(bounds); +} +initMap(); +// [END maps_routes_get_directions_panel] diff --git a/dist/samples/routes-get-directions-panel/docs/index.ts b/dist/samples/routes-get-directions-panel/docs/index.ts new file mode 100644 index 00000000..5f07ff73 --- /dev/null +++ b/dist/samples/routes-get-directions-panel/docs/index.ts @@ -0,0 +1,143 @@ +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +// [START maps_routes_get_directions_panel] +// Initialize and add the map. +let map; +let mapPolylines: google.maps.Polyline[] = []; +let markers: google.maps.marker.AdvancedMarkerElement[] = []; +let center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA + +// Initialize and add the map. +async function initMap(): Promise { + // Request the needed libraries. + //@ts-ignore + const [{Map}, {Route}] = await Promise.all([ + google.maps.importLibrary('maps') as Promise, + google.maps.importLibrary('routes') as Promise + ]); + + map = new Map(document.getElementById("map") as HTMLElement, { + zoom: 12, + center, + mapTypeControl: false, + mapId: 'DEMO_MAP_ID', + }); + + // Define a simple directions request. + const request = { + origin: 'Mountain View, CA', + destination: 'Sausalito, CA', + intermediates: ['Half Moon Bay, CA', 'Pacifica Esplanade Beach'], + travelMode: 'DRIVING', + fields: ['legs', 'path'], + }; + + // Call computeRoutes to get the directions. + const { routes } = await Route.computeRoutes(request); + + // Display the raw JSON for the result in the console. + console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`); + + // Use createPolylines to create polylines for the route. + mapPolylines = routes[0].createPolylines(); + // Add polylines to the map. + mapPolylines.forEach((polyline) => polyline.setMap(map)); + + fitMapToPath(routes[0].path!); + + // Add markers to all the points. + const markers = await routes[0].createWaypointAdvancedMarkers({ map }); + + // [START maps_routes_get_directions_panel_steps] + // Render navigation instructions + const directionsPanel = document.getElementById("directions"); + + if (!routes || routes.length === 0) { + if (directionsPanel) { + directionsPanel.textContent = "No routes available."; + } + return; + } + + const route = routes[0]; + if (!route.legs || route.legs.length === 0) { + if (directionsPanel) { + directionsPanel.textContent = "The route has no legs."; + } + return; + } + + const fragment = document.createDocumentFragment(); + + route.legs.forEach((leg, index) => { + const legContainer = document.createElement("div"); + legContainer.className = "directions-leg"; + + // Leg Title + const legTitleElement = document.createElement("h3"); + legTitleElement.textContent = `Leg ${index + 1} of ${route.legs.length}`; + legContainer.appendChild(legTitleElement); + + if (leg.steps && leg.steps.length > 0) { + // Add steps to an ordered list + const stepsList = document.createElement("ol"); + stepsList.className = "directions-steps"; + + leg.steps.forEach((step, stepIndex) => { + const stepItem = document.createElement("li"); + stepItem.className = "direction-step"; + + const directionWrapper = document.createElement("div"); + directionWrapper.className = "direction"; + + // Maneuver + if (step.maneuver) { + const maneuverNode = document.createElement("p"); + maneuverNode.textContent = step.maneuver; + maneuverNode.className = "maneuver"; + directionWrapper.appendChild(maneuverNode); + } + + // Distance and Duration + if (step.localizedValues) { + const distanceNode = document.createElement("p"); + distanceNode.textContent = `${step.localizedValues.distance} (${step.localizedValues.staticDuration})`; + distanceNode.className = "distance"; + directionWrapper.appendChild(distanceNode); + } + + // Instructions + if (step.instructions) { + const instructionsNode = document.createElement("p"); + instructionsNode.textContent = step.instructions; + instructionsNode.className = "instruction"; + directionWrapper.appendChild(instructionsNode); + } + + stepItem.appendChild(directionWrapper); + stepsList.appendChild(stepItem); + }); + legContainer.appendChild(stepsList); + } + + fragment.appendChild(legContainer); + directionsPanel?.appendChild(fragment); + }); + +} +// [END maps_routes_get_directions_panel_steps] +// Helper function to fit the map to the path. +async function fitMapToPath(path) { + const { LatLngBounds } = await google.maps.importLibrary('core') as google.maps.CoreLibrary; + const bounds = new LatLngBounds(); + path.forEach((point) => { + bounds.extend(point); + }); + map.fitBounds(bounds); +} + +initMap(); +// [END maps_routes_get_directions_panel] diff --git a/dist/samples/routes-get-directions-panel/docs/style.css b/dist/samples/routes-get-directions-panel/docs/style.css new file mode 100644 index 00000000..f4860590 --- /dev/null +++ b/dist/samples/routes-get-directions-panel/docs/style.css @@ -0,0 +1,64 @@ +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +/* [START maps_routes_get_directions_panel] */ + /* + * Always set the map height explicitly to define the size of the div element + * that contains the map. + */ +.container { + display: flex; + flex-direction: row; + height: 100%; + width: 100%; + } + +.directions-panel-container, .map-container { + height: 100%; + width: 50%; + font-family: monospace; +} + +.directions-panel-container { + overflow-y: auto; +} + +/* + * Always set the map height explicitly to define the size of the div element + * that contains the map. + */ +#map { + height: 100%; +} + +.direction { + display: flex; + flex-direction: row; + gap: 1em; +} + +.maneuver { + width: 25% +} + +.distance { + width: 25% +} + +.instruction { + width: 50%; +} + +/* + * Optional: Makes the sample page fill the window. + */ +html, +body { + height: 100%; + margin: 0; + padding: 0; +} + /* [END maps_routes_get_directions_panel] */ + diff --git a/dist/samples/routes-get-directions-panel/jsfiddle/demo.css b/dist/samples/routes-get-directions-panel/jsfiddle/demo.css new file mode 100644 index 00000000..c388804a --- /dev/null +++ b/dist/samples/routes-get-directions-panel/jsfiddle/demo.css @@ -0,0 +1,64 @@ +/* + * @license + * Copyright 2025 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. + */ +.container { + display: flex; + flex-direction: row; + height: 100%; + width: 100%; + } + +.directions-panel-container, .map-container { + height: 100%; + width: 50%; + font-family: monospace; +} + +.directions-panel-container { + overflow-y: auto; +} + +/* + * Always set the map height explicitly to define the size of the div element + * that contains the map. + */ +#map { + height: 100%; +} + +.direction { + display: flex; + flex-direction: row; + gap: 1em; +} + +.maneuver { + width: 25% +} + +.distance { + width: 25% +} + +.instruction { + width: 50%; +} + +/* + * Optional: Makes the sample page fill the window. + */ +html, +body { + height: 100%; + margin: 0; + padding: 0; +} + + diff --git a/dist/samples/routes-get-directions-panel/jsfiddle/demo.details b/dist/samples/routes-get-directions-panel/jsfiddle/demo.details new file mode 100644 index 00000000..f0f13825 --- /dev/null +++ b/dist/samples/routes-get-directions-panel/jsfiddle/demo.details @@ -0,0 +1,7 @@ +name: routes-get-directions-panel +authors: + - Geo Developer IX Documentation Team +tags: + - google maps +load_type: h +description: Sample code supporting Google Maps Platform JavaScript API documentation. diff --git a/dist/samples/routes-get-directions-panel/jsfiddle/demo.html b/dist/samples/routes-get-directions-panel/jsfiddle/demo.html new file mode 100644 index 00000000..0601a38e --- /dev/null +++ b/dist/samples/routes-get-directions-panel/jsfiddle/demo.html @@ -0,0 +1,34 @@ + + + + + + + Get directions with step by step panel + + + + + + +
    +
    +
    +
    +
    +
    +

    Directions

    +
    +
    +
    + + + + + + diff --git a/dist/samples/routes-get-directions-panel/jsfiddle/demo.js b/dist/samples/routes-get-directions-panel/jsfiddle/demo.js new file mode 100644 index 00000000..ba6b6f5b --- /dev/null +++ b/dist/samples/routes-get-directions-panel/jsfiddle/demo.js @@ -0,0 +1,120 @@ +"use strict"; +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// Initialize and add the map. +let map; +let mapPolylines = []; +let markers = []; +let center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA +// Initialize and add the map. +async function initMap() { + // Request the needed libraries. + //@ts-ignore + const [{ Map }, { Route }] = await Promise.all([ + google.maps.importLibrary('maps'), + google.maps.importLibrary('routes') + ]); + map = new Map(document.getElementById("map"), { + zoom: 12, + center, + mapTypeControl: false, + mapId: 'DEMO_MAP_ID', + }); + // Define a simple directions request. + const request = { + origin: 'Mountain View, CA', + destination: 'Sausalito, CA', + intermediates: ['Half Moon Bay, CA', 'Pacifica Esplanade Beach'], + travelMode: 'DRIVING', + fields: ['legs', 'path'], + }; + // Call computeRoutes to get the directions. + const { routes } = await Route.computeRoutes(request); + // Display the raw JSON for the result in the console. + console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`); + // Use createPolylines to create polylines for the route. + mapPolylines = routes[0].createPolylines(); + // Add polylines to the map. + mapPolylines.forEach((polyline) => polyline.setMap(map)); + fitMapToPath(routes[0].path); + // Add markers to all the points. + const markers = await routes[0].createWaypointAdvancedMarkers({ map }); + + // Render navigation instructions + const directionsPanel = document.getElementById("directions"); + if (!routes || routes.length === 0) { + if (directionsPanel) { + directionsPanel.textContent = "No routes available."; + } + return; + } + const route = routes[0]; + if (!route.legs || route.legs.length === 0) { + if (directionsPanel) { + directionsPanel.textContent = "The route has no legs."; + } + return; + } + const fragment = document.createDocumentFragment(); + route.legs.forEach((leg, index) => { + const legContainer = document.createElement("div"); + legContainer.className = "directions-leg"; + // Leg Title + const legTitleElement = document.createElement("h3"); + legTitleElement.textContent = `Leg ${index + 1} of ${route.legs.length}`; + legContainer.appendChild(legTitleElement); + if (leg.steps && leg.steps.length > 0) { + // Add steps to an ordered list + const stepsList = document.createElement("ol"); + stepsList.className = "directions-steps"; + leg.steps.forEach((step, stepIndex) => { + const stepItem = document.createElement("li"); + stepItem.className = "direction-step"; + const directionWrapper = document.createElement("div"); + directionWrapper.className = "direction"; + // Maneuver + if (step.maneuver) { + const maneuverNode = document.createElement("p"); + maneuverNode.textContent = step.maneuver; + maneuverNode.className = "maneuver"; + directionWrapper.appendChild(maneuverNode); + } + // Distance and Duration + if (step.localizedValues) { + const distanceNode = document.createElement("p"); + distanceNode.textContent = `${step.localizedValues.distance} (${step.localizedValues.staticDuration})`; + distanceNode.className = "distance"; + directionWrapper.appendChild(distanceNode); + } + // Instructions + if (step.instructions) { + const instructionsNode = document.createElement("p"); + instructionsNode.textContent = step.instructions; + instructionsNode.className = "instruction"; + directionWrapper.appendChild(instructionsNode); + } + stepItem.appendChild(directionWrapper); + stepsList.appendChild(stepItem); + }); + legContainer.appendChild(stepsList); + } + fragment.appendChild(legContainer); + directionsPanel?.appendChild(fragment); + }); +} + +// Helper function to fit the map to the path. +async function fitMapToPath(path) { + const { LatLngBounds } = await google.maps.importLibrary('core'); + const bounds = new LatLngBounds(); + path.forEach((point) => { + bounds.extend(point); + }); + map.fitBounds(bounds); +} +initMap(); + diff --git a/dist/samples/routes-get-directions/app/.eslintsrc.json b/dist/samples/routes-get-directions/app/.eslintsrc.json new file mode 100644 index 00000000..4c44dab0 --- /dev/null +++ b/dist/samples/routes-get-directions/app/.eslintsrc.json @@ -0,0 +1,13 @@ +{ + "extends": [ + "plugin:@typescript-eslint/recommended" + ], + "parser": "@typescript-eslint/parser", + "rules": { + "@typescript-eslint/ban-ts-comment": 0, + "@typescript-eslint/no-this-alias": 1, + "@typescript-eslint/no-empty-function": 1, + "@typescript-eslint/explicit-module-boundary-types": 1, + "@typescript-eslint/no-unused-vars": 1 + } +} diff --git a/dist/samples/routes-get-directions/app/README.md b/dist/samples/routes-get-directions/app/README.md new file mode 100644 index 00000000..62904810 --- /dev/null +++ b/dist/samples/routes-get-directions/app/README.md @@ -0,0 +1,33 @@ +# Google Maps JavaScript Sample + +This sample is generated from @googlemaps/js-samples located at +https://github.com/googlemaps-samples/js-api-samples. + +## Setup + +### Before starting run: + +`$npm i` + +### Run an example on a local web server + +First `cd` to the folder for the sample to run, then: + +`$npm start` + +### Build an individual example + +From `samples/`: + +`$npm run build --workspace=sample-name/` + +### Build all of the examples. + +From `samples/`: +`$npm run build-all` + +## Feedback + +For feedback related to this sample, please open a new issue on +[GitHub](https://github.com/googlemaps-samples/js-api-samples/issues). + diff --git a/dist/samples/routes-get-directions/app/index.html b/dist/samples/routes-get-directions/app/index.html new file mode 100644 index 00000000..53953011 --- /dev/null +++ b/dist/samples/routes-get-directions/app/index.html @@ -0,0 +1,22 @@ + + + + + + Get directions + + + + + +
    + + + + + \ No newline at end of file diff --git a/dist/samples/routes-get-directions/app/index.ts b/dist/samples/routes-get-directions/app/index.ts new file mode 100644 index 00000000..ee49c89a --- /dev/null +++ b/dist/samples/routes-get-directions/app/index.ts @@ -0,0 +1,125 @@ +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +// [START maps_routes_get_directions] +// Initialize and add the map. +let map; +let mapPolylines: google.maps.Polyline[] = []; +const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA + +// Initialize and add the map. +async function initMap(): Promise { + // Request the needed libraries. + const [{Map}, {Place}, {Route}] = await Promise.all([ + google.maps.importLibrary('maps') as Promise, + google.maps.importLibrary('places') as Promise, + //@ts-ignore + google.maps.importLibrary('routes') as Promise + ]); + + map = new Map(document.getElementById("map") as HTMLElement, { + zoom: 12, + center: center, + mapTypeControl: false, + mapId: 'DEMO_MAP_ID', + }); + + // [START maps_routes_get_directions_request_string] + // Use address strings in a directions request. + const requestWithAddressStrings = { + origin: '1600 Amphitheatre Parkway, Mountain View, CA', + destination: '345 Spear Street, San Francisco, CA', + fields: ['path'], + }; + // [END maps_routes_get_directions_request_string] + + // [START maps_routes_get_directions_request_placeid] + // Use Place IDs in a directions request. + const originPlaceInstance = new Place({ + id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA + }); + + const destinationPlaceInstance = new Place({ + id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA + }); + + const requestWithPlaceIds = { + origin: originPlaceInstance, + destination: destinationPlaceInstance, + fields: ['path'], // Request fields needed to draw polylines. + }; + // [END maps_routes_get_directions_request_placeid] + + // [START maps_routes_get_directions_request_latlng] + // Use lat/lng in a directions request. + // Mountain View, CA + const originLatLng = {lat: 37.422000, lng: -122.084058}; + // San Francisco, CA + const destinationLatLng = {lat: 37.774929, lng: -122.419415}; + + // Define a computeRoutes request. + const requestWithLatLngs = { + origin: originLatLng, + destination: destinationLatLng, + fields: ['path'], + }; + // [END maps_routes_get_directions_request_latlng] + + // [START maps_routes_get_directions_request_pluscode] + // Use Plus Codes in a directions request. + const requestWithPlusCodes = { + origin: '849VCWC8+R9', // Mountain View, CA + destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA + fields: ['path'], + }; + // [END maps_routes_get_directions_request_pluscode] + + // [START maps_routes_get_directions_request_simple] + // Define a simple request. + const request = { + origin: 'Mountain View, CA', + destination: 'San Francisco, CA', + travelMode: 'DRIVING', + fields: ['path'], // Request fields needed to draw polylines. + }; + // [END maps_routes_get_directions_request_simple] + + // Call computeRoutes to get the directions. + //@ts-ignore + // [START maps_routes_get_directions_compute] + const {routes, fallbackInfo, geocodingResults} = await Route.computeRoutes(request); + // [END maps_routes_get_directions_compute] + + // Display the raw JSON for the result in the console. + console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`); + + // [START maps_routes_get_directions_polyline] + // Use createPolylines to create polylines for the route. + mapPolylines = routes[0].createPolylines(); + // Add polylines to the map. + mapPolylines.forEach((polyline) => polyline.setMap(map)); + + // Create markers to start and end points. + const markers = await routes[0].createWaypointAdvancedMarkers(); + // Add markers to the map + markers.forEach((marker) => marker.setMap(map)); + // [END maps_routes_get_directions_polyline] + + fitMapToPath(routes[0].path!); +} + +// Helper function to fit the map to the path. +async function fitMapToPath(path) { + const { LatLngBounds } = await google.maps.importLibrary('core') as google.maps.CoreLibrary; + const bounds = new LatLngBounds(); + path.forEach((point) => { + bounds.extend(point); + }); + map.fitBounds(bounds); +} + +initMap(); +// [END maps_routes_get_directions] + diff --git a/dist/samples/routes-get-directions/app/package.json b/dist/samples/routes-get-directions/app/package.json new file mode 100644 index 00000000..bea7cb8e --- /dev/null +++ b/dist/samples/routes-get-directions/app/package.json @@ -0,0 +1,14 @@ +{ + "name": "@js-api-samples/routes-get-directions", + "version": "1.0.0", + "scripts": { + "build": "tsc && bash ../jsfiddle.sh routes-get-directions && bash ../app.sh routes-get-directions && bash ../docs.sh routes-get-directions && npm run build:vite --workspace=. && bash ../dist.sh routes-get-directions", + "test": "tsc && npm run build:vite --workspace=.", + "start": "tsc && vite build --base './' && vite", + "build:vite": "vite build --base './'", + "preview": "vite preview" + }, + "dependencies": { + + } +} diff --git a/dist/samples/routes-get-directions/app/style.css b/dist/samples/routes-get-directions/app/style.css new file mode 100644 index 00000000..b2359c7d --- /dev/null +++ b/dist/samples/routes-get-directions/app/style.css @@ -0,0 +1,24 @@ +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +/* [START maps_routes_get_directions] */ +/* + * 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; +} +/* [END maps_routes_get_directions] */ diff --git a/dist/samples/routes-get-directions/app/tsconfig.json b/dist/samples/routes-get-directions/app/tsconfig.json new file mode 100644 index 00000000..09179087 --- /dev/null +++ b/dist/samples/routes-get-directions/app/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "esnext", + "target": "esnext", + "strict": true, + "noImplicitAny": false, + "lib": [ + "es2015", + "esnext", + "es6", + "dom", + "dom.iterable" + ], + "moduleResolution": "Node", + "jsx": "preserve" + } + } \ No newline at end of file diff --git a/dist/samples/routes-get-directions/dist/assets/index-CQ7LYNHt.js b/dist/samples/routes-get-directions/dist/assets/index-CQ7LYNHt.js new file mode 100644 index 00000000..ebc8d311 --- /dev/null +++ b/dist/samples/routes-get-directions/dist/assets/index-CQ7LYNHt.js @@ -0,0 +1,6 @@ +(function(){const o=document.createElement("link").relList;if(o&&o.supports&&o.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))n(e);new MutationObserver(e=>{for(const t of e)if(t.type==="childList")for(const i of t.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function r(e){const t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?t.credentials="include":e.crossOrigin==="anonymous"?t.credentials="omit":t.credentials="same-origin",t}function n(e){if(e.ep)return;e.ep=!0;const t=r(e);fetch(e.href,t)}})();/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */let a,l=[];const p={lat:37.447646,lng:-122.113878};async function u(){const[{Map:s},{Place:o},{Route:r}]=await Promise.all([google.maps.importLibrary("maps"),google.maps.importLibrary("places"),google.maps.importLibrary("routes")]);a=new s(document.getElementById("map"),{zoom:12,center:p,mapTypeControl:!1,mapId:"DEMO_MAP_ID"}),new o({id:"ChIJiQHsW0m3j4ARm69rRkrUF3w"}),new o({id:"ChIJIQBpAG2ahYAR_6128GcTUEo"});const n={origin:"Mountain View, CA",destination:"San Francisco, CA",travelMode:"DRIVING",fields:["path"]},{routes:e,fallbackInfo:t,geocodingResults:i}=await r.computeRoutes(n);console.log(`Response: + ${JSON.stringify(e,null,2)}`),l=e[0].createPolylines(),l.forEach(c=>c.setMap(a)),(await e[0].createWaypointAdvancedMarkers()).forEach(c=>c.setMap(a)),d(e[0].path)}async function d(s){const{LatLngBounds:o}=await google.maps.importLibrary("core"),r=new o;s.forEach(n=>{r.extend(n)}),a.fitBounds(r)}u(); diff --git a/dist/samples/routes-get-directions/dist/assets/index-kz-ac4rW.css b/dist/samples/routes-get-directions/dist/assets/index-kz-ac4rW.css new file mode 100644 index 00000000..c4e6ccdb --- /dev/null +++ b/dist/samples/routes-get-directions/dist/assets/index-kz-ac4rW.css @@ -0,0 +1,5 @@ +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */#map{height:100%}html,body{height:100%;margin:0;padding:0} diff --git a/dist/samples/routes-get-directions/dist/index.html b/dist/samples/routes-get-directions/dist/index.html new file mode 100644 index 00000000..ba83caf9 --- /dev/null +++ b/dist/samples/routes-get-directions/dist/index.html @@ -0,0 +1,22 @@ + + + + + + Get directions + + + + + +
    + + + + + \ No newline at end of file diff --git a/dist/samples/routes-get-directions/docs/index.html b/dist/samples/routes-get-directions/docs/index.html new file mode 100644 index 00000000..53953011 --- /dev/null +++ b/dist/samples/routes-get-directions/docs/index.html @@ -0,0 +1,22 @@ + + + + + + Get directions + + + + + +
    + + + + + \ No newline at end of file diff --git a/dist/samples/routes-get-directions/docs/index.js b/dist/samples/routes-get-directions/docs/index.js new file mode 100644 index 00000000..4f10a98b --- /dev/null +++ b/dist/samples/routes-get-directions/docs/index.js @@ -0,0 +1,108 @@ +"use strict"; +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +// [START maps_routes_get_directions] +// Initialize and add the map. +let map; +let mapPolylines = []; +const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA +// Initialize and add the map. +async function initMap() { + // Request the needed libraries. + const [{ Map }, { Place }, { Route }] = await Promise.all([ + google.maps.importLibrary('maps'), + google.maps.importLibrary('places'), + //@ts-ignore + google.maps.importLibrary('routes') + ]); + map = new Map(document.getElementById("map"), { + zoom: 12, + center: center, + mapTypeControl: false, + mapId: 'DEMO_MAP_ID', + }); + // [START maps_routes_get_directions_request_string] + // Use address strings in a directions request. + const requestWithAddressStrings = { + origin: '1600 Amphitheatre Parkway, Mountain View, CA', + destination: '345 Spear Street, San Francisco, CA', + fields: ['path'], + }; + // [END maps_routes_get_directions_request_string] + // [START maps_routes_get_directions_request_placeid] + // Use Place IDs in a directions request. + const originPlaceInstance = new Place({ + id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA + }); + const destinationPlaceInstance = new Place({ + id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA + }); + const requestWithPlaceIds = { + origin: originPlaceInstance, + destination: destinationPlaceInstance, + fields: ['path'], // Request fields needed to draw polylines. + }; + // [END maps_routes_get_directions_request_placeid] + // [START maps_routes_get_directions_request_latlng] + // Use lat/lng in a directions request. + // Mountain View, CA + const originLatLng = { lat: 37.422000, lng: -122.084058 }; + // San Francisco, CA + const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; + // Define a computeRoutes request. + const requestWithLatLngs = { + origin: originLatLng, + destination: destinationLatLng, + fields: ['path'], + }; + // [END maps_routes_get_directions_request_latlng] + // [START maps_routes_get_directions_request_pluscode] + // Use Plus Codes in a directions request. + const requestWithPlusCodes = { + origin: '849VCWC8+R9', // Mountain View, CA + destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA + fields: ['path'], + }; + // [END maps_routes_get_directions_request_pluscode] + // [START maps_routes_get_directions_request_simple] + // Define a simple request. + const request = { + origin: 'Mountain View, CA', + destination: 'San Francisco, CA', + travelMode: 'DRIVING', + fields: ['path'], // Request fields needed to draw polylines. + }; + // [END maps_routes_get_directions_request_simple] + // Call computeRoutes to get the directions. + //@ts-ignore + // [START maps_routes_get_directions_compute] + const { routes, fallbackInfo, geocodingResults } = await Route.computeRoutes(request); + // [END maps_routes_get_directions_compute] + // Display the raw JSON for the result in the console. + console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`); + // [START maps_routes_get_directions_polyline] + // Use createPolylines to create polylines for the route. + mapPolylines = routes[0].createPolylines(); + // Add polylines to the map. + mapPolylines.forEach((polyline) => polyline.setMap(map)); + // Create markers to start and end points. + const markers = await routes[0].createWaypointAdvancedMarkers(); + // Add markers to the map + markers.forEach((marker) => marker.setMap(map)); + // [END maps_routes_get_directions_polyline] + fitMapToPath(routes[0].path); +} +// Helper function to fit the map to the path. +async function fitMapToPath(path) { + const { LatLngBounds } = await google.maps.importLibrary('core'); + const bounds = new LatLngBounds(); + path.forEach((point) => { + bounds.extend(point); + }); + map.fitBounds(bounds); +} +initMap(); +// [END maps_routes_get_directions] diff --git a/dist/samples/routes-get-directions/docs/index.ts b/dist/samples/routes-get-directions/docs/index.ts new file mode 100644 index 00000000..ee49c89a --- /dev/null +++ b/dist/samples/routes-get-directions/docs/index.ts @@ -0,0 +1,125 @@ +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +// [START maps_routes_get_directions] +// Initialize and add the map. +let map; +let mapPolylines: google.maps.Polyline[] = []; +const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA + +// Initialize and add the map. +async function initMap(): Promise { + // Request the needed libraries. + const [{Map}, {Place}, {Route}] = await Promise.all([ + google.maps.importLibrary('maps') as Promise, + google.maps.importLibrary('places') as Promise, + //@ts-ignore + google.maps.importLibrary('routes') as Promise + ]); + + map = new Map(document.getElementById("map") as HTMLElement, { + zoom: 12, + center: center, + mapTypeControl: false, + mapId: 'DEMO_MAP_ID', + }); + + // [START maps_routes_get_directions_request_string] + // Use address strings in a directions request. + const requestWithAddressStrings = { + origin: '1600 Amphitheatre Parkway, Mountain View, CA', + destination: '345 Spear Street, San Francisco, CA', + fields: ['path'], + }; + // [END maps_routes_get_directions_request_string] + + // [START maps_routes_get_directions_request_placeid] + // Use Place IDs in a directions request. + const originPlaceInstance = new Place({ + id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA + }); + + const destinationPlaceInstance = new Place({ + id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA + }); + + const requestWithPlaceIds = { + origin: originPlaceInstance, + destination: destinationPlaceInstance, + fields: ['path'], // Request fields needed to draw polylines. + }; + // [END maps_routes_get_directions_request_placeid] + + // [START maps_routes_get_directions_request_latlng] + // Use lat/lng in a directions request. + // Mountain View, CA + const originLatLng = {lat: 37.422000, lng: -122.084058}; + // San Francisco, CA + const destinationLatLng = {lat: 37.774929, lng: -122.419415}; + + // Define a computeRoutes request. + const requestWithLatLngs = { + origin: originLatLng, + destination: destinationLatLng, + fields: ['path'], + }; + // [END maps_routes_get_directions_request_latlng] + + // [START maps_routes_get_directions_request_pluscode] + // Use Plus Codes in a directions request. + const requestWithPlusCodes = { + origin: '849VCWC8+R9', // Mountain View, CA + destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA + fields: ['path'], + }; + // [END maps_routes_get_directions_request_pluscode] + + // [START maps_routes_get_directions_request_simple] + // Define a simple request. + const request = { + origin: 'Mountain View, CA', + destination: 'San Francisco, CA', + travelMode: 'DRIVING', + fields: ['path'], // Request fields needed to draw polylines. + }; + // [END maps_routes_get_directions_request_simple] + + // Call computeRoutes to get the directions. + //@ts-ignore + // [START maps_routes_get_directions_compute] + const {routes, fallbackInfo, geocodingResults} = await Route.computeRoutes(request); + // [END maps_routes_get_directions_compute] + + // Display the raw JSON for the result in the console. + console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`); + + // [START maps_routes_get_directions_polyline] + // Use createPolylines to create polylines for the route. + mapPolylines = routes[0].createPolylines(); + // Add polylines to the map. + mapPolylines.forEach((polyline) => polyline.setMap(map)); + + // Create markers to start and end points. + const markers = await routes[0].createWaypointAdvancedMarkers(); + // Add markers to the map + markers.forEach((marker) => marker.setMap(map)); + // [END maps_routes_get_directions_polyline] + + fitMapToPath(routes[0].path!); +} + +// Helper function to fit the map to the path. +async function fitMapToPath(path) { + const { LatLngBounds } = await google.maps.importLibrary('core') as google.maps.CoreLibrary; + const bounds = new LatLngBounds(); + path.forEach((point) => { + bounds.extend(point); + }); + map.fitBounds(bounds); +} + +initMap(); +// [END maps_routes_get_directions] + diff --git a/dist/samples/routes-get-directions/docs/style.css b/dist/samples/routes-get-directions/docs/style.css new file mode 100644 index 00000000..b2359c7d --- /dev/null +++ b/dist/samples/routes-get-directions/docs/style.css @@ -0,0 +1,24 @@ +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +/* [START maps_routes_get_directions] */ +/* + * 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; +} +/* [END maps_routes_get_directions] */ diff --git a/dist/samples/routes-get-directions/jsfiddle/demo.css b/dist/samples/routes-get-directions/jsfiddle/demo.css new file mode 100644 index 00000000..f8bab9a6 --- /dev/null +++ b/dist/samples/routes-get-directions/jsfiddle/demo.css @@ -0,0 +1,24 @@ +/* + * @license + * Copyright 2025 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; +} + diff --git a/dist/samples/routes-get-directions/jsfiddle/demo.details b/dist/samples/routes-get-directions/jsfiddle/demo.details new file mode 100644 index 00000000..276d0bc3 --- /dev/null +++ b/dist/samples/routes-get-directions/jsfiddle/demo.details @@ -0,0 +1,7 @@ +name: routes-get-directions +authors: + - Geo Developer IX Documentation Team +tags: + - google maps +load_type: h +description: Sample code supporting Google Maps Platform JavaScript API documentation. diff --git a/dist/samples/routes-get-directions/jsfiddle/demo.html b/dist/samples/routes-get-directions/jsfiddle/demo.html new file mode 100644 index 00000000..0e3ebfa6 --- /dev/null +++ b/dist/samples/routes-get-directions/jsfiddle/demo.html @@ -0,0 +1,21 @@ + + + + + + Get directions + + + + + +
    + + + + diff --git a/dist/samples/routes-get-directions/jsfiddle/demo.js b/dist/samples/routes-get-directions/jsfiddle/demo.js new file mode 100644 index 00000000..c284c8f4 --- /dev/null +++ b/dist/samples/routes-get-directions/jsfiddle/demo.js @@ -0,0 +1,108 @@ +"use strict"; +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// Initialize and add the map. +let map; +let mapPolylines = []; +const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA +// Initialize and add the map. +async function initMap() { + // Request the needed libraries. + const [{ Map }, { Place }, { Route }] = await Promise.all([ + google.maps.importLibrary('maps'), + google.maps.importLibrary('places'), + //@ts-ignore + google.maps.importLibrary('routes') + ]); + map = new Map(document.getElementById("map"), { + zoom: 12, + center: center, + mapTypeControl: false, + mapId: 'DEMO_MAP_ID', + }); + + // Use address strings in a directions request. + const requestWithAddressStrings = { + origin: '1600 Amphitheatre Parkway, Mountain View, CA', + destination: '345 Spear Street, San Francisco, CA', + fields: ['path'], + }; + + + // Use Place IDs in a directions request. + const originPlaceInstance = new Place({ + id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA + }); + const destinationPlaceInstance = new Place({ + id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA + }); + const requestWithPlaceIds = { + origin: originPlaceInstance, + destination: destinationPlaceInstance, + fields: ['path'], // Request fields needed to draw polylines. + }; + + + // Use lat/lng in a directions request. + // Mountain View, CA + const originLatLng = { lat: 37.422000, lng: -122.084058 }; + // San Francisco, CA + const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; + // Define a computeRoutes request. + const requestWithLatLngs = { + origin: originLatLng, + destination: destinationLatLng, + fields: ['path'], + }; + + + // Use Plus Codes in a directions request. + const requestWithPlusCodes = { + origin: '849VCWC8+R9', // Mountain View, CA + destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA + fields: ['path'], + }; + + + // Define a simple request. + const request = { + origin: 'Mountain View, CA', + destination: 'San Francisco, CA', + travelMode: 'DRIVING', + fields: ['path'], // Request fields needed to draw polylines. + }; + + // Call computeRoutes to get the directions. + //@ts-ignore + + const { routes, fallbackInfo, geocodingResults } = await Route.computeRoutes(request); + + // Display the raw JSON for the result in the console. + console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`); + + // Use createPolylines to create polylines for the route. + mapPolylines = routes[0].createPolylines(); + // Add polylines to the map. + mapPolylines.forEach((polyline) => polyline.setMap(map)); + // Create markers to start and end points. + const markers = await routes[0].createWaypointAdvancedMarkers(); + // Add markers to the map + markers.forEach((marker) => marker.setMap(map)); + + fitMapToPath(routes[0].path); +} +// Helper function to fit the map to the path. +async function fitMapToPath(path) { + const { LatLngBounds } = await google.maps.importLibrary('core'); + const bounds = new LatLngBounds(); + path.forEach((point) => { + bounds.extend(point); + }); + map.fitBounds(bounds); +} +initMap(); + diff --git a/dist/samples/routes-route-matrix/app/.eslintsrc.json b/dist/samples/routes-route-matrix/app/.eslintsrc.json new file mode 100644 index 00000000..4c44dab0 --- /dev/null +++ b/dist/samples/routes-route-matrix/app/.eslintsrc.json @@ -0,0 +1,13 @@ +{ + "extends": [ + "plugin:@typescript-eslint/recommended" + ], + "parser": "@typescript-eslint/parser", + "rules": { + "@typescript-eslint/ban-ts-comment": 0, + "@typescript-eslint/no-this-alias": 1, + "@typescript-eslint/no-empty-function": 1, + "@typescript-eslint/explicit-module-boundary-types": 1, + "@typescript-eslint/no-unused-vars": 1 + } +} diff --git a/dist/samples/routes-route-matrix/app/README.md b/dist/samples/routes-route-matrix/app/README.md new file mode 100644 index 00000000..62904810 --- /dev/null +++ b/dist/samples/routes-route-matrix/app/README.md @@ -0,0 +1,33 @@ +# Google Maps JavaScript Sample + +This sample is generated from @googlemaps/js-samples located at +https://github.com/googlemaps-samples/js-api-samples. + +## Setup + +### Before starting run: + +`$npm i` + +### Run an example on a local web server + +First `cd` to the folder for the sample to run, then: + +`$npm start` + +### Build an individual example + +From `samples/`: + +`$npm run build --workspace=sample-name/` + +### Build all of the examples. + +From `samples/`: +`$npm run build-all` + +## Feedback + +For feedback related to this sample, please open a new issue on +[GitHub](https://github.com/googlemaps-samples/js-api-samples/issues). + diff --git a/dist/samples/routes-route-matrix/app/index.html b/dist/samples/routes-route-matrix/app/index.html new file mode 100644 index 00000000..49ce9768 --- /dev/null +++ b/dist/samples/routes-route-matrix/app/index.html @@ -0,0 +1,30 @@ + + + + + + Route matrix + + + + + +
    +
    + +
    + + + + + \ No newline at end of file diff --git a/dist/samples/routes-route-matrix/app/index.ts b/dist/samples/routes-route-matrix/app/index.ts new file mode 100644 index 00000000..69bb5738 --- /dev/null +++ b/dist/samples/routes-route-matrix/app/index.ts @@ -0,0 +1,118 @@ +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +// [START maps_routes_route_matrix] +// Initialize and add the map. +let map; +let markers: google.maps.marker.AdvancedMarkerElement[] = []; +let center = { lat: 51.55, lng: -1.8 }; + +async function initMap(): Promise { + // Request the needed libraries. + //@ts-ignore + const [{Map}, {Place}, {AdvancedMarkerElement, PinElement}, {RouteMatrix}] = await Promise.all([ + google.maps.importLibrary('maps') as Promise, + google.maps.importLibrary('places') as Promise, + google.maps.importLibrary('marker') as Promise, + google.maps.importLibrary('routes') as Promise + ]); + + const bounds = new google.maps.LatLngBounds(); + + map = new Map(document.getElementById('map') as HTMLElement, { + zoom: 8, + center: center, + mapId: 'DEMO_MAP_ID', + }); + + // Build the request using Place instances. + const origin1 = new Place({ + id: "ChIJ83WZp86p2EcRbMrkYqGncBQ", // Greenwich, London, UK + }); + const origin2 = new Place({ + id: "ChIJCSkVvleJc0gR8HHaTGpajKc", // Southampton, UK + }); + const destinationA = new Place({ + id: "ChIJYdizgWaDcUgRH9eaSy6y5I4", // Bristol, UK + }); + const destinationB = new Place({ + id: "ChIJ9VPsNNQCbkgRDmeGZdsGNBQ", // Cardiff, UK + }); + + await Promise.all([ + origin1.fetchFields({ fields: ['location', 'displayName']}), + origin2.fetchFields({ fields: ['location', 'displayName']}), + destinationA.fetchFields({ fields: ['location', 'displayName']}), + destinationB.fetchFields({ fields: ['location', 'displayName']}), + ]); + + const request = { + origins: [origin1, origin2], + destinations: [destinationA, destinationB], + travelMode: 'DRIVING', + units: google.maps.UnitSystem.METRIC, + fields: ['distanceMeters', 'durationMillis', 'condition'], + }; + + // Show the request. + (document.getElementById("request") as HTMLDivElement).innerText = + JSON.stringify(request, null, 2); + + // Get the RouteMatrix response. + const response = await RouteMatrix.computeRouteMatrix(request); + + // Show the response. + (document.getElementById("response") as HTMLDivElement).innerText = + JSON.stringify(response, null, 2); + + // Add markers for the origins. + for (const origin of request.origins) { + if (origin.location) { + const pin = new PinElement({ + glyph: "O", + glyphColor: "white", + background: "#137333", + borderColor: "white", + }); + const marker = new AdvancedMarkerElement({ + map, + position: origin.location, + content: pin.element, + title: `Origin: ${origin.displayName}`, + }); + markers.push(marker); + bounds.extend(origin.location); + } + } + + // Add markers for the destinations. + for (let i = 0; i < request.destinations.length; i++) { + const destination = request.destinations[i]; + if (destination.location) { + const pin = new PinElement({ + glyph: "D", + glyphColor: "white", + background: "#C5221F", + borderColor: "white", + }); + + const marker = new AdvancedMarkerElement({ + map, + position: destination.location, + content: pin.element, + title: `Destination: ${destination.displayName}`, + }); + + markers.push(marker); + bounds.extend(destination.location); + } + } + + // Fit the map to the bounds of all markers. + map.fitBounds(bounds); +} + +initMap(); +// [END maps_routes_route_matrix] diff --git a/dist/samples/routes-route-matrix/app/package.json b/dist/samples/routes-route-matrix/app/package.json new file mode 100644 index 00000000..b31a0f82 --- /dev/null +++ b/dist/samples/routes-route-matrix/app/package.json @@ -0,0 +1,14 @@ +{ + "name": "@js-api-samples/routes-route-matrix", + "version": "1.0.0", + "scripts": { + "build": "tsc && bash ../jsfiddle.sh routes-route-matrix && bash ../app.sh routes-route-matrix && bash ../docs.sh routes-route-matrix && npm run build:vite --workspace=. && bash ../dist.sh routes-route-matrix", + "test": "tsc && npm run build:vite --workspace=.", + "start": "tsc && vite build --base './' && vite", + "build:vite": "vite build --base './'", + "preview": "vite preview" + }, + "dependencies": { + + } +} diff --git a/dist/samples/routes-route-matrix/app/style.css b/dist/samples/routes-route-matrix/app/style.css new file mode 100644 index 00000000..f82f9fac --- /dev/null +++ b/dist/samples/routes-route-matrix/app/style.css @@ -0,0 +1,44 @@ +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +/* [START maps_routes_route_matrix] */ + /* + * Always set the map height explicitly to define the size of the div element + * that contains the map. + */ +/* Optional: Makes the sample page fill the window. */ +html, +body { + height: 100%; + margin: 0; + padding: 0; +} + +#container { + height: 100%; + display: flex; +} + +#sidebar { + flex-basis: 15rem; + flex-grow: 1; + padding: 1rem; + max-width: 30rem; + height: 100%; + box-sizing: border-box; + overflow: auto; +} + +#map { + flex-basis: 0; + flex-grow: 4; + height: 100%; +} + +#sidebar { + flex-direction: column; +} + /* [END maps_routes_route_matrix] */ + \ No newline at end of file diff --git a/dist/samples/routes-route-matrix/app/tsconfig.json b/dist/samples/routes-route-matrix/app/tsconfig.json new file mode 100644 index 00000000..09179087 --- /dev/null +++ b/dist/samples/routes-route-matrix/app/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "esnext", + "target": "esnext", + "strict": true, + "noImplicitAny": false, + "lib": [ + "es2015", + "esnext", + "es6", + "dom", + "dom.iterable" + ], + "moduleResolution": "Node", + "jsx": "preserve" + } + } \ No newline at end of file diff --git a/dist/samples/routes-route-matrix/dist/assets/index-Cvua8orA.js b/dist/samples/routes-route-matrix/dist/assets/index-Cvua8orA.js new file mode 100644 index 00000000..00680525 --- /dev/null +++ b/dist/samples/routes-route-matrix/dist/assets/index-Cvua8orA.js @@ -0,0 +1,5 @@ +(function(){const o=document.createElement("link").relList;if(o&&o.supports&&o.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))s(e);new MutationObserver(e=>{for(const t of e)if(t.type==="childList")for(const n of t.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function a(e){const t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?t.credentials="include":e.crossOrigin==="anonymous"?t.credentials="omit":t.credentials="same-origin",t}function s(e){if(e.ep)return;e.ep=!0;const t=a(e);fetch(e.href,t)}})();/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */let c,y={lat:51.55,lng:-1.8};async function h(){const[{Map:d},{Place:o},{AdvancedMarkerElement:a,PinElement:s},{RouteMatrix:e}]=await Promise.all([google.maps.importLibrary("maps"),google.maps.importLibrary("places"),google.maps.importLibrary("marker"),google.maps.importLibrary("routes")]),t=new google.maps.LatLngBounds;c=new d(document.getElementById("map"),{zoom:8,center:y,mapId:"DEMO_MAP_ID"});const n=new o({id:"ChIJ83WZp86p2EcRbMrkYqGncBQ"}),p=new o({id:"ChIJCSkVvleJc0gR8HHaTGpajKc"}),m=new o({id:"ChIJYdizgWaDcUgRH9eaSy6y5I4"}),u=new o({id:"ChIJ9VPsNNQCbkgRDmeGZdsGNBQ"});await Promise.all([n.fetchFields({fields:["location","displayName"]}),p.fetchFields({fields:["location","displayName"]}),m.fetchFields({fields:["location","displayName"]}),u.fetchFields({fields:["location","displayName"]})]);const l={origins:[n,p],destinations:[m,u],travelMode:"DRIVING",units:google.maps.UnitSystem.METRIC,fields:["distanceMeters","durationMillis","condition"]};document.getElementById("request").innerText=JSON.stringify(l,null,2);const g=await e.computeRouteMatrix(l);document.getElementById("response").innerText=JSON.stringify(g,null,2);for(const i of l.origins)if(i.location){const r=new s({glyph:"O",glyphColor:"white",background:"#137333",borderColor:"white"});new a({map:c,position:i.location,content:r.element,title:`Origin: ${i.displayName}`}),t.extend(i.location)}for(let i=0;i + + + + + Route matrix + + + + + +
    +
    + +
    + + + + + \ No newline at end of file diff --git a/dist/samples/routes-route-matrix/docs/index.html b/dist/samples/routes-route-matrix/docs/index.html new file mode 100644 index 00000000..49ce9768 --- /dev/null +++ b/dist/samples/routes-route-matrix/docs/index.html @@ -0,0 +1,30 @@ + + + + + + Route matrix + + + + + +
    +
    + +
    + + + + + \ No newline at end of file diff --git a/dist/samples/routes-route-matrix/docs/index.js b/dist/samples/routes-route-matrix/docs/index.js new file mode 100644 index 00000000..59befaaf --- /dev/null +++ b/dist/samples/routes-route-matrix/docs/index.js @@ -0,0 +1,104 @@ +"use strict"; +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +// [START maps_routes_route_matrix] +// Initialize and add the map. +let map; +let markers = []; +let center = { lat: 51.55, lng: -1.8 }; +async function initMap() { + // Request the needed libraries. + //@ts-ignore + const [{ Map }, { Place }, { AdvancedMarkerElement, PinElement }, { RouteMatrix }] = await Promise.all([ + google.maps.importLibrary('maps'), + google.maps.importLibrary('places'), + google.maps.importLibrary('marker'), + google.maps.importLibrary('routes') + ]); + const bounds = new google.maps.LatLngBounds(); + map = new Map(document.getElementById('map'), { + zoom: 8, + center: center, + mapId: 'DEMO_MAP_ID', + }); + // Build the request using Place instances. + const origin1 = new Place({ + id: "ChIJ83WZp86p2EcRbMrkYqGncBQ", // Greenwich, London, UK + }); + const origin2 = new Place({ + id: "ChIJCSkVvleJc0gR8HHaTGpajKc", // Southampton, UK + }); + const destinationA = new Place({ + id: "ChIJYdizgWaDcUgRH9eaSy6y5I4", // Bristol, UK + }); + const destinationB = new Place({ + id: "ChIJ9VPsNNQCbkgRDmeGZdsGNBQ", // Cardiff, UK + }); + await Promise.all([ + origin1.fetchFields({ fields: ['location', 'displayName'] }), + origin2.fetchFields({ fields: ['location', 'displayName'] }), + destinationA.fetchFields({ fields: ['location', 'displayName'] }), + destinationB.fetchFields({ fields: ['location', 'displayName'] }), + ]); + const request = { + origins: [origin1, origin2], + destinations: [destinationA, destinationB], + travelMode: 'DRIVING', + units: google.maps.UnitSystem.METRIC, + fields: ['distanceMeters', 'durationMillis', 'condition'], + }; + // Show the request. + document.getElementById("request").innerText = + JSON.stringify(request, null, 2); + // Get the RouteMatrix response. + const response = await RouteMatrix.computeRouteMatrix(request); + // Show the response. + document.getElementById("response").innerText = + JSON.stringify(response, null, 2); + // Add markers for the origins. + for (const origin of request.origins) { + if (origin.location) { + const pin = new PinElement({ + glyph: "O", + glyphColor: "white", + background: "#137333", + borderColor: "white", + }); + const marker = new AdvancedMarkerElement({ + map, + position: origin.location, + content: pin.element, + title: `Origin: ${origin.displayName}`, + }); + markers.push(marker); + bounds.extend(origin.location); + } + } + // Add markers for the destinations. + for (let i = 0; i < request.destinations.length; i++) { + const destination = request.destinations[i]; + if (destination.location) { + const pin = new PinElement({ + glyph: "D", + glyphColor: "white", + background: "#C5221F", + borderColor: "white", + }); + const marker = new AdvancedMarkerElement({ + map, + position: destination.location, + content: pin.element, + title: `Destination: ${destination.displayName}`, + }); + markers.push(marker); + bounds.extend(destination.location); + } + } + // Fit the map to the bounds of all markers. + map.fitBounds(bounds); +} +initMap(); +// [END maps_routes_route_matrix] diff --git a/dist/samples/routes-route-matrix/docs/index.ts b/dist/samples/routes-route-matrix/docs/index.ts new file mode 100644 index 00000000..69bb5738 --- /dev/null +++ b/dist/samples/routes-route-matrix/docs/index.ts @@ -0,0 +1,118 @@ +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +// [START maps_routes_route_matrix] +// Initialize and add the map. +let map; +let markers: google.maps.marker.AdvancedMarkerElement[] = []; +let center = { lat: 51.55, lng: -1.8 }; + +async function initMap(): Promise { + // Request the needed libraries. + //@ts-ignore + const [{Map}, {Place}, {AdvancedMarkerElement, PinElement}, {RouteMatrix}] = await Promise.all([ + google.maps.importLibrary('maps') as Promise, + google.maps.importLibrary('places') as Promise, + google.maps.importLibrary('marker') as Promise, + google.maps.importLibrary('routes') as Promise + ]); + + const bounds = new google.maps.LatLngBounds(); + + map = new Map(document.getElementById('map') as HTMLElement, { + zoom: 8, + center: center, + mapId: 'DEMO_MAP_ID', + }); + + // Build the request using Place instances. + const origin1 = new Place({ + id: "ChIJ83WZp86p2EcRbMrkYqGncBQ", // Greenwich, London, UK + }); + const origin2 = new Place({ + id: "ChIJCSkVvleJc0gR8HHaTGpajKc", // Southampton, UK + }); + const destinationA = new Place({ + id: "ChIJYdizgWaDcUgRH9eaSy6y5I4", // Bristol, UK + }); + const destinationB = new Place({ + id: "ChIJ9VPsNNQCbkgRDmeGZdsGNBQ", // Cardiff, UK + }); + + await Promise.all([ + origin1.fetchFields({ fields: ['location', 'displayName']}), + origin2.fetchFields({ fields: ['location', 'displayName']}), + destinationA.fetchFields({ fields: ['location', 'displayName']}), + destinationB.fetchFields({ fields: ['location', 'displayName']}), + ]); + + const request = { + origins: [origin1, origin2], + destinations: [destinationA, destinationB], + travelMode: 'DRIVING', + units: google.maps.UnitSystem.METRIC, + fields: ['distanceMeters', 'durationMillis', 'condition'], + }; + + // Show the request. + (document.getElementById("request") as HTMLDivElement).innerText = + JSON.stringify(request, null, 2); + + // Get the RouteMatrix response. + const response = await RouteMatrix.computeRouteMatrix(request); + + // Show the response. + (document.getElementById("response") as HTMLDivElement).innerText = + JSON.stringify(response, null, 2); + + // Add markers for the origins. + for (const origin of request.origins) { + if (origin.location) { + const pin = new PinElement({ + glyph: "O", + glyphColor: "white", + background: "#137333", + borderColor: "white", + }); + const marker = new AdvancedMarkerElement({ + map, + position: origin.location, + content: pin.element, + title: `Origin: ${origin.displayName}`, + }); + markers.push(marker); + bounds.extend(origin.location); + } + } + + // Add markers for the destinations. + for (let i = 0; i < request.destinations.length; i++) { + const destination = request.destinations[i]; + if (destination.location) { + const pin = new PinElement({ + glyph: "D", + glyphColor: "white", + background: "#C5221F", + borderColor: "white", + }); + + const marker = new AdvancedMarkerElement({ + map, + position: destination.location, + content: pin.element, + title: `Destination: ${destination.displayName}`, + }); + + markers.push(marker); + bounds.extend(destination.location); + } + } + + // Fit the map to the bounds of all markers. + map.fitBounds(bounds); +} + +initMap(); +// [END maps_routes_route_matrix] diff --git a/dist/samples/routes-route-matrix/docs/style.css b/dist/samples/routes-route-matrix/docs/style.css new file mode 100644 index 00000000..f82f9fac --- /dev/null +++ b/dist/samples/routes-route-matrix/docs/style.css @@ -0,0 +1,44 @@ +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +/* [START maps_routes_route_matrix] */ + /* + * Always set the map height explicitly to define the size of the div element + * that contains the map. + */ +/* Optional: Makes the sample page fill the window. */ +html, +body { + height: 100%; + margin: 0; + padding: 0; +} + +#container { + height: 100%; + display: flex; +} + +#sidebar { + flex-basis: 15rem; + flex-grow: 1; + padding: 1rem; + max-width: 30rem; + height: 100%; + box-sizing: border-box; + overflow: auto; +} + +#map { + flex-basis: 0; + flex-grow: 4; + height: 100%; +} + +#sidebar { + flex-direction: column; +} + /* [END maps_routes_route_matrix] */ + \ No newline at end of file diff --git a/dist/samples/routes-route-matrix/jsfiddle/demo.css b/dist/samples/routes-route-matrix/jsfiddle/demo.css new file mode 100644 index 00000000..e3e4799e --- /dev/null +++ b/dist/samples/routes-route-matrix/jsfiddle/demo.css @@ -0,0 +1,44 @@ +/* + * @license + * Copyright 2025 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. + */ +/* Optional: Makes the sample page fill the window. */ +html, +body { + height: 100%; + margin: 0; + padding: 0; +} + +#container { + height: 100%; + display: flex; +} + +#sidebar { + flex-basis: 15rem; + flex-grow: 1; + padding: 1rem; + max-width: 30rem; + height: 100%; + box-sizing: border-box; + overflow: auto; +} + +#map { + flex-basis: 0; + flex-grow: 4; + height: 100%; +} + +#sidebar { + flex-direction: column; +} + + \ No newline at end of file diff --git a/dist/samples/routes-route-matrix/jsfiddle/demo.details b/dist/samples/routes-route-matrix/jsfiddle/demo.details new file mode 100644 index 00000000..8cbe5a59 --- /dev/null +++ b/dist/samples/routes-route-matrix/jsfiddle/demo.details @@ -0,0 +1,7 @@ +name: routes-route-matrix +authors: + - Geo Developer IX Documentation Team +tags: + - google maps +load_type: h +description: Sample code supporting Google Maps Platform JavaScript API documentation. diff --git a/dist/samples/routes-route-matrix/jsfiddle/demo.html b/dist/samples/routes-route-matrix/jsfiddle/demo.html new file mode 100644 index 00000000..a54829ea --- /dev/null +++ b/dist/samples/routes-route-matrix/jsfiddle/demo.html @@ -0,0 +1,29 @@ + + + + + + Route matrix + + + + + +
    +
    + +
    + + + + diff --git a/dist/samples/routes-route-matrix/jsfiddle/demo.js b/dist/samples/routes-route-matrix/jsfiddle/demo.js new file mode 100644 index 00000000..13162a1e --- /dev/null +++ b/dist/samples/routes-route-matrix/jsfiddle/demo.js @@ -0,0 +1,104 @@ +"use strict"; +/* + * @license + * Copyright 2025 Google LLC. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// Initialize and add the map. +let map; +let markers = []; +let center = { lat: 51.55, lng: -1.8 }; +async function initMap() { + // Request the needed libraries. + //@ts-ignore + const [{ Map }, { Place }, { AdvancedMarkerElement, PinElement }, { RouteMatrix }] = await Promise.all([ + google.maps.importLibrary('maps'), + google.maps.importLibrary('places'), + google.maps.importLibrary('marker'), + google.maps.importLibrary('routes') + ]); + const bounds = new google.maps.LatLngBounds(); + map = new Map(document.getElementById('map'), { + zoom: 8, + center: center, + mapId: 'DEMO_MAP_ID', + }); + // Build the request using Place instances. + const origin1 = new Place({ + id: "ChIJ83WZp86p2EcRbMrkYqGncBQ", // Greenwich, London, UK + }); + const origin2 = new Place({ + id: "ChIJCSkVvleJc0gR8HHaTGpajKc", // Southampton, UK + }); + const destinationA = new Place({ + id: "ChIJYdizgWaDcUgRH9eaSy6y5I4", // Bristol, UK + }); + const destinationB = new Place({ + id: "ChIJ9VPsNNQCbkgRDmeGZdsGNBQ", // Cardiff, UK + }); + await Promise.all([ + origin1.fetchFields({ fields: ['location', 'displayName'] }), + origin2.fetchFields({ fields: ['location', 'displayName'] }), + destinationA.fetchFields({ fields: ['location', 'displayName'] }), + destinationB.fetchFields({ fields: ['location', 'displayName'] }), + ]); + const request = { + origins: [origin1, origin2], + destinations: [destinationA, destinationB], + travelMode: 'DRIVING', + units: google.maps.UnitSystem.METRIC, + fields: ['distanceMeters', 'durationMillis', 'condition'], + }; + // Show the request. + document.getElementById("request").innerText = + JSON.stringify(request, null, 2); + // Get the RouteMatrix response. + const response = await RouteMatrix.computeRouteMatrix(request); + // Show the response. + document.getElementById("response").innerText = + JSON.stringify(response, null, 2); + // Add markers for the origins. + for (const origin of request.origins) { + if (origin.location) { + const pin = new PinElement({ + glyph: "O", + glyphColor: "white", + background: "#137333", + borderColor: "white", + }); + const marker = new AdvancedMarkerElement({ + map, + position: origin.location, + content: pin.element, + title: `Origin: ${origin.displayName}`, + }); + markers.push(marker); + bounds.extend(origin.location); + } + } + // Add markers for the destinations. + for (let i = 0; i < request.destinations.length; i++) { + const destination = request.destinations[i]; + if (destination.location) { + const pin = new PinElement({ + glyph: "D", + glyphColor: "white", + background: "#C5221F", + borderColor: "white", + }); + const marker = new AdvancedMarkerElement({ + map, + position: destination.location, + content: pin.element, + title: `Destination: ${destination.displayName}`, + }); + markers.push(marker); + bounds.extend(destination.location); + } + } + // Fit the map to the bounds of all markers. + map.fitBounds(bounds); +} +initMap(); + diff --git a/index.html b/index.html index b173d804..f5b0414f 100644 --- a/index.html +++ b/index.html @@ -63,6 +63,9 @@

    Maps JSAPI Samples

  • react-ui-kit-place-details-latlng-compact
  • react-ui-kit-search-nearby
  • react-ui-kit-search-text
  • +
  • routes-get-directions
  • +
  • routes-get-directions-panel
  • +
  • routes-route-matrix
  • test-example
  • ui-kit-customization
  • ui-kit-place-details
  • diff --git a/package-lock.json b/package-lock.json index c7facf2b..4fcaf187 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1387,6 +1387,18 @@ "resolved": "samples/react-ui-kit-place-details-compact", "link": true }, + "node_modules/@js-api-samples/routes-get-directions": { + "resolved": "samples/routes-get-directions", + "link": true + }, + "node_modules/@js-api-samples/routes-get-directions-panel": { + "resolved": "samples/routes-get-directions-panel", + "link": true + }, + "node_modules/@js-api-samples/routes-route-matrix": { + "resolved": "samples/routes-route-matrix", + "link": true + }, "node_modules/@js-api-samples/test-example": { "resolved": "samples/test-example", "link": true @@ -8917,6 +8929,18 @@ } } }, + "samples/routes-get-directions": { + "name": "@js-api-samples/routes-get-directions", + "version": "1.0.0" + }, + "samples/routes-get-directions-panel": { + "name": "@js-api-samples/routes-get-directions-panel", + "version": "1.0.0" + }, + "samples/routes-route-matrix": { + "name": "@js-api-samples/routes-route-matrix", + "version": "1.0.0" + }, "samples/test-example": { "name": "@js-api-samples/test-example", "version": "1.0.0"