Skip to content

Commit

Permalink
feat: Adds new example maps to demonstrate the place autocomplete dat…
Browse files Browse the repository at this point in the history
…a API (#1745)

* feat: Adds demo for marker accessibility using gmp-map.

Change-Id: I4823fb42df80c8e74f8abbb5e7876678ce3deb9e

* feat: Adds example apps for Place Autocomplete Data API GA.

Change-Id: Id9218c089a9dfc92bc6a2c802aa6a15b37ef5333
  • Loading branch information
willum070 authored May 28, 2024
1 parent d008d15 commit eb5b637
Show file tree
Hide file tree
Showing 12 changed files with 364 additions and 0 deletions.
19 changes: 19 additions & 0 deletions samples/place-autocomplete-data-session/index.njk
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<!--
@license
Copyright 2019 Google LLC. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
-->
{% extends '../../src/_includes/layout.njk'%}
{% block html %}
<!-- // [START maps_place_autocomplete_data_session_html] -->
<input id="input" type="text" placeholder="Search for a place..."/>
<div id="title"></div>
<ul id="results"></ul>
<img
class="powered-by-google"
src="https://storage.googleapis.com/geo-devrel-public-buckets/powered_by_google_on_white.png"
alt="Powered by Google"
/>
<!-- // [END maps_place_autocomplete_data_session_html] -->
{% endblock %}
97 changes: 97 additions & 0 deletions samples/place-autocomplete-data-session/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/**
* @license
* Copyright 2024 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

// [START maps_place_autocomplete_data_session]
let title;
let results;
let input;
let token;

// Add an initial request body.
let request = {
input: "",
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",
};

async function init() {
token = new google.maps.places.AutocompleteSessionToken();

title = document.getElementById('title');
results = document.getElementById('results');
input = document.querySelector("input");
input.addEventListener("input", makeAcRequest);
request = refreshToken(request) as any;
}

async function makeAcRequest(input) {
// Reset elements and exit if an empty string is received.
if (input.target.value == '') {
title.innerText = '';
results.replaceChildren();
return;
}

// Add the latest char sequence to the request.
request.input = input.target.value;

// Fetch autocomplete suggestions and show them in a list.
// @ts-ignore
const { suggestions } = await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request);

title.innerText = 'Query predictions for "' + request.input + '"';

// Clear the list first.
results.replaceChildren();

for (const suggestion of suggestions) {
const placePrediction = suggestion.placePrediction;

// Create a link for the place, add an event handler to fetch the place.
const a = document.createElement('a');
a.addEventListener('click', () => {
onPlaceSelected(placePrediction.toPlace());
});
a.innerText = placePrediction.text.toString();

// Create a new list element.
const li = document.createElement('li');
li.appendChild(a);
results.appendChild(li);
}
}

// Event handler for clicking on a suggested place.
async function onPlaceSelected(place) {
await place.fetchFields({
fields: ['displayName', 'formattedAddress'],
});
let placeText = document.createTextNode(place.displayName + ': ' + place.formattedAddress);
results.replaceChildren(placeText);
title.innerText = 'Selected Place:';
input.value = '';
refreshToken(request);
}

// Helper function to refresh the session token.
async function refreshToken(request) {
// Create a new session token and add it to the request.
token = new google.maps.places.AutocompleteSessionToken();
request.sessionToken = token;
return request;
}

declare global {
interface Window {
init: () => void;
}
}
window.init = init;
// [END maps_place_autocomplete_data_session]
export { };
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"title": "Place Autocomplete Data API Session",
"callback": "init",
"libraries": ["places"],
"version": "weekly",
"tag": "maps_place_autocomplete_data_session",
"name": "place-autocomplete-data-session",
"pagination": {
"data": "mode",
"size": 1,
"alias": "mode"
},
"permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}"
}
22 changes: 22 additions & 0 deletions samples/place-autocomplete-data-session/style.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

@use 'sass:meta'; // To enable @use via meta.load-css and keep comments in order

/* [START maps_place_autocomplete_data_session] */
@include meta.load-css("../../shared/scss/default.scss");

a {
cursor: pointer;
text-decoration: underline;
color: blue;
}

input {
width: 300px;
}

/* [END maps_place_autocomplete_data_session] */
18 changes: 18 additions & 0 deletions samples/place-autocomplete-data-simple/index.njk
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<!--
@license
Copyright 2019 Google LLC. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
-->
{% extends '../../src/_includes/layout.njk'%} {% block html %}
<!-- // [START maps_place_autocomplete_data_simple_html] -->
<div id="title"></div>
<ul id="results"></ul>
<p>First predicted place: <span id="prediction"></span></p>
<img
class="powered-by-google"
src="https://storage.googleapis.com/geo-devrel-public-buckets/powered_by_google_on_white.png"
alt="Powered by Google"
/>
<!-- // [END maps_place_autocomplete_data_simple_html] -->
{% endblock %}
80 changes: 80 additions & 0 deletions samples/place-autocomplete-data-simple/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* @license
* Copyright 2024 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

// [START maps_place_autocomplete_data_simple]
/**
* Demonstrates making a single request for Place predictions, then requests Place Details for the first result.
*/
async function init() {
// @ts-ignore
const { Place, AutocompleteSessionToken, AutocompleteSuggestion } = await google.maps.importLibrary("places") as google.maps.PlacesLibrary;

// [START maps_place_autocomplete_data_simple_request]
// Add an initial request body.
// [START maps_place_autocomplete_data_simple_request_body]
let 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",
};
// [END maps_place_autocomplete_data_simple_request_body]

// [START maps_place_autocomplete_data_simple_token]
// Create a session token.
const token = new AutocompleteSessionToken();
// Add the token to the request.
// @ts-ignore
request.sessionToken = token;
// [END maps_place_autocomplete_data_simple_token]

// [START maps_place_autocomplete_data_simple_get_suggestions]
// Fetch autocomplete suggestions.
const { suggestions } = await AutocompleteSuggestion.fetchAutocompleteSuggestions(request);
// [END maps_place_autocomplete_data_simple_request]

const title = document.getElementById('title') as HTMLElement;
title.appendChild(document.createTextNode('Query predictions for "' + request.input + '":'));

for (let suggestion of suggestions) {
const placePrediction = suggestion.placePrediction;

// Log everything for the place prediction. TODO: Delete this section once we have seen the results.
console.log('placeId: ' + placePrediction.placeId); // You've now got the place ID!
console.log(' text: ' + placePrediction.text.toString());
console.log(' mainText: ' + placePrediction.mainText.toString());
console.log(
' secondaryText: ' + placePrediction.secondaryText.toString());
console.log(' types: ' + placePrediction.types);
console.log(' distanceMeters: ' + placePrediction.distanceMeters);

// Create a new list element.
const listItem = document.createElement('li');
const resultsElement = document.getElementById("results") as HTMLElement;
listItem.appendChild(document.createTextNode(placePrediction.text.toString()));
resultsElement.appendChild(listItem);
}
// [END maps_place_autocomplete_data_simple_get_suggestions]

// [START maps_place_autocomplete_data_simple_prediction]
let place = suggestions[0].placePrediction.toPlace(); // Get first predicted place.
// [START maps_place_autocomplete_data_simple_fetch]
await place.fetchFields({
fields: ['displayName', 'formattedAddress'],
});
// [END maps_place_autocomplete_data_simple_fetch]

const placeInfo = document.getElementById("prediction") as HTMLElement;
placeInfo.textContent = 'First predicted place: ' + place.displayName + ': ' + place.formattedAddress;
// [END maps_place_autocomplete_data_simple_prediction]

}

