### Basic getDetails Call Source: https://developers.google.com/maps/documentation/javascript/places A minimal example demonstrating the initialization of the PlacesService and the call to `getDetails` with a specified place ID and callback. ```javascript service = new google.maps.places.PlacesService(map); service.getDetails(request, callback); ``` -------------------------------- ### Fetch Autocomplete Suggestions and Place Details (JavaScript) Source: https://developers.google.com/maps/documentation/javascript/place-autocomplete-data This JavaScript example demonstrates calling `fetchAutocompleteSuggestions()` for an input, then calling `toPlace()` on the first prediction result, followed by a call to `fetchFields()` to get place details. It requires importing 'places' library and creating an AutocompleteSessionToken. ```javascript async function init() { const { AutocompleteSessionToken, AutocompleteSuggestion } = await google.maps.importLibrary('places'); // Add an initial request body. const request = { input: 'Tadi', locationRestriction: { west: -122.44, north: 37.8, east: -122.39, south: 37.78, }, origin: { lat: 37.7893, lng: -122.4039 }, includedPrimaryTypes: ['restaurant'], language: 'en-US', region: 'us', }; // Create a session token. const token = new AutocompleteSessionToken(); // Add the token to the request. request.sessionToken = token; // Fetch autocomplete suggestions. const { suggestions } = await AutocompleteSuggestion.fetchAutocompleteSuggestions(request); const title = document.getElementById('title'); title.appendChild( document.createTextNode( 'Query predictions for "' + request.input + '":' ) ); const resultsElement = document.getElementById('results'); for (const suggestion of suggestions) { const placePrediction = suggestion.placePrediction; // Create a new list element. const listItem = document.createElement('li'); listItem.appendChild( document.createTextNode(placePrediction.text.toString()) ); resultsElement.appendChild(listItem); } const place = suggestions[0].placePrediction.toPlace(); // Get first predicted place. await place.fetchFields({ fields: ['displayName', 'formattedAddress'], }); const placeInfo = document.getElementById('prediction'); placeInfo.textContent = `First predicted place: ${place.displayName}: ${place.formattedAddress}`; } void init(); index.js ``` -------------------------------- ### Fetch Autocomplete Suggestions and Place Details Source: https://developers.google.com/maps/documentation/javascript/place-autocomplete-data This example demonstrates calling `fetchAutocompleteSuggestions()` for an input, then calling `toPlace()` on the first prediction result, followed by a call to `fetchFields()` to get place details. It requires importing 'places' library and creating an AutocompleteSessionToken. ```typescript async function init() { const { AutocompleteSessionToken, AutocompleteSuggestion } = await google.maps.importLibrary('places'); // Add an initial request body. const request: google.maps.places.AutocompleteRequest = { input: 'Tadi', locationRestriction: { west: -122.44, north: 37.8, east: -122.39, south: 37.78, }, origin: { lat: 37.7893, lng: -122.4039 }, includedPrimaryTypes: ['restaurant'], language: 'en-US', region: 'us', }; // Create a session token. const token = new AutocompleteSessionToken(); // Add the token to the request. request.sessionToken = token; // Fetch autocomplete suggestions. const { suggestions } = await AutocompleteSuggestion.fetchAutocompleteSuggestions(request); const title = document.getElementById('title')!; title.appendChild( document.createTextNode( 'Query predictions for "' + request.input + '":' ) ); const resultsElement = document.getElementById('results')!; for (const suggestion of suggestions) { const placePrediction = suggestion.placePrediction; // Create a new list element. const listItem = document.createElement('li'); listItem.appendChild( // eslint-disable-next-line @typescript-eslint/no-base-to-string document.createTextNode(placePrediction!.text.toString()) ); resultsElement.appendChild(listItem); } const place = suggestions[0].placePrediction!.toPlace(); // Get first predicted place. await place.fetchFields({ fields: ['displayName', 'formattedAddress'], }); const placeInfo = document.getElementById('prediction')!; placeInfo.textContent = `First predicted place: ${place.displayName}: ${place.formattedAddress}`; } void init(); index.ts ``` -------------------------------- ### HTML Structure for Place Autocomplete Source: https://developers.google.com/maps/documentation/javascript/place-autocomplete-new Sets up the basic HTML structure for the Place Autocomplete example, including linking the CSS and JavaScript files, and includes a script for loading the Google Maps JavaScript API. ```html Place Autocomplete element

