FIELD NOTES ON BUILDING SYSTEMS

A personal technical publication

Android Google Places Autocomplete feature tutorial with example

I am back with a blog on android after quite sometime. This post is about Android Google Places Autocomplete feature tutorial with example. In today’s time in almost all the location based mobile application, we…

google-place-autocomplete-select-api

 

The approach taken in this tutorial got deprecated by google as of 29th January’19. I have published an updated version of this tutorial. Please click here to check the updated version.

 

I am back with a blog on android after quite sometime. This post is about Android Google Places Autocomplete feature tutorial with example. In today’s time in almost all the location based mobile application, we get feature to search location manually ourselves for various needs. The Google Places SDK for Android provides places autocomplete service. It returns predictions of places in response to the search queries entered by the user in the search box. User can keep typing what they want to search, and the autocomplete service keeps returning list of suggestions based on the user input.

There are two ways of adding Google places autocomplete in android application –

  1. Using a place autocomplete widget – This requires lesser coding as Google itself made it easy for the developers by implementing much of the functionality. This works perfectly in usual scenarios. The autocomplete widget contains a place search dialog UI and it has built-in autocomplete functionality. There are two ways we can add this widget in our app –

In this tutorial, we will cover the first one i.e. by embedding PlaceAutocompleteFragment.

  1. Programmatic implementation of place autocomplete feature – However, many a time when you want a great extent of customization in UI and user experience, the place autocomplete widget may pose some limitations. In such cases, we can implement the entire feature  by ourselves.

In this blog, we will concentrate on the option 1.

App Demo

google-places-auto-complete-android-app-example
google-places-auto-complete-android-app-example

Tech Stack

Android Studio 3.0.1
JAVA for Android programming
Google Play Services 11.8.0

Create API Key

In order to use Google Places SDK, we need to register our app project in Google API Console. We also need to obtain a Google API key. We’ll then add this API key in our android app.

  • Login to https://console.cloud.google.com/apis/dashboard with your google credential.
  • Click on the Select a project drop down list from the menu bar. A popup will open; Click on NEW PROJECT
    google-place-autocomplete-select-project
    google-place-autocomplete-select-project
  • Give a project name of your choice. In this demonstration of google places Autocomplete feature, I have given the project name as ItcGoogleFeaturesDemo
  • As you type the project name, google will auto generate a Project ID. You may change it to your choice of id if you so want. I have not changed in my case.
  • Click on the Create button. This may take a few moments to create the project
  • Thereafter, select the newly created project and click on ENABLE APIS AND SERVICES
    google-place-autocomplete-enable-api-service
    google-place-autocomplete-enable-api-service
  • A new page will open up; search for Places API (refer to the below screenshot). Click on the Places SDK for Android. A new page will open up; click on the ENABLE button.
    google-place-autocomplete-select-api
    google-place-autocomplete-select-api
  • Once clicked a new page will open up. Select the Credentials tab. Thereafter, click on Create credentials drop-down and select API key.
    google-place-autocomplete-create-credentials
    google-place-autocomplete-create-credentials
  • In a few moment, a new API key will be generated. Copy and keep it safe. We’ll use this key in our application. If you would like to stop the misuse of they key, you must click on the RESTRICT KEY button and follow the steps. In my scenario, it’s just a demonstration and POC. Hence, I’ll skip this process. However, when you are developing to release a product to play store; ensure to restrict your key to stop misuse of your API key.
    google-place-autocomplete-api-key
    google-place-autocomplete-api-key

Create an empty project

  • Launch Android Studio and click: File –> New –> New Project…
  • A “Create New Project” dialog box will open; we’ll provide the app name and company domain. I have entered following details, you can provide the name/domain as per your choice and preference.
    • Application Name:- ItcGooglePlaceAutoComplete
    • Company Domain:- iteritory.com
  • Click on Next button. In the next window, select the minimum SDK version; you can choose as per your preference. In this case, I have chosen API 16: Android 4.1 (Jelly Bean). Click Next button.
  • In the next window, select “Empty Activity“. Click Next button.
  • In the next window,  let’s keep the Activity Name and Layout Name to default. Click Finish button.
  • I’ll change the app name a bit here, traverse and open res–> values –> strings.xml. Find the line with app_name attribute. Change the value to ““My Google Place App”.

Add dependency

We’ll add following dependency required for the google places SDK

implementation 'com.google.android.gms:play-services-places:16.0.0'

We’ll also add following dependency for a better UI and wrapping the google places autocomplete widget.

implementation 'com.android.support:cardview-v7:28.0.0'

After adding all the details, the module level build.gradle looks like below –

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.iteritory.itcgoogleplaceautocomplete"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'com.google.android.gms:play-services-places:16.0.0'
    implementation 'com.android.support:cardview-v7:28.0.0'
}

 

Add API Key to Manifest File

Now, we will add the API key in AndroidManifest.xml file. This is the key that we just generated from Google Developer Console. Replace YOUR_API_KEY_FROM_GOOGLE_DEV_CONSOLE with your own API key.

<meta-data android:name="com.google.android.geo.API_KEY" android:value="YOUR_API_KEY_FROM_GOOGLE_DEV_CONSOLE"/>

