The autocomplete service in the Google Places API for Android returns place predictions in response to user search queries.
Add the dependency to your buid.gradile
1 |
compile 'com.google.android.gms:play-services-location:11.6.0' |
Add the following tag to your AndroidManifest.xml under application tag.
1 |
<meta-data android:name="com.google.android.geo.API_KEY" android:value="Your api key"/> |
Creating the layouts of the main GooglePlacesAutocompleteActivity
1 2 3 4 5 6 |
<fragment android:id="@+id/place_autocomplete_fragment" android:layout_width="match_parent" android:layout_height="wrap_content" android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment" /> |
Place is an instance of PlaceAutocompteFragment setOnPlaceSelectedListener to place instance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
PlaceAutocompleteFragment place= (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment); place.setOnPlaceSelectedListener(new PlaceSelectionListener() { @Override public void onPlaceSelected(Place place) { Toast.makeText(getApplicationContext(),place.getName(),Toast.LENGTH_SHORT).show(); } @Override public void onError(Status status) { Toast.makeText(getApplicationContext(),status.toString(),Toast.LENGTH_SHORT).show(); } }); |
You can filter the places which should be listed in suggestion, Like suppose if you want to show just city name instead of entire address, you can add the filter like this:
1 2 3 4 |
AutocompleteFilter filter = new AutocompleteFilter.Builder() .setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES) .build(); place.setFilter(filter); |