Search for a place here:

``` -------------------------------- ### Initialize Autocomplete with Options Source: https://developers.google.com/maps/documentation/javascript/place-autocomplete Instantiate the Autocomplete widget with specific options to constrain predictions by geographic bounds, country, and desired data fields. This example sets up the widget at construction time. ```typescript const center = { lat: 50.064192, lng: -130.605469 }; // Create a bounding box with sides ~10km away from the center point const defaultBounds = { north: center.lat + 0.1, south: center.lat - 0.1, east: center.lng + 0.1, west: center.lng - 0.1, }; const input = document.getElementById("pac-input") as HTMLInputElement; const options = { bounds: defaultBounds, componentRestrictions: { country: "us" }, fields: ["address_components", "geometry", "icon", "name"], strictBounds: false, }; const autocomplete = new google.maps.places.Autocomplete(input, options); ``` ```javascript const center = { lat: 50.064192, lng: -130.605469 }; // Create a bounding box with sides ~10km away from the center point const defaultBounds = { north: center.lat + 0.1, south: center.lat - 0.1, east: center.lng + 0.1, west: center.lng - 0.1, }; const input = document.getElementById("pac-input"); const options = { bounds: defaultBounds, componentRestrictions: { country: "us" }, fields: ["address_components", "geometry", "icon", "name"], strictBounds: false, }; const autocomplete = new google.maps.places.Autocomplete(input, options); ``` -------------------------------- ### Get Place Details with Reviews (Legacy PlacesService) Source: https://developers.google.com/maps/documentation/javascript/places-migration-reviews This snippet demonstrates how to use the legacy `PlacesService` to fetch place details, including reviews, and display the first review in an infowindow. It requires a `google.maps.places.PlacesService` instance and uses a callback to handle the results. ```javascript const request = { placeId: "ChIJpyiwa4Zw44kRBQSGWKv4wgA", // Faneuil Hall Marketplace, Boston, MA fields: ["name", "formatted_address", "geometry", "reviews"], }; const service = new google.maps.places.PlacesService(map); service.getDetails(request, (place, status) => { if ( status === google.maps.places.PlacesServiceStatus.OK && place && place.geometry && place.geometry.location ) { // If there are any reviews display the first one. if (place.reviews && place.reviews.length > 0) { // Get info for the first review. let reviewRating = place.reviews[0].rating; let reviewText = place.reviews[0].text; let authorName = place.reviews[0].author_name; let authorUri = place.reviews[0].author_url; // Format the review using HTML. contentString =`
${place.name}
${place.formatted_address}
Author: ${authorName}
Rating: ${reviewRating} stars

Review: ${reviewText}

