From 5dec4cdbd23d574dca9071e18dbbadd8400f9543 Mon Sep 17 00:00:00 2001 From: William French Date: Thu, 20 Nov 2025 13:48:40 -0800 Subject: [PATCH] fix: Adds prettier-ignore comments to select ts-ignores. --- samples/place-autocomplete-element/index.ts | 7 +- samples/place-autocomplete-map/index.ts | 69 +- samples/routes-compute-routes/index.ts | 845 ++++++++++---------- samples/routes-route-matrix/index.ts | 175 ++-- 4 files changed, 565 insertions(+), 531 deletions(-) diff --git a/samples/place-autocomplete-element/index.ts b/samples/place-autocomplete-element/index.ts index 7e14b6c2..46b6940e 100644 --- a/samples/place-autocomplete-element/index.ts +++ b/samples/place-autocomplete-element/index.ts @@ -8,9 +8,11 @@ async function initMap(): Promise { // [START maps_place_autocomplete_element_add] // Request needed libraries. - await google.maps.importLibrary("places") as google.maps.PlacesLibrary; + (await google.maps.importLibrary('places')) as google.maps.PlacesLibrary; // Create the input HTML element, and append it. - const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement({}); + const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement( + {} + ); document.body.appendChild(placeAutocomplete); // [END maps_place_autocomplete_element_add] @@ -25,6 +27,7 @@ async function initMap(): Promise { // [START maps_place_autocomplete_element_listener] // Add the gmp-placeselect listener, and display the results. + //prettier-ignore //@ts-ignore placeAutocomplete.addEventListener('gmp-select', async ({ placePrediction }) => { const place = placePrediction.toPlace(); diff --git a/samples/place-autocomplete-map/index.ts b/samples/place-autocomplete-map/index.ts index d9e81ef9..e53d509f 100644 --- a/samples/place-autocomplete-map/index.ts +++ b/samples/place-autocomplete-map/index.ts @@ -7,43 +7,44 @@ // [START maps_place_autocomplete_map] const mapElement = document.querySelector('gmp-map') as google.maps.MapElement; const placeAutocomplete = document.querySelector( - 'gmp-place-autocomplete' + 'gmp-place-autocomplete' ) as google.maps.places.PlaceAutocompleteElement; let innerMap; let marker: google.maps.marker.AdvancedMarkerElement; let infoWindow: google.maps.InfoWindow; let center = { lat: 40.749933, lng: -73.98633 }; // New York City async function initMap(): Promise { - // Request needed libraries. - const [] = await Promise.all([ - google.maps.importLibrary('marker'), - google.maps.importLibrary('places'), - ]); + // Request needed libraries. + const [] = await Promise.all([ + google.maps.importLibrary('marker'), + google.maps.importLibrary('places'), + ]); - // [START maps_place_autocomplete_map_add] - // Get the inner map. - innerMap = mapElement.innerMap; - innerMap.setOptions({ - mapTypeControl: false, - }); + // [START maps_place_autocomplete_map_add] + // Get the inner map. + innerMap = mapElement.innerMap; + innerMap.setOptions({ + mapTypeControl: false, + }); - // Use the bounds_changed event to restrict results to the current map bounds. - google.maps.event.addListener(innerMap, 'bounds_changed', async () => { - placeAutocomplete.locationRestriction = innerMap.getBounds(); - }); - // [END maps_place_autocomplete_map_add] + // Use the bounds_changed event to restrict results to the current map bounds. + google.maps.event.addListener(innerMap, 'bounds_changed', async () => { + placeAutocomplete.locationRestriction = innerMap.getBounds(); + }); + // [END maps_place_autocomplete_map_add] - // Create the marker and infowindow. - marker = new google.maps.marker.AdvancedMarkerElement({ - map: innerMap, - }); + // Create the marker and infowindow. + marker = new google.maps.marker.AdvancedMarkerElement({ + map: innerMap, + }); - infoWindow = new google.maps.InfoWindow({}); + infoWindow = new google.maps.InfoWindow({}); - // [START maps_place_autocomplete_map_listener] - // Add the gmp-placeselect listener, and display the results on the map. - //@ts-ignore - placeAutocomplete.addEventListener('gmp-select', async ({ placePrediction }) => { + // [START maps_place_autocomplete_map_listener] + // Add the gmp-placeselect listener, and display the results on the map. + //prettier-ignore + //@ts-ignore + placeAutocomplete.addEventListener('gmp-select', async ({ placePrediction }) => { const place = placePrediction.toPlace(); await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'], @@ -70,18 +71,18 @@ async function initMap(): Promise { marker.position = place.location; } ); - // [END maps_place_autocomplete_map_listener] + // [END maps_place_autocomplete_map_listener] } // Helper function to create an info window. function updateInfoWindow(content, center) { - infoWindow.setContent(content); - infoWindow.setPosition(center); - infoWindow.open({ - map: innerMap, - anchor: marker, - shouldFocus: false, - }); + infoWindow.setContent(content); + infoWindow.setPosition(center); + infoWindow.open({ + map: innerMap, + anchor: marker, + shouldFocus: false, + }); } initMap(); diff --git a/samples/routes-compute-routes/index.ts b/samples/routes-compute-routes/index.ts index aa36e605..11bcf881 100644 --- a/samples/routes-compute-routes/index.ts +++ b/samples/routes-compute-routes/index.ts @@ -9,290 +9,313 @@ let polylines: google.maps.Polyline[] = []; let waypointInfoWindow: google.maps.InfoWindow | null = null; interface PlaceAutocompleteSelection { - predictionText: string | null; - location: google.maps.LatLng | null; + predictionText: string | null; + location: google.maps.LatLng | null; } const originAutocompleteSelection: PlaceAutocompleteSelection = { - predictionText: null, - location: null, + predictionText: null, + location: null, }; const destinationAutocompleteSelection: PlaceAutocompleteSelection = { - predictionText: null, - location: null, + predictionText: null, + location: null, }; async function init() { - const [ - { InfoWindow }, - { AdvancedMarkerElement }, - //@ts-ignore - { PlaceAutocompleteElement }, - //@ts-ignore - { ComputeRoutesExtraComputation, ReferenceRoute, Route, RouteLabel }, - ] = await Promise.all([ - google.maps.importLibrary('maps') as Promise, - google.maps.importLibrary('marker') as Promise, - google.maps.importLibrary('places') as Promise, - google.maps.importLibrary('routes') as Promise, - ]); - - const map = document.getElementById('map') as google.maps.MapElement; - - attachSubmitListener(); - initializeLocationInputs(); - attachMapClickListener(); - attachTravelModeListener(); - attachAlertWindowListener(); - attachDepartureTimeListener(); - - function attachSubmitListener() { - const computeRoutesForm = document.getElementById( - 'compute-routes-form', - ) as HTMLFormElement; - - computeRoutesForm.addEventListener('submit', (event) => { - event.preventDefault(); - sendRequest(new FormData(computeRoutesForm)); - }); - } - - async function sendRequest(formData: FormData) { - clearMap(); - - try { - const { routes } = await Route.computeRoutes( - buildComputeRoutesJsRequest(formData), - ); - - if (!routes) { - console.log('No routes returned.'); - return; - } - - console.log('Routes:'); - routes.forEach((route) => { - console.log(route.toJSON()); - }); + const [ + { InfoWindow }, + { AdvancedMarkerElement }, + //prettier-ignore + //@ts-ignore + { PlaceAutocompleteElement }, + //prettier-ignore + //@ts-ignore + { ComputeRoutesExtraComputation, ReferenceRoute, Route, RouteLabel }, + ] = await Promise.all([ + google.maps.importLibrary('maps') as Promise, + google.maps.importLibrary( + 'marker' + ) as Promise, + google.maps.importLibrary( + 'places' + ) as Promise, + google.maps.importLibrary( + 'routes' + ) as Promise, + ]); + + const map = document.getElementById('map') as google.maps.MapElement; + + attachSubmitListener(); + initializeLocationInputs(); + attachMapClickListener(); + attachTravelModeListener(); + attachAlertWindowListener(); + attachDepartureTimeListener(); + + function attachSubmitListener() { + const computeRoutesForm = document.getElementById( + 'compute-routes-form' + ) as HTMLFormElement; + + computeRoutesForm.addEventListener('submit', (event) => { + event.preventDefault(); + sendRequest(new FormData(computeRoutesForm)); + }); + } - await Promise.all( - routes.map((route) => - drawRoute( - route, - !!route.routeLabels?.includes(RouteLabel.DEFAULT_ROUTE), - ), - ), - ); - } catch (error: unknown) { - console.error(error); - setErrorMessage((error as Error).message || 'Unknown error.'); + async function sendRequest(formData: FormData) { + clearMap(); + + try { + const { routes } = await Route.computeRoutes( + buildComputeRoutesJsRequest(formData) + ); + + if (!routes) { + console.log('No routes returned.'); + return; + } + + console.log('Routes:'); + routes.forEach((route) => { + console.log(route.toJSON()); + }); + + await Promise.all( + routes.map((route) => + drawRoute( + route, + !!route.routeLabels?.includes(RouteLabel.DEFAULT_ROUTE) + ) + ) + ); + } catch (error: unknown) { + console.error(error); + setErrorMessage((error as Error).message || 'Unknown error.'); + } } - } - function buildComputeRoutesJsRequest( - formData: FormData, - //@ts-ignore - ): google.maps.routes.ComputeRoutesRequest { - const travelMode = - (formData.get('travel_mode') as string) === '' - ? undefined - : (formData.get('travel_mode') as google.maps.TravelMode); - //@ts-ignore - const extraComputations: google.maps.routes.ComputeRoutesExtraComputation[] = + function buildComputeRoutesJsRequest( + formData: FormData + //prettier-ignore + //@ts-ignore + ): google.maps.routes.ComputeRoutesRequest { + const travelMode = + (formData.get('travel_mode') as string) === '' + ? undefined + : (formData.get('travel_mode') as google.maps.TravelMode); + //prettier-ignore + //@ts-ignore + const extraComputations: google.maps.routes.ComputeRoutesExtraComputation[] = []; - //@ts-ignore - const requestedReferenceRoutes: google.maps.routes.ReferenceRoute[] = []; - //@ts-ignore - const transitPreference: google.maps.routes.TransitPreference = {}; - - const request = { - origin: { - location: buildComputeRoutesLocation( - originAutocompleteSelection, - formData.get('origin_location'), - formData.get('heading_org'), - travelMode, - ), - vehicleStopover: formData.get('origin_stopover') === 'on', - sideOfRoad: formData.get('origin_side_of_road') === 'on', - }, - destination: { - location: buildComputeRoutesLocation( - destinationAutocompleteSelection, - formData.get('destination_location'), - formData.get('heading_dest'), - travelMode, - ), - vehicleStopover: formData.get('destination_stopover') === 'on', - sideOfRoad: formData.get('destination_side_of_road') === 'on', - }, - fields: Array.from( - document.querySelectorAll( - 'ul#fields li input[type="checkbox"]:checked', - ), - (input) => (input as HTMLInputElement).value, - ), - travelMode: travelMode as google.maps.TravelMode, - routingPreference: - formData.get('routing_preference') === '' - ? undefined - : (formData.get( - 'routing_preference', - //@ts-ignore - ) as google.maps.routes.RoutingPreference), - polylineQuality: - formData.get('polyline_quality') === '' - ? undefined - : (formData.get( - 'polyline_quality', + //prettier-ignore + //@ts-ignore + const requestedReferenceRoutes: google.maps.routes.ReferenceRoute[] = []; + //prettier-ignore + //@ts-ignore + const transitPreference: google.maps.routes.TransitPreference = {}; + + const request = { + origin: { + location: buildComputeRoutesLocation( + originAutocompleteSelection, + formData.get('origin_location'), + formData.get('heading_org'), + travelMode + ), + vehicleStopover: formData.get('origin_stopover') === 'on', + sideOfRoad: formData.get('origin_side_of_road') === 'on', + }, + destination: { + location: buildComputeRoutesLocation( + destinationAutocompleteSelection, + formData.get('destination_location'), + formData.get('heading_dest'), + travelMode + ), + vehicleStopover: formData.get('destination_stopover') === 'on', + sideOfRoad: formData.get('destination_side_of_road') === 'on', + }, + fields: Array.from( + document.querySelectorAll( + 'ul#fields li input[type="checkbox"]:checked' + ), + (input) => (input as HTMLInputElement).value + ), + travelMode: travelMode as google.maps.TravelMode, + routingPreference: + formData.get('routing_preference') === '' + ? undefined + : (formData.get( + 'routing_preference' + //prettier-ignore + //@ts-ignore + ) as google.maps.routes.RoutingPreference), + polylineQuality: + formData.get('polyline_quality') === '' + ? undefined + : (formData.get( + 'polyline_quality' + //prettier-ignore + //@ts-ignore + ) as google.maps.routes.PolylineQuality), + computeAlternativeRoutes: + formData.get('compute_alternative_routes') === 'on', + routeModifiers: { + avoidTolls: formData.get('avoid_tolls') === 'on', + avoidHighways: formData.get('avoid_highways') === 'on', + avoidFerries: formData.get('avoid_ferries') === 'on', + avoidIndoor: formData.get('avoid_indoor') === 'on', + }, + departureTime: + (formData.get('departure_time') as string) === '' + ? undefined + : new Date(formData.get('departure_time') as string), + extraComputations, + requestedReferenceRoutes, + transitPreference, + }; + + if (formData.get('traffic_aware_polyline') === 'on') { + extraComputations.push( + ComputeRoutesExtraComputation.TRAFFIC_ON_POLYLINE + ); + } + + if (formData.get('shorter_distance') === 'on') { + requestedReferenceRoutes.push(ReferenceRoute.SHORTER_DISTANCE); + } + + if (formData.get('eco_routes') === 'on') { + requestedReferenceRoutes.push(ReferenceRoute.FUEL_EFFICIENT); + extraComputations.push( + ComputeRoutesExtraComputation.FUEL_CONSUMPTION + ); + //prettier-ignore //@ts-ignore - ) as google.maps.routes.PolylineQuality), - computeAlternativeRoutes: - formData.get('compute_alternative_routes') === 'on', - routeModifiers: { - avoidTolls: formData.get('avoid_tolls') === 'on', - avoidHighways: formData.get('avoid_highways') === 'on', - avoidFerries: formData.get('avoid_ferries') === 'on', - avoidIndoor: formData.get('avoid_indoor') === 'on', - }, - departureTime: - (formData.get('departure_time') as string) === '' - ? undefined - : new Date(formData.get('departure_time') as string), - extraComputations, - requestedReferenceRoutes, - transitPreference, - }; - - if (formData.get('traffic_aware_polyline') === 'on') { - extraComputations.push(ComputeRoutesExtraComputation.TRAFFIC_ON_POLYLINE); - } + (request.routeModifiers as google.maps.routes.RouteModifiers).vehicleInfo = + { + emissionType: formData.get( + 'emission_type' + //prettier-ignore + //@ts-ignore + ) as google.maps.routes.VehicleEmissionType, + }; + } - if (formData.get('shorter_distance') === 'on') { - requestedReferenceRoutes.push(ReferenceRoute.SHORTER_DISTANCE); - } + if (travelMode === google.maps.TravelMode.TRANSIT) { + const selectedTransitModes = document.querySelectorAll( + 'ul#transitModes li input[type="checkbox"]:checked' + ); + transitPreference.allowedTransitModes = Array.from( + selectedTransitModes, + (input) => + (input as HTMLInputElement).value as google.maps.TransitMode + ); + transitPreference.routingPreference = + formData.get('transit_preference') === '' + ? undefined + : (formData.get( + 'transit_preference' + ) as google.maps.TransitRoutePreference); + } - if (formData.get('eco_routes') === 'on') { - requestedReferenceRoutes.push(ReferenceRoute.FUEL_EFFICIENT); - extraComputations.push(ComputeRoutesExtraComputation.FUEL_CONSUMPTION); - ( - //@ts-ignore - request.routeModifiers as google.maps.routes.RouteModifiers - ).vehicleInfo = { - emissionType: formData.get( - 'emission_type', - //@ts-ignore - ) as google.maps.routes.VehicleEmissionType, - }; + return request; } - if (travelMode === google.maps.TravelMode.TRANSIT) { - const selectedTransitModes = document.querySelectorAll( - 'ul#transitModes li input[type="checkbox"]:checked', - ); - transitPreference.allowedTransitModes = Array.from( - selectedTransitModes, - (input) => (input as HTMLInputElement).value as google.maps.TransitMode, - ); - transitPreference.routingPreference = - formData.get('transit_preference') === '' - ? undefined - : (formData.get( - 'transit_preference', - ) as google.maps.TransitRoutePreference); - } + function buildComputeRoutesLocation( + autocompleteSelection: PlaceAutocompleteSelection, + locationInput?: FormDataEntryValue | null, + headingInput?: FormDataEntryValue | null, + travelModeInput?: FormDataEntryValue | null + //prettier-ignore + //@ts-ignore + ): string | google.maps.routes.DirectionalLocationLiteral { + if (!locationInput) { + throw new Error('Location is required.'); + } - return request; - } + const latLngRegex = /^-?\d+(\.\d+)?,\s*-?\d+(\.\d+)?$/; + const location = locationInput as string; + const heading = + headingInput && travelModeInput !== 'TRANSIT' + ? Number(headingInput as string) + : undefined; + + if ( + autocompleteSelection.predictionText === location && + autocompleteSelection.location + ) { + // Use the lat/lng from the autocomplete selection if the current input + // matches the autocomplete prediction text + return { + lat: autocompleteSelection.location.lat(), + lng: autocompleteSelection.location.lng(), + altitude: 0, + heading, + }; + } else if (latLngRegex.test(location)) { + // If the current input looks like a lat/lng, format it as a + // google.maps.routes.DirectionalLocationLiteral + return { + lat: Number(location.split(',')[0]), + lng: Number(location.split(',')[1]), + altitude: 0, + heading, + }; + } - function buildComputeRoutesLocation( - autocompleteSelection: PlaceAutocompleteSelection, - locationInput?: FormDataEntryValue | null, - headingInput?: FormDataEntryValue | null, - travelModeInput?: FormDataEntryValue | null, - // @ts-ignore - ): string | google.maps.routes.DirectionalLocationLiteral { - if (!locationInput) { - throw new Error('Location is required.'); + // Otherwise return the input location string + return location; } - const latLngRegex = /^-?\d+(\.\d+)?,\s*-?\d+(\.\d+)?$/; - const location = locationInput as string; - const heading = - headingInput && travelModeInput !== 'TRANSIT' - ? Number(headingInput as string) - : undefined; - - if ( - autocompleteSelection.predictionText === location && - autocompleteSelection.location - ) { - // Use the lat/lng from the autocomplete selection if the current input - // matches the autocomplete prediction text - return { - lat: autocompleteSelection.location.lat(), - lng: autocompleteSelection.location.lng(), - altitude: 0, - heading, - }; - } else if (latLngRegex.test(location)) { - // If the current input looks like a lat/lng, format it as a - // google.maps.routes.DirectionalLocationLiteral - return { - lat: Number(location.split(',')[0]), - lng: Number(location.split(',')[1]), - altitude: 0, - heading, - }; + function setErrorMessage(error: string) { + const alertBox = document.getElementById('alert') as HTMLDivElement; + alertBox.querySelector('p')!.textContent = error; + alertBox.style.display = 'flex'; } - // Otherwise return the input location string - return location; - } + async function drawRoute( + //prettier-ignore + //@ts-ignore + route: google.maps.routes.Route, + isPrimaryRoute: boolean + ) { + polylines = polylines.concat( + route.createPolylines({ + polylineOptions: isPrimaryRoute + ? { map: map.innerMap, zIndex: 1 } + : { + map: map.innerMap, + strokeColor: '#669DF6', + strokeOpacity: 0.5, + strokeWeight: 8, + }, + colorScheme: map.innerMap.get('colorScheme'), + }) + ); - function setErrorMessage(error: string) { - const alertBox = document.getElementById('alert') as HTMLDivElement; - alertBox.querySelector('p')!.textContent = error; - alertBox.style.display = 'flex'; - } + if (isPrimaryRoute) { + markers = markers.concat( + await route.createWaypointAdvancedMarkers({ + map: map.innerMap, + zIndex: 1, + }) + ); + + if (route.viewport) { + map.innerMap.fitBounds(route.viewport); + } + } - async function drawRoute( - //@ts-ignore - route: google.maps.routes.Route, - isPrimaryRoute: boolean, - ) { - polylines = polylines.concat( - route.createPolylines({ - polylineOptions: isPrimaryRoute - ? { map: map.innerMap, zIndex: 1 } - : { - map: map.innerMap, - strokeColor: '#669DF6', - strokeOpacity: 0.5, - strokeWeight: 8, - }, - colorScheme: map.innerMap.get('colorScheme'), - }), - ); - - if (isPrimaryRoute) { - markers = markers.concat( - await route.createWaypointAdvancedMarkers({ - map: map.innerMap, - zIndex: 1, - }), - ); - - if (route.viewport) { - map.innerMap.fitBounds(route.viewport); - } + addRouteLabel(route, Math.floor(route.path!.length / 2)); } - addRouteLabel(route, Math.floor(route.path!.length / 2)); - } - - //@ts-ignore - function addRouteLabel(route: google.maps.routes.Route, index: number) { + //prettier-ignore + //@ts-ignore + function addRouteLabel(route: google.maps.routes.Route, index: number) { const routeTag = document.createElement('div'); routeTag.className = 'route-tag'; @@ -351,152 +374,156 @@ async function init() { markers.push(marker); } - function clearMap() { - markers.forEach((marker) => { - marker.map = null; - }); - markers.length = 0; - - polylines.forEach((polyline) => { - polyline.setMap(null); - }); - polylines.length = 0; - } - - function attachMapClickListener() { - if (!map || !map.innerMap) { - return; - } + function clearMap() { + markers.forEach((marker) => { + marker.map = null; + }); + markers.length = 0; - let infoWindowAlert = document.getElementById('infowindow-alert'); - if (!infoWindowAlert) { - infoWindowAlert = document.createElement('div'); - infoWindowAlert.id = infoWindowAlert.className = 'infowindow-alert'; - infoWindowAlert.textContent = 'Lat/Lng are copied to clipboard'; + polylines.forEach((polyline) => { + polyline.setMap(null); + }); + polylines.length = 0; } - const infoWindow = new InfoWindow(); - let closeWindowTimeout: number; - - map.innerMap.addListener( - 'click', - async (mapsMouseEvent: google.maps.MapMouseEvent) => { - if (!mapsMouseEvent.latLng) { - return; + function attachMapClickListener() { + if (!map || !map.innerMap) { + return; } - infoWindow.close(); - if (closeWindowTimeout) { - clearTimeout(closeWindowTimeout); + let infoWindowAlert = document.getElementById('infowindow-alert'); + if (!infoWindowAlert) { + infoWindowAlert = document.createElement('div'); + infoWindowAlert.id = infoWindowAlert.className = 'infowindow-alert'; + infoWindowAlert.textContent = 'Lat/Lng are copied to clipboard'; } - infoWindow.setContent(infoWindowAlert); - infoWindow.setPosition({ - lat: mapsMouseEvent.latLng.lat(), - lng: mapsMouseEvent.latLng.lng(), - }); - - await navigator.clipboard.writeText( - `${mapsMouseEvent.latLng.lat()},${mapsMouseEvent.latLng.lng()}`, + const infoWindow = new InfoWindow(); + let closeWindowTimeout: number; + + map.innerMap.addListener( + 'click', + async (mapsMouseEvent: google.maps.MapMouseEvent) => { + if (!mapsMouseEvent.latLng) { + return; + } + + infoWindow.close(); + if (closeWindowTimeout) { + clearTimeout(closeWindowTimeout); + } + + infoWindow.setContent(infoWindowAlert); + infoWindow.setPosition({ + lat: mapsMouseEvent.latLng.lat(), + lng: mapsMouseEvent.latLng.lng(), + }); + + await navigator.clipboard.writeText( + `${mapsMouseEvent.latLng.lat()},${mapsMouseEvent.latLng.lng()}` + ); + + infoWindow.open(map.innerMap); + closeWindowTimeout = window.setTimeout(() => { + infoWindow.close(); + }, 2000); + } ); + } - infoWindow.open(map.innerMap); - closeWindowTimeout = window.setTimeout(() => { - infoWindow.close(); - }, 2000); - }, - ); - } - - function attachTravelModeListener() { - const travelMode = document.getElementById( - 'travel-mode', - ) as HTMLSelectElement; - const routingPreference = document.getElementById( - 'routing-preference', - ) as HTMLSelectElement; - const trafficAwarePolyline = document.getElementById( - 'traffic-aware-polyline', - ) as HTMLInputElement; - const ecoRoutes = document.getElementById('eco-routes') as HTMLInputElement; - const emissionType = document.getElementById( - 'emission-type', - ) as HTMLSelectElement; - - travelMode.addEventListener('change', () => { - // Toggle the Routing Preference selection and Traffic Aware Polyline - // selection for WALKING, BICYCLING, and TRANSIT modes. - if ( - travelMode.value === 'WALKING' || - travelMode.value === 'BICYCLING' || - travelMode.value === 'TRANSIT' - ) { - routingPreference.disabled = true; - routingPreference.value = ''; - } else { - routingPreference.disabled = false; - routingPreference.value = routingPreference.value || 'TRAFFIC_UNAWARE'; - } - - toggleTrafficAwarePolyline(); - - // Toggle transit options for Transit mode - ( - document.getElementById('transit-options') as HTMLElement - ).style.display = travelMode.value === 'TRANSIT' ? 'flex' : 'none'; - }); + function attachTravelModeListener() { + const travelMode = document.getElementById( + 'travel-mode' + ) as HTMLSelectElement; + const routingPreference = document.getElementById( + 'routing-preference' + ) as HTMLSelectElement; + const trafficAwarePolyline = document.getElementById( + 'traffic-aware-polyline' + ) as HTMLInputElement; + const ecoRoutes = document.getElementById( + 'eco-routes' + ) as HTMLInputElement; + const emissionType = document.getElementById( + 'emission-type' + ) as HTMLSelectElement; + + travelMode.addEventListener('change', () => { + // Toggle the Routing Preference selection and Traffic Aware Polyline + // selection for WALKING, BICYCLING, and TRANSIT modes. + if ( + travelMode.value === 'WALKING' || + travelMode.value === 'BICYCLING' || + travelMode.value === 'TRANSIT' + ) { + routingPreference.disabled = true; + routingPreference.value = ''; + } else { + routingPreference.disabled = false; + routingPreference.value = + routingPreference.value || 'TRAFFIC_UNAWARE'; + } + + toggleTrafficAwarePolyline(); + + // Toggle transit options for Transit mode + ( + document.getElementById('transit-options') as HTMLElement + ).style.display = travelMode.value === 'TRANSIT' ? 'flex' : 'none'; + }); - routingPreference.addEventListener('change', () => { - toggleTrafficAwarePolyline(); - }); + routingPreference.addEventListener('change', () => { + toggleTrafficAwarePolyline(); + }); - ecoRoutes.addEventListener('change', () => { - if (ecoRoutes.checked) { - emissionType.disabled = false; - } else { - emissionType.disabled = true; - } - }); + ecoRoutes.addEventListener('change', () => { + if (ecoRoutes.checked) { + emissionType.disabled = false; + } else { + emissionType.disabled = true; + } + }); - function toggleTrafficAwarePolyline() { - if ( - !routingPreference.value || - routingPreference.value === 'TRAFFIC_UNAWARE' - ) { - trafficAwarePolyline.checked = false; - trafficAwarePolyline.disabled = true; - } else { - trafficAwarePolyline.disabled = false; - } + function toggleTrafficAwarePolyline() { + if ( + !routingPreference.value || + routingPreference.value === 'TRAFFIC_UNAWARE' + ) { + trafficAwarePolyline.checked = false; + trafficAwarePolyline.disabled = true; + } else { + trafficAwarePolyline.disabled = false; + } + } } - } - function attachAlertWindowListener() { - const alertBox = document.getElementById('alert') as HTMLDivElement; - const closeBtn = alertBox.querySelector('.close') as HTMLButtonElement; - closeBtn.addEventListener('click', () => { - if (alertBox.style.display !== 'none') { - alertBox.style.display = 'none'; - } - }); - } + function attachAlertWindowListener() { + const alertBox = document.getElementById('alert') as HTMLDivElement; + const closeBtn = alertBox.querySelector('.close') as HTMLButtonElement; + closeBtn.addEventListener('click', () => { + if (alertBox.style.display !== 'none') { + alertBox.style.display = 'none'; + } + }); + } - function initializeLocationInputs() { - const originAutocomplete = new PlaceAutocompleteElement({ - name: 'origin_location', - }); - const destinationAutocomplete = new PlaceAutocompleteElement({ - name: 'destination_location', - }); + function initializeLocationInputs() { + const originAutocomplete = new PlaceAutocompleteElement({ + name: 'origin_location', + }); + const destinationAutocomplete = new PlaceAutocompleteElement({ + name: 'destination_location', + }); - [ - [originAutocomplete, originAutocompleteSelection], - [destinationAutocomplete, destinationAutocompleteSelection], - ].forEach(([autocomplete, autocompleteData]) => { - autocomplete.addEventListener( - 'gmp-select', - //@ts-ignore - async (event: google.maps.places.PlacePredictionSelectEvent) => { + [ + [originAutocomplete, originAutocompleteSelection], + [destinationAutocomplete, destinationAutocompleteSelection], + ].forEach(([autocomplete, autocompleteData]) => { + autocomplete.addEventListener( + 'gmp-select', + //prettier-ignore + //@ts-ignore + async (event: google.maps.places.PlacePredictionSelectEvent) => { autocompleteData.predictionText = event.placePrediction.text.text; const place = event.placePrediction.toPlace(); @@ -504,29 +531,31 @@ async function init() { fields: ['location'], }); autocompleteData.location = place.location; - }, - ); - }); + } + ); + }); - document.getElementById('origin-input')?.appendChild(originAutocomplete); - document - .getElementById('destination-input') - ?.appendChild(destinationAutocomplete); - } + document + .getElementById('origin-input') + ?.appendChild(originAutocomplete); + document + .getElementById('destination-input') + ?.appendChild(destinationAutocomplete); + } - function attachDepartureTimeListener() { - const departureTime = document.getElementById( - 'departure-time', - ) as HTMLInputElement; - const utcOutput = document.getElementById( - 'utc-output', - ) as HTMLParagraphElement; - departureTime.addEventListener('change', () => { - utcOutput.textContent = `UTC time: ${new Date( - departureTime.value, - ).toUTCString()}`; - }); - } + function attachDepartureTimeListener() { + const departureTime = document.getElementById( + 'departure-time' + ) as HTMLInputElement; + const utcOutput = document.getElementById( + 'utc-output' + ) as HTMLParagraphElement; + departureTime.addEventListener('change', () => { + utcOutput.textContent = `UTC time: ${new Date( + departureTime.value + ).toUTCString()}`; + }); + } } window.addEventListener('load', init); diff --git a/samples/routes-route-matrix/index.ts b/samples/routes-route-matrix/index.ts index 0589e78f..18db1f5a 100644 --- a/samples/routes-route-matrix/index.ts +++ b/samples/routes-route-matrix/index.ts @@ -10,112 +10,113 @@ 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([ + // Request the needed libraries. + //prettier-ignore + //@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(); + const bounds = new google.maps.LatLngBounds(); - map = new Map(document.getElementById('map') as HTMLElement, { - zoom: 8, - center: center, - mapId: 'DEMO_MAP_ID', - }); + 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 - }); + // 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']}), - ]); + await Promise.all([ + origin1.fetchFields({ fields: ['location', 'displayName'] }), + origin2.fetchFields({ fields: ['location', 'displayName'] }), + destinationA.fetchFields({ fields: ['location', 'displayName'] }), + destinationB.fetchFields({ fields: ['location', 'displayName'] }), + ]); + + // [START maps_routes_route_matrix_request] + const request = { + origins: [origin1, origin2], + destinations: [destinationA, destinationB], + travelMode: 'DRIVING', + units: google.maps.UnitSystem.METRIC, + fields: ['distanceMeters', 'durationMillis', 'condition'], + }; + // [END maps_routes_route_matrix_request] - // [START maps_routes_route_matrix_request] - const request = { - origins: [origin1, origin2], - destinations: [destinationA, destinationB], - travelMode: 'DRIVING', - units: google.maps.UnitSystem.METRIC, - fields: ['distanceMeters', 'durationMillis', 'condition'], - }; - // [END maps_routes_route_matrix_request] + // Show the request. + (document.getElementById('request') as HTMLDivElement).innerText = + JSON.stringify(request, null, 2); - // Show the request. - (document.getElementById("request") as HTMLDivElement).innerText = - JSON.stringify(request, null, 2); + // Get the RouteMatrix response. + const response = await RouteMatrix.computeRouteMatrix(request); - // Get the RouteMatrix response. - const response = await RouteMatrix.computeRouteMatrix(request); + // Show the response. + (document.getElementById('response') as HTMLDivElement).innerText = + JSON.stringify(response, null, 2); - // 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({ - //@ts-ignore - glyphText: "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 origins. + for (const origin of request.origins) { + if (origin.location) { + const pin = new PinElement({ + //@ts-ignore + glyphText: '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({ - //@ts-ignore - glyphText: "D", - glyphColor: "white", - background: "#C5221F", - borderColor: "white", - }); + // 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({ + //@ts-ignore + glyphText: 'D', + glyphColor: 'white', + background: '#C5221F', + borderColor: 'white', + }); - const marker = new AdvancedMarkerElement({ - map, - position: destination.location, - content: pin.element, - title: `Destination: ${destination.displayName}`, - }); + const marker = new AdvancedMarkerElement({ + map, + position: destination.location, + content: pin.element, + title: `Destination: ${destination.displayName}`, + }); - markers.push(marker); - bounds.extend(destination.location); + markers.push(marker); + bounds.extend(destination.location); + } } - } - // Fit the map to the bounds of all markers. - map.fitBounds(bounds); + // Fit the map to the bounds of all markers. + map.fitBounds(bounds); } initMap();