After adding the tag, the manifest xml looks as follows –

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.iteritory.itcgoogleplaceautocomplete">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <meta-data android:name="com.google.android.geo.API_KEY" android:value="YOUR_API_KEY_FROM_GOOGLE_DEV_CONSOLE"/>
    </application>

</manifest>

 

Add PlaceAutocompleteFragment to layout file

Open the layout file (app -> res -> layout -> activity_main.xml). Add the PlaceAutocompleteFragment in the layout file. Also add a textbox to display the user selection. By default, this fragment has no border or background. We will wrap this fragment in a cardview to give a better look. After adding the necessary objects, the layout file looks like –

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v7.widget.CardView
        android:id="@+id/idCardView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_marginTop="5dp"
        app:cardCornerRadius="4dp">
        <fragment
            android:id="@+id/place_autocomplete_fragment"
            android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </android.support.v7.widget.CardView>
    <TextView
        android:id="@+id/placeName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="No Place selected"
        android:textSize="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Add necessary codes to handle the search result

Now that we have added the widget, it”ll show a cardview wrapping the autocomplete widget and also a textbox. So, at this point, if user types, the widget will show related suggestion based on user input. Next, we’ll also add few lines of codes to display what user have actually selected from the suggestion list. To do this, we will add few lines of codes in MainActivity.java.

After adding the code, the MainActivity.java looks like –

package com.iteritory.itcgoogleplaceautocomplete;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.AutocompleteFilter;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TextView txtVw = findViewById(R.id.placeName);

        PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
                getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

        /*AutocompleteFilter filter = new AutocompleteFilter.Builder()
                .setCountry("IN")
                .setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES)
                .build();
        autocompleteFragment.setFilter(filter);*/
        autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
            @Override
            public void onPlaceSelected(Place place) {
                txtVw.setText(place.getName());
            }
            @Override
            public void onError(Status status) {
                txtVw.setText(status.toString());
            }
        });
    }


}

Well, that’s it. You can run the app in emulator or android phone itself and you will see that auto complete feature is ready.

Add some filters of on the search result

So far the app that we created, searches all the places in Google Database as and when you type. Pretty humongous!! isn’t it? So, if you want to limit the search by country, you can do so by adding following snippet of code.  Here, I am limiting my searches in India only. This feature is a huge saver of performance

AutocompleteFilter filter= new AutocompleteFilter.Builder()
.setCountry("IN")
.build();

autocompleteFragment.setFilter(filter);

We can also add some more filters like, searching only cities or regions or establishments etc. For example, if I want to search only cities in India, I can very well write following snippet of code –

AutocompleteFilter filter = new AutocompleteFilter.Builder()
                .setCountry("IN")
                .setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES)
                .build();
autocompleteFragment.setFilter(filter);

Conclusion

It was that easy to incorporate Google’s places auto complete feature in your app with just a few line’s of codes. Well, that’s it for today. Have good time learning . 🙂

Reference

 

Filed under:
Previous article
Next article

17 responses

  1. Wahab Asif Avatar
    Wahab Asif

    Thank you so much you have solved my problem thanks a’lot brother.

  2. Sadruddin Md Avatar

    Great to hear that brother 🙂

  3. Cayque Avatar
    Cayque

    Hello, thank you for sharing.
    I had trouble clicking on the search cardView. The following was returned to me: PLACES + API_ACCESS_NOT_CONFIGURED.
    Places SDK for Android does not appear for me.
    What can it be?
    Thank you

  4. Sitarram Gpta Avatar

    Hello Sadruddin Md,

    The example you have given is depreciated.
    Notice: The Google Play Services version of the Places SDK for Android (in Google Play Services 16.0.0) is deprecated as of January 29, 2019, and will be turned off on July 29, 2019. A new version of the Places SDK for Android is now available.

    Link: https://developers.google.com/places/android-sdk/autocomplete

    Could you please migrate with new library?

    Thanks

    1. Sadruddin Md Avatar

      Hi,
      You are right and thanks for your time and putting the comment here. I’ll update the content as soon as I get sometime. Thanks again for sharing 🙂

  5. Sitarram Gpta Avatar

    Thanks for your response, i am waiting for updates 🙂

  6. Sitarram Gpta Avatar

    Hi Sadruddin Md,

    Please let me know once you updated i am waiting forward to update.

    Thank you very much!!

  7. Muhammad Luqman Avatar
    Muhammad Luqman

    I have try same code but it not show me suggestion

  8. prince Avatar
    prince

    Place can you do the autocomplete without the watermark powered by google, Thank you

  9. Shrawan Kumar Avatar
    Shrawan Kumar

    how i can get latitude and longitude. or any url for to open the place in map?

    1. Sadruddin Md Avatar

      Hi, you can check here –>

  10. kostas Avatar
    kostas

    Thanks for the solution! One quick question, although I have created the api key and enabled the places api, I keep getting a ‘Places: Error while autocompleting: REQUEST_DENIED’ error. I tried un-restricting the api key, as google suggests for android apps, but still nothing..
    Any help is appreciated!

    1. Sadruddin Md Avatar

      Thanks for your question.
      Please get your key recreated. Please also check if you have completed your billing setup with the cards.
      https://developers.google.com/places/web-service/get-api-key

  11. abhirup patra Avatar
    abhirup patra

    Hi, can you tell how can i remove the text from the autocomplete fragment after the search is done?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.