PlaceAutocompleteAdapter с совместимой библиотекой Places SDK - PullRequest
0 голосов
/ 20 февраля 2019

Я работаю над картами Google и выполняю поиск.

Единственный вариант поиска на карте - это Google Places API.https://developers.google.com/places/android-sdk/intro

В нем также указано, что вы играете служебную версию SDK, и она устарела.

Поэтому я пытался реализовать ее с помощью нового SDK.Теперь вместо автозаполнения я хочу открыть новое действие. Я хочу, чтобы оно отображалось в виде списка автозаполнения.

Поэтому я попытался реализовать это: https://github.com/googlesamples/android-play-places/blob/master/PlaceCompleteAdapter/Application/src/main/java/com/example/google/playservices/placecomplete/PlaceAutocompleteAdapter.java

Нопроблема в том, что он работает с версией сервиса Play, но не с версией Compat, потому что классы и импорт различаются.

Это часть кода, с которой у меня возникают проблемы:

// Submit the query to the autocomplete API and retrieve a PendingResult that will
            // contain the results when the query completes.
            PendingResult<AutocompletePredictionBuffer> results =
                    Places.GeoDataApi
                            .getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
                                    mBounds, mPlaceFilter);

            // This method should have been called off the main UI thread. Block and wait for at most 60s
            // for a result from the API.
            AutocompletePredictionBuffer autocompletePredictions = results
                    .await(60, TimeUnit.SECONDS);

            // Confirm that the query completed successfully, otherwise return null
            final Status status = autocompletePredictions.getStatus();
            if (!status.isSuccess()) {
                Toast.makeText(getContext(), "Error contacting API: " + status.toString(),
                        Toast.LENGTH_SHORT).show();
                Log.e(TAG, "Error getting autocomplete prediction API call: " + status.toString());
                autocompletePredictions.release();
                return null;
            }

Если кто-то реализовал PlacesAutoCompleteAdapter с библиотекой API New Places.Пожалуйста, помогите мне изменить указанный выше код.

Спасибо.

1 Ответ

0 голосов
/ 05 марта 2019

Reference link:

https://developers.google.com/places/android-sdk/autocomplete#get_place_predictions_programmatically

Шаг 1. Запуск нового PlaceClient

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

Шаг 2. Создание запроса

// contain the results when the query completes.
  FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
       // similar to previous mBounds
      // but you have to use Rectangular bounds (Check reference link)
      .setLocationRestriction(mBounds)  
      .setQuery(constraint.toString()) // similar to previous constraint
      .setTypeFilter(TypeFilter.ADDRESS) // similar to mPlaceFilter
      .build();

Шаг 3. Отправьте объект запроса методу ответа

Task<FindAutocompletePredictionsResponse> task =
      placeClient.findAutocompletePredictions(request);

Шаг 4. Обрабатывайте здесь код OnSuccess

  task.addOnSuccessListener(
      (response) -> {
        for (AutocompletePrediction prediction : response.getAutocompletePredictions()) {
          Timber.d("prediction result: " + prediction);

          // add result to your arraylist
        }
        // return your arraylist outside foreach loop
      });

Шаг 5. Здесь обрабатывайте код OnFailure

task.addOnFailureListener((exception) -> {
    if (exception instanceof ApiException) {
      ApiException apiException = (ApiException) exception;
      // places not found exception code
      Timber.i("error message %s", apiException.getMessage());
    }
  });

Шаг 6. Обработайте код OnComplete здесь

task.addOnCompleteListener((response) -> {
    Exception e = task.getException();
    if (e instanceof ApiException) {
      ApiException apiException = (ApiException) e;
      if (!task.isSuccessful()) {
        // your code
      }
    }
  });
}
...