我正在研究Google地图和搜索。
在地图上进行搜索的唯一选项是Google Places API。 https://developers.google.com/places/android-sdk/intro
其中还指出您的播放服务版本的SDK已过时。
所以我试图用新的SDK来实现它。 现在,我想要的是代替“自动完成”来打开一个新活动,我希望它以列表显示在我的自动完成中。
但是问题在于它适用于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。请指导我更改上面的代码。
谢谢。
答案 0 :(得分:1)
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
}
}
});
}