为 PlaceAutocomplete 设置场所类型过滤器
在某些情况下,我们可能希望将 PlaceAutocomplete 显示的结果缩小到特定国家/地区,或者仅显示区域。这可以通过在 intent 上设置 AutocompleteFilter 来实现。例如,如果我只想查看 REGION 类型的地方并且只属于印度,我会做以下事情:
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>
该 PlaceAutocomplete 将自动启动,然后你可以选择从结果将只能是类型的地方地区和只属于指定的国家。也可以通过单击按钮启动意图。