Logo
blank Skip to main content

How to Implement the Places API in Your Web Application

API

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.

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:

Reasons to use Place Autocomplete

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 serviceRole of the Places API 
Door-to-door and last-mile delivery
  • Retrieving valid delivery addresses
  • Restricting search area to service delivery area
Hospitality services
  • Searching for accommodation in a particular area
  • Providing a user with information on the distance to a specific location
Navigation
  • Retrieving information about a userโ€™s current location and desired destination
Postal services
  • Providing a user with addresses and information on post offices
  • Limiting address search to specific types of locations
Weather forecasts
  • Retrieving a location from a user to display the forecast
Local business catalogs
  • Searching for a business within a restricted area
  • Providing a user with information about businesses nearby

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:

  1. 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.
  2. 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:

HTML
<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:

HTML
<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.

Learn more
API Management Strategies and Tools

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

JavaScript
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):

HTML
<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:

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.

Learn more
cross-platform-apps-ionic-angular.jpg

Click on the correct suggestion to fill the address form. Below, you can see an example of the response:

Places API responce

On the client side, the results of the search will look like this:

Client side of the Places API responce

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.

Have a question?

Ask our expert!

Maryna-Prudka
Maryna Prudka

R&D Delivery Manager

Tell us about
your project

...And our team will:

  • Process your request within 1-2 business days.
  • Get back to you with an offer based on your project's scope and requirements.
  • Set a call to discuss your future project in detail and finalize the offer.
  • Sign a contract with you to start working on your project.

Do not have any specific task for us in mind but our skills seem interesting? Get a quick Apriorit intro to better understand our team capabilities.