Google Places Autocomplete Android Example

Google places autocomplete search input can be easily implemented using Google API. Google Places API allows you to query for place information on a variety of categories, such as cities, shops and more. A Place Search returns a list of places along with more detailed information about each place.

New version of places SDK for Android is available now. The old version of the API which was part of Google Play Services is deprecated. In addition to extra features, the new places-SDK for android supports all the features which were supported by old version except Place Picker feature which is deprecated.

In this post, I am going to explain about, How to display google places in autocomplete view with example.

Checkout my other post using Google APIs,

Google Places Autocomplete Android Example

How To Get Current Latitude And Longitude In Android

Single Sign-on with AppAuth Android [Step by Step]

Lets getting started to create application with places autocomplete in android.

First, In order to use Google Places API, you need to configure an API key in Google developers console of your account.

1.Go to Google developers console and log in to your Google account.

2.Create New Project.

3.Go to the credential tab and create new credential .

4.Press edit credential,  Then you can able to see your API KEY. Copy you API Key. (Optional)Then Select Android App in the Key Restriction. Then generate Keystore in your android studio and paste it into the package.

5. Finally, Go to Library, and enable the API Places API service.

Now the Google API Key setup Done.

Lets getting started to coding part of the google places autocomplete example.

Create New Project in Android Studio.

Add the Places Library dependency to your apps build.gradle file.

implementation 'com.google.android.libraries.places:places:1.1.0'

Copy the API key from the google console and add it to your strings.xml folder like this:

<string name="api_key">API KEY</string>

To add an AutocompleteSupportFragment to your app, take the following steps:

  1. Add a fragment to your activity's XML layout.
  2. Add a listener to your activity or fragment.

Add AutocompleteSupportFragment to an activity

To add AutocompleteSupportFragment to an activity, add a new fragment to an XML layout. 

<fragment
        android:id="@+id/place_autocomplete_fragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment" />

In the activity within which you want to implement the autocomplete search feature, you’d need to initialize PlacesClient like this:

String apiKey = getString(R.string.api_key);
        if (!Places.isInitialized()) {
            Places.initialize(getApplicationContext(), apiKey);
        }

        // Create a new Places client instance.
        placesClient = Places.createClient(this);

Next, initialize the AutocompleteSupportFragment and set the fields to specify which types of place data to return in the activity or fragment.

// Initialize the AutocompleteSupportFragment.
        AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
                getSupportFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
        autocompleteFragment.setTypeFilter(TypeFilter.CITIES);
        autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.PHOTO_METADATAS));

You can set type filter, to get the results of specified place type only, by calling setTypeFilter method on the request object and passing one of the TypeFilter to it, for example TypeFilter.CITIES. To know all the place type, see Place Type Filter documentation.

Also, You can set the which are the place fields should be returned back as a response using setPlaceFields like Place.Field ID and Place.Field NAME etc. To know all the place fields, see Place.Field documentation

Finally, Add the listener for the autocomplete item select on the google places list.

autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
            @Override
            public void onPlaceSelected(@NonNull Place place) {
                // TODO: Get info about the selected place.
                Toast.makeText(getApplicationContext(), place.getName(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(@NonNull Status status) {
                // TODO: Handle the error.
                Toast.makeText(getApplicationContext(), status.toString(), Toast.LENGTH_SHORT).show();
            }
        });

How to get the Places Photos in Places autocomplete 

To get place photos, first you need to get photo metadata by calling findCurrentPlace or fetchPlace API and passing Place.Field.PHOTO_METADATAS in those requests. Each place contains list of photos, so you will get list of PhotoMetadata objects for each place.

After getting PhotoMetadata objects, pick one object, create FetchPhotoRequest object and pass it to fetchPhoto() API call to get photo.

AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
                getSupportFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
        autocompleteFragment.setTypeFilter(TypeFilter.CITIES);
        autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.PHOTO_METADATAS));
        autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
            @Override
            public void onPlaceSelected(@NonNull Place place) {
                // TODO: Get info about the selected place.
                Toast.makeText(getApplicationContext(), place.getName(), Toast.LENGTH_SHORT).show();

                FetchPhotoRequest photoRequest = FetchPhotoRequest.builder(Objects.requireNonNull(place.getPhotoMetadatas()).get(0))
                        .build();
                placesClient.fetchPhoto(photoRequest).addOnSuccessListener(
                        new OnSuccessListener<FetchPhotoResponse>() {
                            @Override
                            public void onSuccess(FetchPhotoResponse response) {
                                Bitmap bitmap = response.getBitmap();
                                ((ImageView)findViewById(R.id.img)).setImageBitmap(bitmap);
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception exception) {
                                exception.printStackTrace();
                            }
                        });
            }

            @Override
            public void onError(@NonNull Status status) {
                // TODO: Handle the error.
                Toast.makeText(getApplicationContext(), status.toString(), Toast.LENGTH_SHORT).show();
            }
        });

That's on google places autocomplete.

You can download the example in Github.

Conclusion

Thanks for reading. Please try to create example yourself and let me know your feedback in comments.

2 Replies to “Google Places Autocomplete Android Example”

Leave a Reply

Your email address will not be published. Required fields are marked *