Я работаю с картами Google и поиском.
Единственным вариантом поиска на карте является API Google Places. 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 с библиотекой New Places API. Пожалуйста, помогите мне изменить приведенный выше код.
Спасибо.
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
}
}
});
}