init();
// [END maps_place_autocomplete_data_simple]
export { };
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"title": "Place Autocomplete Data API Predictions",
"version": "3.57.1",
"dynamic_import": "true",
"tag": "maps_place_autocomplete_data_simple",
"name": "place-autocomplete-data-simple",
"pagination": {
"data": "mode",
"size": 1,
"alias": "mode"
},
"permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}"
}
13 changes: 13 additions & 0 deletions samples/place-autocomplete-data-simple/style.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

@use 'sass:meta'; // To enable @use via meta.load-css and keep comments in order

/* [START maps_place_autocomplete_data_simple] */
@include meta.load-css("../../shared/scss/default.scss");

/* [END maps_place_autocomplete_data_simple] */

17 changes: 17 additions & 0 deletions web-components-accessibility/index.njk
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<!--
@license
Copyright 2019 Google LLC. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
-->
{% extends '../../src/_includes/layout.njk'%} {% block html %}
<gmp-map center="34.84555, -111.8035" zoom="12" map-id="DEMO_MAP_ID">
<!-- START maps_web_components_events_clickable -->
<gmp-advanced-marker position="34.8791806, -111.8265049" title="Boynton Pass" gmp-clickable></gmp-advanced-marker>
<!-- END maps_web_components_events_clickable -->
<gmp-advanced-marker position="34.8559195, -111.7988186" title="Airport Mesa" gmp-clickable></gmp-advanced-marker>
<gmp-advanced-marker position="34.832149, -111.7695277" title="Chapel of the Holy Cross" gmp-clickable></gmp-advanced-marker>
<gmp-advanced-marker position="34.823736, -111.8001857" title="Red Rock Crossing" gmp-clickable></gmp-advanced-marker>
<gmp-advanced-marker position="34.800326, -111.7665047" title="Bell Rock" gmp-clickable></gmp-advanced-marker>
</gmp-map>
{% endblock %}
41 changes: 41 additions & 0 deletions web-components-accessibility/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

