Goal: Replace your implementation of Places API or Place Class with the Places UI Kit.
Who this guide is for
Developers who are:
- Making HTTP requests to Places API (New or Legacy) endpoints.
- Using the Place Class within the Maps JavaScript API.
- Handling the API response to render place information in their web application's UI.
Prerequisites
Enable the Places UI Kit on your Google Cloud Project. You can continue to use your existing API key, or generate a new one for Places UI Kit. See Use API Keys for more information, including restricting a key.
Update Maps JavaScript API Loading
The Places UI Kit requires the Dynamic Library Import method of loading the Maps JavaScript API. If you are using the direct script loading tag, this must be updated.
Once you have updated the loading script for the Maps JavaScript API, import the required libraries to use Places UI Kit.
Implement the Place Details Element
Current Implementation
- You perform a Place Details call using a HTTP request, or use the JavaScript API Place Class.
- You parse the API response, and display the place details using HTML and CSS.
Migration to Place Details Element
Modify HTML Structure
Identify the HTML container where place details are rendered. Replace your custom HTML elements (divs, spans for name, address, photos, etc.) with the Place Details Element html.
There are two elements to pick from:
- Place Details Compact Element
- Place Details Element
For more information about which one to use, see Place Details Element.
Your existing HTML may look like this.
<div id="my-place-details-container">
<h2 id="place-name"></h2>
<p id="place-address"></p>
<img id="place-photo" src="" alt="Place photo">
<!-- ... more custom elements -->
</div>
Example new HTML, explicitly stating which content to display:
<gmp-place-details-compact orientation="horizontal" truncation-preferred style="display: none;">
<gmp-place-details-place-request></gmp-place-details-place-request>
<gmp-place-content-config>
<gmp-place-media lightbox-preferred></gmp-place-media>
<gmp-place-address></gmp-place-address>
<gmp-place-rating></gmp-place-rating>
<gmp-place-type></gmp-place-type>
<gmp-place-price></gmp-place-price>
<gmp-place-accessible-entrance-icon></gmp-place-accessible-entrance-icon>
<gmp-place-open-now-status></gmp-place-open-now-status>
</gmp-place-content-config>
</gmp-place-details-compact>
Adapt JavaScript Logic
Existing logic
Your existing logic likely involves:
- Retrieving a Place ID.
- Using
PlacesService().getDetails()
or making a web service call. - Specifying a fields array (for JS API) or FieldMask (for web service) to request specific data.
- In the callback resolution, manually selecting your HTML elements and populating them with the received data.
The following is an example of how you may have Place Details implemented:
async function getPlaceDetails(placeId) {
const { Place } = await google.maps.importLibrary('places');
// Use place ID to create a new Place instance.
const place = new Place({
id: placeId
});
await place.fetchFields({
fields: ['displayName', 'formattedAddress', 'location'],
});
// Log the result
console.log(place.displayName);
console.log(place.formattedAddress);
}
New logic
Your new logic will involve:
- Retrieve your Place ID or Place Object.
- Get a reference to the
<gmp-place-details-place-request>
element. - Pass the Place ID or the Place Object to the place property on the
<gmp-place-details-place-request>
element.
The following is an example of how you can implement the Place Details UI kit in
your JavaScript logic. Get a reference to the Place Details Element. If this
exists, get a reference to the Place Details Place Request element, and set the
place property using a Place ID. In the example HTML code above, the Place
Details Element style is set to display: none
. This is updated to display:
block
.
function displayPlaceDetailsWithUIKit(placeId) {
const placeDetailsElement = document.querySelector('gmp-place-details-compact');
if (placeDetailsElement) {
const placeDetailsRequest = document.querySelector('gmp-place-details-place-request');
// Configure the element with the Place ID
placeDetailsRequest.place = placeId
placeDetailsElement.style.display = 'block';
console.log("PlaceDetailsElement configured for place:", placeId);
} else {
console.error("PlaceDetailsElement not found in the DOM.");
}
}
// Example usage:
const placeId = 'ChIJC8HakaIRkFQRiOgkgdHmqkk';
displayPlaceDetailsWithUIKit(placeId);
Implement Place Search Element
Current Implementation
- You perform a Text Search or Nearby Search using a HTTP request, or use the JavaScript API Place Class.
- You specify query parameters, location restrictions or biases, types, and requested fields using FieldMask.
- You parse the API response, iterate through the array of places, and manually create HTML list items.
Migration to Place Search Element
Modify HTML Structure
Identify the HTML container where you render your place list. Replace your custom HTML elements (divs, spans for name, address, etc.) with the Place Search Element html element.
Your existing HTML may look something like this:
<div id="search-results-area">
<h3>Nearby Places:</h3>
<ul id="manual-places-list">
<!-- JavaScript would dynamically insert list items here -->
<!-- Example of what JS might generate:
<li class="place-entry" data-place-id="SOME_PLACE_ID_1">
<img class="place-icon" src="icon_url_1.png" alt="Icon">
<span class="place-name">Place Name One</span> -
<span class="place-vicinity">123 Main St</span>
</li>
<li class="place-entry" data-place-id="SOME_PLACE_ID_2">
<img class="place-icon" src="icon_url_2.png" alt="Icon">
<span class="place-name">Place Name Two</span> -
<span class="place-vicinity">456 Oak Ave</span>
</li>
-->
<li class="loading-message">Loading places...</li>
</ul>
</div>
The Place Search Element uses the HTML tag <gmp-place-list>
. Your new HTML
would look like the following. Add the selectable
attribute if you want users
to be able to click list items.
<gmp-place-list id="myPlaceListComponent" selectable></gmp-place-list>
Adapt JavaScript Logic
Get a reference to the <gmp-place-list>
DOM element.
For Text Search functionality: Use
configureFromSearchByTextRequest(requestOptions)
.
const placeListComp = document.getElementById('myPlaceListComponent');
try {
await placeListComp.configureFromSearchByTextRequest({
textQuery: 'restaurants in Sydney',
// locationRestriction: map.getBounds(), // Optional
// includedType: 'restaurant' // Optional
});
} catch (error) {
console.error('UI Kit Place List (Text Search) Error:', error);
}
For Nearby Search functionality: Use
configureFromSearchNearbyRequest(requestOptions)
:
const placeListComp = document.getElementById('myPlaceListComponent');
if (placeListComp) {
try {
await placeListComp.configureFromSearchNearbyRequest({
locationRestriction: { circle: { center: { latitude: ..., longitude: ... }, radius: 5000 } },
includedPrimaryTypes: ['cafe', 'bakery'] // Example
});
} catch (error) {
console.error('UI Kit Place List (Nearby Search) Error:', error);
}
}
Once the text or nearby search request is complete, the Place Search Element will automatically update its UI with the search results.
Handle Customization
Place Details Element customization
Orientation
The Place Details Element can be rendered in both Horizontal and Vertical
orientation. Use the orientation
attribute on gmp-place-details-compact
to
choose between vertical and horizontal. For example:
<gmp-place-details-compact orientation="vertical">
Choose fields to render
Use content elements to specify the content to be rendered within the Place
Details Element. For example, excluding the content element <gmp-place-type>
would stop the Place Details Element rendering the Place Type of the selected
place. For a full list of content elements, see the
PlaceContentConfigElement
reference documentation.
Adding or removing fields from the Place Details Element does not change the cost of rendering the element on the page.
Set CSS Styles
Custom CSS properties are available to configure the element's colors and fonts. For example, to set the element background to green, set the following CSS property:
gmp-place-details-compact {
--gmp-mat-color-surface: green;
}
See the reference documentation for
PlaceDetailsCompactElement
for more details.
Handle events & data
The Places UI Kit Elements expose certain events, such as gmp-placeselect
event on the Place Search Element, allowing an action when the user clicks a
place result. For more information, see the Place Search
Element and Place
Details Element
documentation.
When interacting programmatically with the Place Search Element and the Place Details Element, there is data that can be requested, being:
- Place ID
- Location (Latitude & Longitude)
- Viewport
An example of how to do this is shown in the Place List Element documentation.
All other data within the element is read-only.
Testing and Refinement
Once you have integrated the Place Details Element or the Place Search Element, testing is important for a smooth transition and a positive user experience. Your testing should cover several key areas, addressing both components if you've implemented them.
For the Place Details Element, begin by verifying that place details are displayed correctly for a diverse range of places. This involves testing with various Place IDs representing different types of establishments (businesses with rich data, points of interest, basic addresses), and places in different regions or languages (if relevant). Pay close attention to the formatting, layout, and presence of expected UI elements within the PlaceDetailsElement.
If you've implemented the Place Search Element, verify its rendering and
behavior under different search scenarios. Test both
configureFromSearchNearbyRequest
and configureFromSearchByTextRequest
methods if applicable. Use various search inputs: broad queries, specific
addresses, queries with different location biases or restrictions, and searches
filtered by different place types. Confirm that the list populates with relevant
results and that the number of results seems appropriate for the query. Check
the visual presentation of each list item.
Rigorous testing of error handling scenarios is essential for both components.
Simulate passing invalid or non-existent Place IDs to
PlaceDetailsElement.configureFromPlace()
. For Place Search Element, test with
invalid search parameters, network issues during the request, or scenarios that
might return zero results.
Your JavaScript code must catch errors thrown by the Places UI Kit. Implement user-friendly error handling, such as displaying informative messages, hiding the components gracefully, or logging errors, to prevent a broken or confusing UI.