我正在研究谷歌地图和搜索。
在 map 上搜索的唯一选项是 Google Places API。 https://developers.google.com/places/android-sdk/intro
其中还声明您播放服务版本的 SDK 已弃用。
所以我尝试用新的 SDK 来实现它。 现在我想要的不是自动完成来打开一个新 Activity ,而是希望它在我的自动完成中显示为列表。
但问题是它适用于 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;
}
如果有人使用 New Places API 库实现了 PlacesAutoCompleteAdapter。请指导我更改上述代码。
谢谢。
最佳答案
引用链接:
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
}
}
});
}
关于android - 带有 Places SDK 兼容库的 PlaceAutocompleteAdapter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54783052/