// [START maps_web_components_accessibility]
async function initMap(): Promise<void> {
const { InfoWindow } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
const { PinElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;
console.log('Maps JavaScript API loaded.');

// [START maps_web_components_accessibility_query]
// Return an array of markers.
const advancedMarkers = [...document.querySelectorAll('gmp-advanced-marker')];
// [END maps_web_components_accessibility_query]

// [START maps_web_components_accessibility_iterate]
// Create a shared info window.
let infoWindow = new InfoWindow();

for (let i = 0; i < advancedMarkers.length; i++) {
const marker = advancedMarkers[i] as google.maps.marker.AdvancedMarkerElement;
const pin = new PinElement({
glyph: `${i + 1}`,
scale: 1.5,
});

marker.appendChild(pin.element);
marker.addEventListener('gmp-click', () => {
infoWindow.close();
infoWindow.setContent(marker.title);
infoWindow.open(marker.map, marker);
});
}
// [END maps_web_components_accessibility_iterate]
}

initMap();
// [END maps_web_components_accessibility]
export { };
17 changes: 17 additions & 0 deletions web-components-accessibility/style.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

@use 'sass:meta'; // To enable @use via meta.load-css and keep comments in order

/* [START maps_web_components_accessibility] */
@include meta.load-css("../../shared/scss/default.scss");

gmp-map {
height: 400px;
}

/* [END maps_web_components_accessibility] */

13 changes: 13 additions & 0 deletions web-components-accessibility/web-components-accessibility.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"title": "Advanced Marker Accessibility with web components",
"dynamic_import": "true",
"version": "beta",
"tag": "web_components_accessibility",
"name": "web-components-accessibility",
"pagination": {
"data": "mode",
"size": 1,
"alias": "mode"
},
"permalink": "samples/{{ page.fileSlug }}/{{mode}}/{% if mode == 'jsfiddle' %}demo{% else %}index{% endif %}.{{ page.outputFileExtension }}"
}

0 comments on commit eb5b637

Please sign in to comment.