Today, making a user input an entire address is considered a sign of a poor user experience. Thatโs why location-based applications need autocomplete services. Place Autocomplete is one such service for web applications that use Google Maps.
In this article, we discuss key features of the Places API Autocomplete service. We also explain how to implement address autocomplete using this Google API.
This article will be helpful for anyone interested in building location-aware web applications.
Contents:
What is Place Autocomplete and why should you use it?
Place Autocomplete is part of the Places API. It implements type-ahead search for Google Maps in web applications. The Places API processes user queries as theyโre typed and returns on-the-fly predictions. This allows a user to quickly choose an address from a list of predictions instead of typing it in full.
Autocomplete matches user queries with:
- Addresses
- Full words
- Substrings
- Place names
- Plus Codes
Implementing an address autocomplete feature using this Google API is beneficial for both businesses and end users for several reasons:
The ability to search for a particular address or location is an integral part of any location-aware application. Here are several examples of businesses that can benefit from adding the Places API to their web solutions:
Type of service | Role of the Places API |
Door-to-door and last-mile delivery |
|
Hospitality services |
|
Navigation |
|
Postal services |
|
Weather forecasts |
|
Local business catalogs |
|
Next, letโs take a look at key implementation options for the Places API.
Integrate popular third-party services into your application
Apriorit cloud development specialists will help you find the safest, most efficient, and cost-effective way to build an API integration.
Places API implementation options
The Places API is available for desktop, Android, and iOS, so you can use it not only for web applications but also for mobile and cross-platform solutions. No matter your choice of platform, there are two ways to implement the Places API on the client side:
- Using the Autocomplete widget, which automatically provides address predictions as a user types a request. When the user chooses a predicted address, the widget fetches additional information about it (coordinates, exact address, place name, etc.). This implementation of the Places API is the most convenient for users, since they donโt have to type a complete search request. Also, the dropdown list with predictions is implemented and styled by Google, which means less work for a developer.
- Using AutocompleteService, a JavaScript object thatโs used to retrieve predictions programmatically. After the user finishes inputting data, AutocompleteService returns an array of predictions with all of the referenced information about those predictions. The key advantage of using AutocompleteService is that it doesnโt add any UI elements of its own to the mapโs address search box. Instead, it uses elements of your web app. This way, you donโt need to take into account Google UI elements when designing mockups and can easily maintain UI consistency.
To interact with the server side of your application fast and easily, you can use one of the client libraries for Google Maps web services. Google provides libraries for Java, Python, Go, Node.js, and Objective-C, each with Places API functionality.
If you need an application that searches for a particular type of location, use these Places API parameters to configure search results:
- Component restrictions โ Restricts search results to specific areas (country, city, place ID, etc.).
- Bounds โ Defines the preferred area for results but doesnโt limit them to this area.
- Types โ Sets prediction types (geocode, address, name of the establishment, etc.) that should be returned to the user.
- Fields โ Specifies data fields that should be included in the search results.
This knowledge of Places API Autocomplete is enough to implement it in an existing application. Letโs move to the practical part and build a simple web app with an address finder using this Google API.
Adding Places Autocomplete to a web app
Weโll start with enabling the Places API in your Google account and getting an API key. Both processes are covered in the official Google documentation, so weโll omit them from this article.
Once you get your API key, you can start building a simple application with Place Autocomplete. In the following example, weโll show how to implement the Autocomplete widget.
Weโll create an application that allows a user to input part of an address, select a prediction, and get information about the address on the screen. The application will also show the requested address on the map.
The HTML for this application will be pretty simple:
<style>
.map-container {
position: relative;
overflow: hidden;
display: block;
width: 300px;
height: 300px;
padding: 20px;
}
</style>
<input id="searchInput" type="text" placeholder="Enter a location" />
<h4>Address Components</h4>
<ul class="geo-data">
<li>Street number: <span id="street_number">-</span></li>
<li>Street: <span id="street">-</span></li>
<li>City: <span id="city">-</span></li>
<li>Country: <span id="country">-</span></li>
<li>Latitude: <span id="lat">-</span></li>
<li>Longitude: <span id="lng">-</span></li>
<li>Place_ID: <span id="place_id">-</span></li>
</ul>
<div id="map" class="map-container hidden"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js">
Now we need to include Place Autocomplete libraries (which are an integral part of the API) into the app. Hereโs how we do it:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places"></script>
Youโll need to replace the key=YOUR_KEY
parameter with the API key you received previously. Note that the library=places
parameter we specified above limits our appโs access to Places API libraries only.
Read also
API Management Essentials: Strategies and Tools
Explore the key strategies for building, integrating, and maintaining APIs securely. Whether youโre looking to monetize APIs or build an internal ecosystem, this guide provides the tools and insights to elevate your API management efforts.
When we use the Autocomplete widget, we should create a listener for the place_changed
event. When a user clicks on a prediction, the widget triggers this event. We need to handle this event and request details on the selected location by adding the following method to the code
const place = autocomplete.getPlace();
To initialize an address search within a map using the Autocomplete API, we need to add the code below to the HTML markup of the web app (or create a new JavaScript file and connect it to the markup):
<script type="text/javascript">
function initAutocomplete() {
let components = {
'#street_number': 'street_number',
'#street': 'route',
'#city': 'locality',
'#state': 'administrative_area_level_1',
'#zip': 'postal_code',
'#country': 'country'
};
let input = $("#searchInput")[0];
let map = new google.maps.Map($("#map")[0]);
let marker = new google.maps.Marker({ map: map }); // This marker is used as a pointer on the map
let infowindow = new google.maps.InfoWindow(); // This window will be attached to a marker and displayed when a user clicks on it
marker.addListener("click", function () {
infowindow.open(map, marker);
});
let autocomplete = new google.maps.places.Autocomplete(input, {
types: ['address'], // The map will show exact addresses only
fields: ['place_id', 'geometry', 'address_component', 'formatted_address'], // Results will include limited address components like place ID, coordinates, and formatted address
componentRestrictions: { country: 'us' } // Limit addresses to USA only
});
autocomplete.bindTo('bounds', map);
autocomplete.addListener('place_changed', () => {
let place = autocomplete.getPlace(); // Retrieve details about the place
if (!place.geometry) {
alert("No predictions were found")
return;
}
infowindow.close();
marker.setVisible(false);
infowindow.setContent(place.formatted_address);
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(25);
}
$.each(components, (listComponent) => {
let addressComponent = components[listComponent];
let matchedComponent = place.address_components.find((value, index) => {
return value.types.some((v) => v === addressComponent );
});
let displayVal = matchedComponent ? matchedComponent.long_name : '-';
$(listComponent).text(displayVal);
});
$('#place_id').text(place.place_id);
$('#lat').text(place.geometry.location.lat());
$('#lng').text(place.geometry.location.lng());
marker.addListener("click", function () {
infowindow.open(map, marker);
});
marker.setPosition(place.geometry.location);
marker.setVisible(true);
$("#map").removeClass("hidden");
$("#searchInput").val('');
})
};
$(() => {
initAutocomplete();
});
</script>
With this step completed, our API should start working and processing user queries. When a user requests an address, the application will locate it on the map and show additional information on everything located at this address.
As an example, letโs search for the Museum of Modern Art in San Francisco. Just start typing its address (151 Third Street, San Francisco) into the address field. Youโll see suggestions provided by the Places API:
Read also
Building a Cross-Platform Mobile Web Application with Ionic and Angular
Our experts share how Ionic works and why itโs a game-changer for developers working with Angular and React. Learn how to leverage this framework to build adaptable apps for both Android and iOS while saving time and costs.
Click on the correct suggestion to fill the address form. Below, you can see an example of the response:
On the client side, the results of the search will look like this:
If the user sees search predictions and the correct search result, that means Place Autocomplete is working properly.
Conclusion
Autocomplete features provide users with on-the-fly predictions and simplify the search process. Thatโs why a carefully configured and implemented autocomplete feature for address search is a must for any location-aware application. Following the advice provided above, you can successfully implement search autocomplete with the Google Places API.
At Apriorit, we make sure that each application made by our web development experts is easy to use, well-tuned, and tailored to the customerโs needs. If youโre working on a web project and are in need of a professional team, donโt hesitate to contact us!
Use top-quality integrations for your app
Benefit from Aprioritโs expertise in API development to get efficient, secure, and scalable integrations integrations.