Android Articles » Auto Place Listing Using Google API

Introduction

Are you building an app which needs dynamic listing of places? No need to go for any custom or conventional solutions, using country, places database. Just as in many other fields, Google has made our life easier! We can implement dynamic listing of places using the Google Maps API.


Google provides an easy to use widget, which instantly display the auto complete suggestions, when we start typing in. One can choose the correct option from the list & we can capture the value in our app.


Here is a live demo of, what we are about to accomplish!





First of all we need to create an API Key from the Google Developers Console, and also we need to enable the Google Places API.


So let us start with the project.


The dependencies used for this project are as shown below.





Please add the following dependencies to the build.gradle(Module:app) of our project. (Add which all are not present).



compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
compile 'com.android.support:support-v13:26.0.0-alpha1'
compile 'com.android.support:cardview-v7:26.0.0-alpha1'
compile 'com.android.support:support-v4:26.0.0-alpha1'
compile 'com.google.android.gms:play-services:11.4.2'


Now, open the build.gradle(Project...) which is the first node of the Gradle Scripts. Add the following code to the ‘repositories’ section of ‘allprojects’, as shown below.


allprojects { repositories { jcenter() maven { url "https://maven.google.com" } } } }


Now, we need an API key . Go to the link (given below) to create an API key:



https://developers.google.com/places/web-service/get-api-key


Click Get A Key button. In the pop-up window select Create a New Project and give a Project Name.









Now you will obtain the API key for our project. Copy this key and paste it in the AndroidManifest.xml as follows


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

The complete AndroidManifest.xml is :

   <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="your_package_name">
   
       <uses-permission android:name="android.permission.INTERNET" />
   
       <application
           android:allowBackup="true"
           android:icon="@mipmap/ic_launcher"
           android:label="@string/app_name"
           android:theme="@style/AppTheme">
   
           <meta-data
               android:name="com.google.android.geo.API_KEY"
               android:value="obtained_api_key" />
   
           <activity
               android:name=".MainActivity"
               android:label="@string/app_name">
               <intent-filter>
                   <action android:name="android.intent.action.MAIN" />
                   <category android:name="android.intent.category.LAUNCHER" />
               </intent-filter>
           </activity>
       </application>
   
   </manifest>

Now In the Android Studio, open the strings.xml in the values res folder:

					
   <resources>
   
       <string name="app_name">"Your_Project_Name</string>
       <string name="place_details">
       <![CDATA[
           <b>%1$s</b>
           <br/>
           Place Id: %2$s
           <br/>
           Address: %3$s
           <br/>
           Phone: %4$s
           <br/>
           Website: %5$s
       ]]>
       </string>
   </resources>					

dimens.xml


   <resources>
       <!-- Default screen margins, per the Android Design guidelines. -->
       <dimen name="activity_horizontal_margin">16dp</dimen>
       <dimen name="activity_vertical_margin">16dp</dimen>
       <dimen name="margin_tiny">4dp</dimen>
       <dimen name="margin_small">8dp</dimen>
       <dimen name="margin_medium">16dp</dimen>
       <dimen name="margin_large">32dp</dimen>
       <dimen name="margin_huge">64dp</dimen>
       <dimen name="horizontal_page_margin">@dimen/margin_medium</dimen>
       <dimen name="vertical_page_margin">@dimen/margin_medium</dimen>
   </resources>

In the main_activity.xml file, use this code:


   <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:app="http://schemas.android.com/apk/res-auto"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:background="#cc2a9926">
   
       <LinearLayout
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:orientation="vertical"
           android:paddingBottom="@dimen/vertical_page_margin"
           android:paddingLeft="@dimen/horizontal_page_margin"
           android:paddingRight="@dimen/horizontal_page_margin"
           android:paddingTop="@dimen/vertical_page_margin">
   
           <android.support.v7.widget.CardView
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:layout_marginBottom="@dimen/margin_medium"
               android:layout_marginTop="@dimen/margin_medium"
               app:cardElevation="5dp">
   
               <fragment
                   android:id="@+id/fragment_autocomplete"
                   android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
                   android:layout_width="match_parent"
                   android:layout_height="45dp" />
   
           </android.support.v7.widget.CardView>
   
           <TextView
               android:id="@+id/txt_place_details"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:autoLink="all"
               android:textStyle="bold" />
   
           <TextView
               android:id="@+id/txt_place_attrib"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:autoLink="all"
               android:paddingTop="@dimen/margin_medium" />
       </LinearLayout>
   </ScrollView>

Now, in the MainActivity java class add this code:


   import com.google.android.gms.common.api.Status;
   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;
   
   import android.content.res.Resources;
   import android.net.Uri;
   import android.os.Bundle;
   import android.support.v4.app.FragmentActivity;
   import android.text.Html;
   import android.text.Spanned;
   import android.text.TextUtils;
   import android.widget.TextView;
   import android.widget.Toast;
   
   public class MainActivity extends FragmentActivity implements PlaceSelectionListener {
   
       TextView txtPlaceDetails;
       TextView txtPlaceAttrib;
   
       @Override
       protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
   
           setContentView(R.layout.activity_main);
   
           // Retrieve the PlaceAutocomplete.
           PlaceAutocompleteFragment autocomplete = (PlaceAutocompleteFragment)
                   getFragmentManager().findFragmentById(R.id.fragment_autocomplete);
   
        /*  Register a listener to receive callbacks when a place has been selected or an error has occurred.*/
   
           autocomplete.setOnPlaceSelectedListener(this);
   
           // Retrieve the textViews that will display details about the selected place.
   
           txtPlaceDetails = (TextView) findViewById(R.id.txt_place_details);
           txtPlaceAttrib = (TextView) findViewById(R.id.txt_place_attrib);
       }
   
   
       /*Callback invoked when a place has been selected from the PlaceAutocomplete.*/
   
       @Override
       public void onPlaceSelected(Place place) {
           // Display the place's details in the textView.
           txtPlaceDetails.setText(formatPlaceDetails(getResources(), place.getName(), place.getId(),
                   place.getAddress(), place.getPhoneNumber(), place.getWebsiteUri()));
           txtPlaceDetails.setTextSize(20);
   
           CharSequence attributions = place.getAttributions();
           if (!TextUtils.isEmpty(attributions)) {
               txtPlaceAttrib.setText(Html.fromHtml(attributions.toString()));
           } else {
               txtPlaceAttrib.setText("");
           }
       }
   
       /*Callback invoked when PlaceAutocomplete encounters an error.*/
       @Override
       public void onError(Status status) {
   
           Toast.makeText(this, "Place selection was failed: " + status.getStatusMessage(),
                   Toast.LENGTH_SHORT).show();
       }
   
       private static Spanned formatPlaceDetails(Resources res, CharSequence name, String id,
                                                 CharSequence address, CharSequence phoneNumber, Uri websiteUri) {
           return Html.fromHtml(res.getString(R.string.place_details, name, id, address, phoneNumber,
                   websiteUri));
       }
   }

Now, we need to enable the Google Places API to obtained the place listing. For this go to this link:



https://console.developers.google.com/flows/enableapi?apiid=geocoding_backend&reusekey=true


Select the previously created project and click continue.





In the Credentials we can see the previously created API key:




Now, select the Edit option.


Select the Android apps option(since we are using the project for android devices) and add the package name and the SHA-1 Fingerprint of our project and save:




Next, select the Library and select Google Places API for Android and Enable this API.




Now try running the app & you should get the output, as you see in the live demo.