`; } else { contentString = `No reviews were found for ${place.name}`; } const infowindow = new google.maps.InfoWindow({ content: contentString, ariaLabel: place.displayName, }); // Add a marker. const marker = new google.maps.Marker({ map, position: place.geometry.location, }); // Show the info window. infowindow.open({ anchor: marker, map, }); } }); ``` -------------------------------- ### Load Places Library within an Async Function Source: https://developers.google.com/maps/documentation/javascript/place-get-started This example shows how to load the Places Library by calling `importLibrary("places")` within an `async` function, `initMap()`, and then immediately invoking `initMap()`. ```javascript async function initMap() { google.maps.importLibrary("places"); ... } initMap(); ``` -------------------------------- ### Create Search Input and Button Source: https://developers.google.com/maps/documentation/javascript/places-ui-kit/place-list Implement an HTML input field for user search queries and a button to trigger the search. This setup allows users to interactively search for places. ```html
``` -------------------------------- ### Apply Place Icon and Color to a Marker (JavaScript) Source: https://developers.google.com/maps/documentation/javascript/place-icons Customize a marker using a place's icon, background color, name, and location data. This example uses `place.iconBackgroundColor` for the marker background and `place.svgIconMaskURI` for the glyph. Ensure you fetch the necessary fields before applying them. ```javascript // A marker customized using a place icon and color, name, and geometry. const place = new Place({ id: "ChIJN5Nz71W3j4ARhx5bwpTQEGg", }); // Call fetchFields, passing the desired data fields. await place.fetchFields({ fields: [ "location", "displayName", "svgIconMaskURI", "iconBackgroundColor", ], }); const pinElement = new PinElement({ background: place.iconBackgroundColor, glyph: new URL(String(place.svgIconMaskURI)), }); const placeIconMarkerView = new AdvancedMarkerElement({ map, position: place.location, content: pinElement.element, title: place.displayName, }); index.js ``` -------------------------------- ### Display Place Details on Map (JavaScript) Source: https://developers.google.com/maps/documentation/javascript/place-autocomplete-new This JavaScript example demonstrates handling place selections to update a map. It fetches place details and then adjusts the map's view (fitting bounds or centering) and updates an info window and marker. ```javascript // Add the gmp-select listener, and display the results on the map. placeAutocomplete.addEventListener( 'gmp-select', async ({ placePrediction }) => { const place = placePrediction.toPlace(); await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'], }); // If the place has a geometry, then present it on a map. if (place.viewport) { innerMap.fitBounds(place.viewport); } else { innerMap.setCenter(place.location); innerMap.setZoom(17); } const content = document.createElement('div'); const nameText = document.createElement('span'); nameText.textContent = place.displayName ?? 'No name'; content.appendChild(nameText); content.appendChild(document.createElement('br')); const addressText = document.createElement('span'); addressText.textContent = place.formattedAddress ?? 'No address'; content.appendChild(addressText); updateInfoWindow(content, place.location); marker.position = place.location; } ); ``` -------------------------------- ### Retrieve Autocomplete Predictions (Legacy) Source: https://developers.google.com/maps/documentation/javascript/places-migration-autocomplete Use the legacy Places Service for programmatic control over UI elements. This example shows how to make a request with input and bounds, and then display predictions and fetch details for the first result. ```javascript function init() { const placeInfo = document.getElementById("prediction"); const service = new google.maps.places.AutocompleteService(); const placesService = new google.maps.places.PlacesService(placeInfo); var sessionToken = new google.maps.places.AutocompleteSessionToken(); // Define request options. let request = { input: "par", sessionToken: sessionToken, bounds: { west: -122.44, north: 37.8, east: -122.39, south: 37.78, }, } // Display the query string. const title = document.getElementById("title"); title.appendChild( document.createTextNode('Place predictions for "' + request.input + '":'), ); // Perform the query and display the results. const displaySuggestions = function (predictions, status) { // Check the status of the Places Service. if (status != google.maps.places.PlacesServiceStatus.OK || !predictions) { alert(status); return; } predictions.forEach((prediction) => { const li = document.createElement("li"); li.appendChild(document.createTextNode(prediction.description)); document.getElementById("results").appendChild(li); }); const placeRequest = { placeId: predictions[0].place_id, fields: ["name", "formatted_address"], }; placesService.getDetails(placeRequest, (place, status) => { if (status == google.maps.places.PlacesServiceStatus.OK && place) { placeInfo.textContent = ` First predicted place: ${place.name} at ${place.formatted_address}` } }); }; // Show the results of the query. service.getPlacePredictions(request, displaySuggestions); } ``` -------------------------------- ### Apply Place Icon and Color to a Marker (TypeScript) Source: https://developers.google.com/maps/documentation/javascript/place-icons Customize a marker using a place's icon, background color, name, and location data. This example uses `place.iconBackgroundColor` for the marker background and `place.svgIconMaskURI` for the glyph. Ensure you fetch the necessary fields before applying them. ```typescript // A marker customized using a place icon and color, name, and geometry. const place = new Place({ id: 'ChIJN5Nz71W3j4ARhx5bwpTQEGg', }); // Call fetchFields, passing the desired data fields. await place.fetchFields({ fields: ['location', 'displayName', 'svgIconMaskURI', 'iconBackgroundColor'] }); const pinElement = new PinElement({ background: place.iconBackgroundColor, glyph: new URL(String(place.svgIconMaskURI)), }); const placeIconMarkerView = new AdvancedMarkerElement({ map, position: place.location, content: pinElement.element, title: place.displayName, }); index.ts ``` -------------------------------- ### Display Place Details on Map (TypeScript) Source: https://developers.google.com/maps/documentation/javascript/place-autocomplete-new This TypeScript example shows how to use the `gmp-select` event to fetch place details and then display them on a map. It fits the map bounds to the place's viewport or centers the map on the place's location. ```typescript // Add the gmp-select listener, and display the results on the map. placeAutocomplete.addEventListener( 'gmp-select', async ({ placePrediction }) => { const place = placePrediction.toPlace(); await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'], }); // If the place has a geometry, then present it on a map. if (place.viewport) { innerMap.fitBounds(place.viewport); } else { innerMap.setCenter(place.location!); innerMap.setZoom(17); } const content = document.createElement('div'); const nameText = document.createElement('span'); nameText.textContent = place.displayName ?? 'No name'; content.appendChild(nameText); content.appendChild(document.createElement('br')); const addressText = document.createElement('span'); addressText.textContent = place.formattedAddress ?? 'No address'; content.appendChild(addressText); updateInfoWindow(content, place.location); marker.position = place.location; } ); ``` -------------------------------- ### Display Place and Review Summaries with PlaceDetailsElement Source: https://developers.google.com/maps/documentation/javascript/places-ui-kit/ai-powered-summaries-ui-kit Configure the `PlaceDetailsElement` to display both place summaries and review summaries. Ensure the `gmp-place-review-summary` attribute is used for review summaries. This setup includes place requests, content configuration, and attribution. ```html
``` -------------------------------- ### Display Place Photos in TypeScript Source: https://developers.google.com/maps/documentation/javascript/place-photos Use the Place Photos library to fetch and display images for a given place ID. This example shows how to create image elements, handle click events for larger views, and display author attributions. Ensure the 'places' library is imported. ```typescript async function init() { const { Place } = await google.maps.importLibrary('places'); // Use a place ID to create a new Place instance. const place = new Place({ id: 'ChIJydSuSkkUkFQRsqhB-cEtYnw', // Woodland Park Zoo, Seattle WA }); // Call fetchFields, passing the desired data fields. await place.fetchFields({ fields: ['displayName', 'photos', 'editorialSummary'], }); // Get the various HTML elements. const heading = document.getElementById('heading')!; const summary = document.getElementById('summary')!; const gallery = document.getElementById('gallery')!; const expandedImageDiv = document.getElementById('expanded-image')!; // Show the display name and summary for the place. heading.textContent = place.displayName!; summary.textContent = place.editorialSummary!; // Add photos to the gallery. place.photos?.forEach((photo) => { const altText = 'Photo of ' + place.displayName; const img = document.createElement('img'); const imgButton = document.createElement('button'); const expandedImage = document.createElement('img'); img.src = photo?.getURI({ maxHeight: 380 }); img.alt = altText; imgButton.addEventListener('click', (event) => { centerSelectedThumbnail(imgButton); event.preventDefault(); expandedImage.src = img.src; expandedImage.alt = altText; expandedImageDiv.innerHTML = ''; expandedImageDiv.appendChild(expandedImage); const attributionLabel = createAttribution( photo.authorAttributions[0] ); expandedImageDiv.appendChild(attributionLabel); }); imgButton.addEventListener('focus', () => { centerSelectedThumbnail(imgButton); }); imgButton.appendChild(img); gallery.appendChild(imgButton); }); // Display the first photo. if (place.photos && place.photos.length > 0) { const photo = place.photos[0]; const img = document.createElement('img'); img.alt = 'Photo of ' + place.displayName; img.src = photo.getURI(); expandedImageDiv.appendChild(img); if (photo.authorAttributions && photo.authorAttributions.length > 0) { expandedImageDiv.appendChild( createAttribution(photo.authorAttributions[0]) ); } } // Helper function to create attribution DIV. function createAttribution( attribution: google.maps.places.AuthorAttribution ) { const attributionLabel = document.createElement('a'); attributionLabel.classList.add('attribution-label'); attributionLabel.textContent = attribution.displayName; attributionLabel.href = attribution.uri!; attributionLabel.target = '_blank'; attributionLabel.rel = 'noopener noreferrer'; return attributionLabel; } // Helper function to center the selected thumbnail in the gallery. function centerSelectedThumbnail(element: HTMLElement) { element.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'center', }); } } void init(); index.ts ``` -------------------------------- ### Initialize Map and Place Details Source: https://developers.google.com/maps/documentation/javascript/places-ui-kit/place-details Sets up the map, advanced marker, and info window. Handles map clicks to display place details, falling back to the place's location for initial load. ```javascript // Use querySelector to select elements for interaction. const map = document.querySelector('gmp-map'); const placeDetails = document.querySelector('gmp-place-details-compact'); const placeDetailsRequest = document.querySelector( 'gmp-place-details-place-request' ); const marker = document.querySelector('gmp-advanced-marker'); async function init() { // Request needed libraries. void Promise.all([ google.maps.importLibrary('marker'), google.maps.importLibrary('places'), ]); const { InfoWindow } = await google.maps.importLibrary('maps'); await window.customElements.whenDefined('gmp-map'); // Set the inner map options. map.innerMap.setOptions({ mapTypeControl: false, streetViewControl: false, }); await window.customElements.whenDefined('gmp-advanced-marker'); marker.collisionBehavior = 'REQUIRED_AND_HIDES_OPTIONAL'; const infoWindow = new InfoWindow(); infoWindow.addListener('close', () => { marker.position = null; }); const showInfoWindow = () => { if (infoWindow.isOpen) return; infoWindow.setContent(placeDetails); infoWindow.open({ anchor: marker }); }; placeDetails.addEventListener('gmp-load', () => { // For the initial load case, with no user click, we fall back to the place's location, and ensure the map has a center set and the InfoWindow is show. // (The clicked POI LatLng will be a more natural marker position, when available.) if (!map.center && placeDetails.place?.location) { map.center = marker.position = placeDetails.place.location; showInfoWindow(); } }); // Add an event listener to handle clicks. map.innerMap.addListener('click', (event) => { event.stop(); if ('placeId' in event) { // When the user clicks a POI. marker.position = event.latLng; placeDetailsRequest.place = event.placeId; showInfoWindow(); } else { // When the user clicks the map (not on a POI). marker.position = null; placeDetailsRequest.place = null; console.log('No place was selected.'); } }); } void init(); index.js ``` -------------------------------- ### AutocompleteService.getQueryPredictions Source: https://developers.google.com/maps/documentation/javascript/places-autocomplete Retrieves autocomplete predictions programmatically from the autocomplete service and displays them as an HTML list. This example demonstrates how to use `getQueryPredictions` to get suggestions for a given input string. ```APIDOC ## AutocompleteService.getQueryPredictions ### Description Retrieves an extended list of predictions, which can include places as well as suggested search terms. This is useful for providing more comprehensive search suggestions to users. ### Method `getQueryPredictions(request: AutocompleteService.QueryAutocompleteRequest, callback: (result: google.maps.places.QueryAutocompletePrediction[] | null, status: google.maps.places.PlacesServiceStatus) => void): void` ### Parameters #### Request Body - **input** (string) - Required - The text entered by the user. - **callback** (function) - Required - A callback function that is executed when the request completes. It receives an array of prediction objects and the status of the request. ### Request Example ```typescript const service = new google.maps.places.AutocompleteService(); service.getQueryPredictions({ input: "pizza near Syd" }, displaySuggestions); ``` ### Response #### Success Response (OK) - **predictions** (Array) - An array of prediction objects. - **description** (string) - The matched prediction text. - **distance_meters** (number) - The distance in meters of the place from the specified origin. - **matched_substrings** (Array) - Substrings in the description that match elements in the user's input. - **length** (number) - The length of the substring. - **offset** (number) - The character offset of the substring. - **place_id** (string) - A textual identifier that uniquely identifies a place. - **terms** (Array) - An array containing elements of the query. - **offset** (number) - The character offset of the matched substring. - **value** (string) - The matching term. #### Status Codes - **OK**: Indicates that no error occurred. - Other statuses indicate an error (e.g., `ZERO_RESULTS`, `INVALID_REQUEST`). ``` -------------------------------- ### Initialize Map and Place Search Functionality Source: https://developers.google.com/maps/documentation/javascript/places-ui-kit/place-list Sets up the map, place search, and details components, along with event listeners for user interactions. Imports necessary libraries and configures map options. ```javascript // Query selectors for various elements in the HTML file. const map = document.querySelector('gmp-map'); const placeSearch = document.querySelector('gmp-place-search'); const placeSearchQuery = document.querySelector( 'gmp-place-nearby-search-request' ); const placeDetails = document.querySelector('gmp-place-details-compact'); const placeRequest = document.querySelector('gmp-place-details-place-request'); const typeSelect = document.querySelector('.type-select'); // Global variables for the map, markers, and info window. const markers = new Map(); let infoWindow; // The init function is called when the page loads. async function init() { // Import the necessary libraries from the Google Maps API. const [{ InfoWindow }] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('places'), ]); // Create a new info window and set its content to the place details element. placeDetails.remove(); // Hide the place details element because it is not needed until the info window opens infoWindow = new InfoWindow({ content: placeDetails, ariaLabel: 'Place Details', }); // Set the map options. map.innerMap.setOptions({ clickableIcons: false, mapTypeControl: false, streetViewControl: false, }); // Add event listeners to the type select and place search elements. typeSelect.addEventListener('change', () => { searchPlaces(); }); placeSearch.addEventListener('gmp-select', (event) => { const { place } = event; markers.get(place.id)?.click(); }); placeSearch.addEventListener('gmp-load', () => { void addMarkers(); }); searchPlaces(); } // The searchPlaces function is called when the user changes the type select or when the page loads. function searchPlaces() { // Close the info window and clear the markers. infoWindow.close(); for (const marker of markers.values()) { marker.remove(); } markers.clear(); // Set the place search query and add an event listener to the place search element. if (typeSelect.value) { const center = map.center; placeSearchQuery.locationRestriction = { center, radius: 50000, // 50km radius }; placeSearchQuery.includedTypes = [typeSelect.value]; } } // The addMarkers function is called when the place search element loads. async function addMarkers() { // Import the necessary libraries from the Google Maps API. const [{ AdvancedMarkerElement }, { LatLngBounds }] = await Promise.all([ google.maps.importLibrary('marker'), google.maps.importLibrary('core'), ]); const bounds = new LatLngBounds(); if (placeSearch.places.length === 0) { return; } for (const place of placeSearch.places) { if (!place.location) continue; const marker = new AdvancedMarkerElement({ map: map.innerMap, position: place.location, collisionBehavior: 'REQUIRED_AND_HIDES_OPTIONAL', }); markers.set(place.id, marker); bounds.extend(place.location); marker.addListener('click', () => { placeRequest.place = place; infoWindow.open(map.innerMap, marker); }); } map.innerMap.fitBounds(bounds); } void init(); index.js ``` -------------------------------- ### Retrieve Place Predictions with AutocompleteService (JavaScript) Source: https://developers.google.com/maps/documentation/javascript/places-autocomplete Use AutocompleteService to get place predictions programmatically. This example displays results as an HTML list. Requires the Places library. ```javascript // This example retrieves autocomplete predictions programmatically from the // autocomplete service, and displays them as an HTML list. // This example requires the Places library. Include the libraries=places // parameter when you first load the API. For example: //