How To Get Google Places In 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.

The new version of places SDK for Android is availablenow. 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 the old version except the Place Picker feature which is deprecated.

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

Check out 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]

Let’s get started to create an application with places autocomplete in android.

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

  1. Go to the Google developers console and log in to your Google account.
  2. Create New Project.
create new project
  1. Go to the credential tab and create a new credential.
Create Credentials in Google API
  1. Pressedit credential, Then you can able to see your API KEY.Copy your API Key. (Optional)Then SelectAndroid Appin the Key Restriction. Then generate Keystore in your android studio and paste it into the package.
Add SHA1 key for the API KEY
  1. Finally,Go to Library, andenable the API Places API service.
Enable Google Places API

Now the Google API Key setup is Done.


Let’s get started with the coding part of the google places autocomplete example.

Create New Project in Android Studio.

Add the Places Library dependency to your app’sbuild.gradlefile

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 initializePlacesClientlike 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 a type filter, to get the results of a specified place type only, by calling the setTypeFilter method on the request object and passing one of the TypeFilter to it, for example, TypeFilter.CITIES. To know all the place types, seePlace Type Filterdocumentation.

Also, You can set which are the place fields that should be returned back as a response usingsetPlaceFieldslike Place. Field ID and Place.Field NAME etc. To know all the place fields, seePlace.Fielddocumentation

Finally, Add the listener for the autocomplete item selected 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_METADATASin those requests. Each place contains a list of photos, so you will get a list of PhotoMetadata objects for each place.

After getting PhotoMetadata objects, pick one object, create a FetchPhotoRequest object and pass it to fetchPhoto() The API call to get a 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 on Github.

Conclusion

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


Comments

One response to “How To Get Google Places In Android Example ?”

Leave a Reply

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


Latest Posts