Setting place type filters for PlaceAutocomplete
suggest changeIn some scenarios, we might want to narrow down the results being shown by PlaceAutocomplete to a specific country or maybe to show only Regions. This can be achieved by setting an AutocompleteFilter on the intent. For example, if I want to look only for places of type REGION and only belonging to India, I would do the following:
MainActivity.java
public class MainActivity extends AppComatActivity { private static final int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1; private TextView selectedPlace; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); selectedPlace = (TextView) findViewById(R.id.selected_place); try { AutocompleteFilter typeFilter = new AutocompleteFilter.Builder() .setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS) .setCountry("IN") .build(); Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN) .setFilter(typeFilter) .build(this); startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE); } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException e) { e.printStackTrace(); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE && resultCode == Activity.RESULT_OK) { final Place place = PlacePicker.getPlace(this, data); selectedPlace.setText(place.getName().toString().toUpperCase()); } else { Toast.makeText(MainActivity.this, "Could not get location.", Toast.LENGTH_SHORT).show(); } }
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/selected_place"/> </LinearLayout>
The PlaceAutocomplete will launch automatically and you can then select a place from the results which will only be of the type REGION and will only belong to the specified country. The intent can also be launched at the click of a button.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents