Android Place Picker API


Introduction

In this article, we will learn about one of the greatest APIs for Android provided by Google, called Place Picker API. This API is used to Pick a Place from Google Maps Application without any Map Integration.
The Place Picker provides a UI dialog that displays an interactive map and a list of nearby places, including places corresponding to geographical addresses and local businesses. Users can choose a place, and your app can then retrieve the details of the selected place.

Place Picker API

The Place Picker provides a UI dialog that displays an interactive map and a list of nearby places, including places corresponding to geographical addresses and local businesses. Users can choose a place, and your app can then retrieve the details of the selected place. To know more, click here.

Steps

I have divided this Implementation into 4 steps as shown in the following.
  • Step 1: Creating New Project with Android Studio
  • Step 2: Enabling the API in Google Console.
  • Step 3: Setting up the library and AndroidManifest for the project.
  • Step 4: Implementation of the Place Picker API.

Step 1 - Creating New Project with Android Studio

  1. Open Android Studio and Select "Create new project".
  2. Name the project as per your wish and select your activity template.
  3. Click “finish” button to create the new project in Android Studio.

Step 2 - Enabling the API in Google Developer Console

  1. For using Google Places API, We need to know SHA1 Key, which is used in Google Developer Console. You can get your SHA1 Key using Command Prompt.
    keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
  2. Open Google Developer Console.
  3. Create New Project or you can use your Existing Project.
  4. Go to Dashboard and click Enable API.
  5. Click Google Places API for Android and Select Enable.
  6. Create new API Key, which is used later.

Step 3 - Setting up the library and AndroidManifest for the project

  1. Add Google Play service library dependency in your app level build.gradle file. Here, I used the following dependency. You can change as per your Android SDK.
    compile 'com.google.android.gms:play-services:9.2.0'
  2. Then click “Sync Now” to add the library.
  3. Now open your Manifest File (AndroidManifest.xml) and the following permission.
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />  
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
    <uses-permission android:name="android.permission.INTERNET" />
  4. Add the following meta data to apply the API KEY.
    <meta-data  
        android:name="com.google.android.geo.API_KEY"  
        android:value="Your_API_Key"/>

Step 4 - Implementation of Place Picker API

  1. Add the following to initialize the API.
    //Declaration of Google API Client  
    private GoogleApiClient mGoogleApiClient;  
    private int PLACE_PICKER_REQUEST = 1;  
    In the onCreate method of the Activity initialize the GoogleApiClient.
    mGoogleApiClient = new GoogleApiClient  
                    .Builder(this)  
                    .addApi(Places.GEO_DATA_API)  
                    .addApi(Places.PLACE_DETECTION_API)  
                    .enableAutoManage(this, this)  
                    .build();
  2. Implement the onStart and onStop method and do the client connection task.
    @Override  
    protected void onStart() {  
        super.onStart();  
        mGoogleApiClient.connect();  
    }  
      
    @Override  
    protected void onStop() {  
        mGoogleApiClient.disconnect();  
        super.onStop();  
    } 
  3. Start Place Picker Intent using the following snippet.
    PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();  
    try {  
        startActivityForResult(builder.build(MainActivity.this), PLACE_PICKER_REQUEST);  
    } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {  
        e.printStackTrace();  
    }
  4. After this, you will get Google Maps Screen like below. It has an interactive map and a list of nearby places, including places corresponding to geographical addresses and local businesses. Users can choose a place, and your app can then retrieve the details of the selected place. The Details can be retrieved in onActivityResult method of your Activity.
    @Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == PLACE_PICKER_REQUEST) {  
            if (resultCode == RESULT_OK) {  
                Place place = PlacePicker.getPlace(data, this);  
                StringBuilder stBuilder = new StringBuilder();  
                String placename = String.format("%s", place.getName());  
                String latitude = String.valueOf(place.getLatLng().latitude);  
                String longitude = String.valueOf(place.getLatLng().longitude);  
                String address = String.format("%s", place.getAddress());  
                stBuilder.append("Name: ");  
                stBuilder.append(placename);  
                stBuilder.append("\n");  
                stBuilder.append("Latitude: ");  
                stBuilder.append(latitude);  
                stBuilder.append("\n");  
                stBuilder.append("Logitude: ");  
                stBuilder.append(longitude);  
                stBuilder.append("\n");  
                stBuilder.append("Address: ");  
                stBuilder.append(address);  
                tvPlaceDetails.setText(stBuilder.toString());  
            }  
        }
    }

Demo:

Figure 1:
Place Picker Intent Builder Output
Figure 2:
Place Picker Dialog (after selecting the place)
Figure 3:
Output of the Intent Builder from onActivityResult.

