In this example, we add a Place Autocomplete
search bar for addresses to allow the user to enter in an address and evaluate
the nearby amenities. For residential users, we set the placeTypePreferences
to types commonly associated with home life. Addresses in this sample are
restricted to the United States.
/*
* 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
with https://www.npmjs.com/package/@googlemaps/js-api-loader.
-->
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&libraries=localContext,places&v=beta"
defer
></script>
</body>
</html>
When specifying place types for the Local Context Library
to return, you can assign a relative weight to each property by using the
weight attribute (types with a higher relative weighting will appear more
often). This example specifies a higher frequency of parks and schools if
available.
To use the Place Autocomplete service, you must first load Places Library, Maps JavaScript API.
The Autocomplete documentation details all of the parameters available to
customize the Place Autocomplete behavior
such as filtering predictions by geography or place type.
Follow the Autocomplete documentation
and code samples to
learn how to add a Place Autocomplete search bar to your website or map. In
this example, the relevant lines are:
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);