Google Places Autocomplete Api 2019

时间:2019-06-11 07:32:08

标签: java android

我已经尝试了好几天了,但找不到使用Google的Places自动完成API的解决方案。我发现的所有方法都是旧版本的大多数。现在,不推荐使用Android版Places SDK的Google Play服务版本(在Google Play Services 16.0.0中),我似乎找不到有效的更新代码。我在网上找到的所有解决方案都不适合我,我什至不知道发生了什么。有人可以详细说明使用Google Place Autocomplete API的新方法的代码。

这是我到目前为止所做的。

public class SearchAndFilter extends AppCompatActivity {
    String TAG = "placeautocomplete";
    TextView txtView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_and_filter);
        txtView = findViewById(R.id.txtView);

        // Initialize Places.
        Places.initialize(getApplicationContext(), "MY_KEY");
        // Create a new Places client instance.
        PlacesClient placesClient = Places.createClient(this);

        // Initialize the AutocompleteSupportFragment.
        AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
                getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);

        // Specify the types of place data to return.
        autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));

        // Set up a PlaceSelectionListener to handle the response.
        autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
            @Override
            public void onPlaceSelected(Place place) {
                // TODO: Get info about the selected place.
                txtView.setText(place.getName()+","+place.getId());
                Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
            }

            @Override
            public void onError(Status status) {
                // TODO: Handle the error.
                Log.i(TAG, "An error occurred: " + status);
            }
        });
    }
}

布局文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.SearchAndFilter">
    <androidx.cardview.widget.CardView
        android:id="@+id/idCardView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_marginTop="5dp"
        app:cardCornerRadius="4dp">

        <fragment android:id="@+id/autocomplete_fragment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
            />

    </androidx.cardview.widget.CardView>

    <TextView
        android:id="@+id/txtView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

当我运行上面的代码时,搜索栏带有google水印,但是就像我键入的内容一样,搜索栏只是关闭了。我不知道为什么。

2 个答案:

答案 0 :(得分:0)

只需在Oncreate()中调用此函数;

    /**
 * Sets up the autocomplete fragment to show place details when a place is selected.
 */
private void setupAutoCompleteFragment() {
    PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
            getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

    AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
            .setTypeFilter(Place.TYPE_COUNTRY).setCountry("IN")

            .build();
    autocompleteFragment.setFilter(typeFilter);

    autocompleteFragment.setHint(getResources().getString(R.string.search_stadium_court_area));
    autocompleteFragment.searchIcon.setVisibility(View.GONE);
    autocompleteFragment.input.setTextSize(10f);

    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {


        @Override
        public void onPlaceSelected(Place place) {
            showPlace(getString(R.string.place_autocomplete_search_hint), place);

        }

        @Override
        public void onError(Status status) {
            showResponse("An error occurred: " + status);
        }
    });
}


    private void showPlace(String source, Place place) {
    locationSelect = AppConstants.LOCATION_SELECTED_ONITEMCLICK;

    PlaceBean placeBean = new PlaceBean();


    placeBean.setAddress(String.valueOf(place.getAddress()));
    placeBean.setLatitude(String.valueOf(place.getLatLng().latitude));
    placeBean.setLongitude(String.valueOf(place.getLatLng().longitude));
    placeBean.setName((String) place.getName());
    placeBean.setCityname(cityName);

    Intent intent = new Intent();
    intent.putExtra("location", placeBean);
    setResult(RESULT_OK, intent);
    finish();

}

答案 1 :(得分:0)

搜索栏关闭的原因是此错误

  

状态{statusCode = PLACES_API_ACCESS_NOT_CONFIGURED,分辨率为空}

关注此磁带

  

添加Gradle依赖项

implementation 'com.google.android.libraries.places:places:1.0.0'
  

初始化Place API

Places.initialize(getApplicationContext(), "YOUR_API_KEY");
  

启动自动填充意图

List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
    Intent intent = new Autocomplete.IntentBuilder(
            AutocompleteActivityMode.OVERLAY, fields)
            .build(this);
    startActivityForResult(intent, 1101);
  

onActivityResult

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == request_code) {
        if (resultCode == RESULT_OK) {
            Place place = Autocomplete.getPlaceFromIntent(data);
            Log.i(TAG, "ManishPlace: " + place.getName() + ", " + place.getId());
            txt_search.setText(place.getName());
        } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
            // TODO: Handle the error.
            Status status = Autocomplete.getStatusFromIntent(data);
            Log.i(TAG, status.getStatusMessage());
        } else if (resultCode == RESULT_CANCELED) {
            // The user canceled the operation.
        }
    }
}
  

或使用由我Master-Google-Place-API创建的GitHub示例