Full code of MainActivity.java

public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {  
  
    private GoogleApiClient mGoogleApiClient;  
    private int PLACE_PICKER_REQUEST = 1;  
    private TextView tvPlaceDetails;  
    private FloatingActionButton fabPickPlace;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
  
        initViews();  
  
        mGoogleApiClient = new GoogleApiClient  
                .Builder(this)  
                .addApi(Places.GEO_DATA_API)  
                .addApi(Places.PLACE_DETECTION_API)  
                .enableAutoManage(this, this)  
                .build();  
  
  
        fabPickPlace.setOnClickListener(new View.OnClickListener() {  
            @Override  
            public void onClick(View view) {  
                PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();  
                try {  
                    startActivityForResult(builder.build(MainActivity.this), PLACE_PICKER_REQUEST);  
                } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) {  
                    e.printStackTrace();  
                }  
            }  
        });  
    }  
  
    private void initViews() {  
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);  
        setSupportActionBar(toolbar);  
        fabPickPlace = (FloatingActionButton) findViewById(R.id.fab);  
        tvPlaceDetails = (TextView) findViewById(R.id.placeDetails);  
    }  
  
    @Override  
    protected void onStart() {  
        super.onStart();  
        mGoogleApiClient.connect();  
    }  
  
    @Override  
    protected void onStop() {  
        mGoogleApiClient.disconnect();  
        super.onStop();  
    }  
  
    @Override  
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {  
        Snackbar.make(fabPickPlace, connectionResult.getErrorMessage() + "", Snackbar.LENGTH_LONG).show();  
    }  
  
    @Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == PLACE_PICKER_REQUEST) {  
            if (resultCode == RESULT_OK) {  
                Place place = PlacePicker.getPlace(data, this);  
                StringBuilder stBuilder = new StringBuilder();  
                String placename = String.format("%s", place.getName());  
                String latitude = String.valueOf(place.getLatLng().latitude);  
                String longitude = String.valueOf(place.getLatLng().longitude);  
                String address = String.format("%s", place.getAddress());  
                stBuilder.append("Name: ");  
                stBuilder.append(placename);  
                stBuilder.append("\n");  
                stBuilder.append("Latitude: ");  
                stBuilder.append(latitude);  
                stBuilder.append("\n");  
                stBuilder.append("Logitude: ");  
                stBuilder.append(longitude);  
                stBuilder.append("\n");  
                stBuilder.append("Address: ");  
                stBuilder.append(address);  
                tvPlaceDetails.setText(stBuilder.toString());  
            }  
        }  
    }  
}  

Download Code:

You can download the full source from the following Github link. If you Like this tutorial, Please star it in Github.

Post your doubts and comments in the comments section.

Share this

Related Posts

Previous
Next Post »

15 comments

comments
25 June 2017 at 07:42 delete

Well explained. Thanks alot.

Reply
avatar
25 June 2017 at 12:27 delete

Thanks Bro for your support

Reply
avatar
7 July 2017 at 18:50 delete

app is crashing after launching

Reply
avatar
8 July 2017 at 22:24 delete

It may crash due to permission. Check Logcat for more details about the crash/error

Reply
avatar
10 August 2017 at 10:15 delete

In my case, permission already done but maps still close immediately (ASUS, OPPO, XIAOMI). What can I do?

Reply
avatar
14 August 2017 at 19:07 delete

how to show the selected place in map

Reply
avatar
14 August 2017 at 21:37 delete

Add marker against the latitude and longitude picked into google maps

Reply
avatar
18 August 2017 at 16:27 delete

i downloaded your code and i installed in my mobile it is not working when ever i am clicking Floating action button its opening and suddenly Closing that activity could you please explain me what is the problem nothing i Changed your code

Reply
avatar
19 August 2017 at 21:05 delete

Hey bro, check with your api key and your picker api is enabled in your google api console

Reply
avatar
Anonymous
28 August 2017 at 17:36 delete

Can we change the color of the marker....If so..How can we?

Reply
avatar
16 November 2018 at 06:35 delete

hello sir, how to save it into firebase for selected location

Reply
avatar
Anonymous
5 February 2019 at 17:21 delete

Can you provide the activity_main xml file?

Reply
avatar
Anonymous
5 February 2019 at 17:29 delete

That's okay, I got it. Nice work

Reply
avatar
19 July 2019 at 23:12 delete

App is Map closes immediately as it opens. API Key is correct

Reply
avatar
14 October 2019 at 07:26 delete

Same to me, the map closed immediately while clicked the FAB. API Key has been tested on other app and the map appear.

Reply
avatar

Please Comment about the Posts and Blog