Dalam contoh ini, kami menambahkan kotak penelusuran Place Autocomplete untuk alamat agar pengguna dapat memasukkan alamat dan mengevaluasi fasilitas terdekat. Untuk pengguna perumahan, kami menetapkan placeTypePreferences ke jenis yang umum dikaitkan dengan kehidupan sehari-hari seseorang. Alamat dalam contoh ini dibatasi untuk Amerika Serikat.
/*
* 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;
}
input {
height: 30px;
margin: 12px 0px;
padding: 10px;
width: 300px;
}
<html>
<head>
<title>Local Context Home</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
</head>
<body>
<input id="input" placeholder="Enter a US address" />
<div id="map"></div>
<!--
The `defer` attribute causes the callback to execute after the full HTML
document has been parsed. For non-blocking uses, avoiding race conditions,
and consistent behavior across browsers, consider loading using Promises.
See https://developers.google.com/maps/documentation/javascript/load-maps-js-api
for more information.
-->
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&libraries=localContext,places&v=beta"
defer
></script>
</body>
</html>
Saat menentukan jenis tempat untuk ditampilkan oleh Library Konteks Lokal, Anda dapat menetapkan bobot relatif untuk setiap properti menggunakan atribut weight (jenis dengan bobot relatif yang lebih tinggi akan lebih sering muncul). Contoh ini menetapkan frekuensi taman dan sekolah yang lebih tinggi jika
tersedia.
Untuk menggunakan layanan Place Autocomplete, Anda harus memuat Places Library, Maps JavaScript API terlebih dahulu.
Dokumentasi Autocomplete menjelaskan semua parameter yang tersedia untuk
menyesuaikan perilaku Place Autocomplete
seperti memfilter prediksi berdasarkan geografi atau jenis tempat.
Ikuti dokumentasi Autocomplete
dan contoh kode untuk
mempelajari cara menambahkan kotak penelusuran Place Autocomplete ke situs atau peta Anda. Dalam
contoh ini, baris yang relevan adalah:
TypeScript
// Build and add the Autocomplete search bar
const input = document.getElementById("input")! as HTMLInputElement;
const options = {
types: ["address"],
componentRestrictions: {
country: "us",
},
fields: ["address_components", "geometry", "name"],
};
const autocomplete = new google.maps.places.Autocomplete(input, options);