我在使用 Android Google Places API - 自动完成功能时遇到问题。
我正在尝试使用 Places.GeoDataApi.getAutocompletePredictions()获取 placeId 的方法,但是,它不起作用。(输出甚至不显示“无法获取值”) 谁能帮帮我?
这是我的 Java 代码:
PendingResult<AutocompletePredictionBuffer> result =
Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, query,
mLatLonBounds, null);
result.setResultCallback(new ResultCallback<AutocompletePredictionBuffer>() {
@Override
public void onResult(@NonNull AutocompletePredictionBuffer autocompletePredictions) {
if (autocompletePredictions.getStatus().isSuccess()) { //如果回傳SUCCESS
Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
resultList = new ArrayList<>(autocompletePredictions.getCount());
while (iterator.hasNext()) {
AutocompletePrediction prediction = iterator.next();
resultList.add(prediction.getPlaceId().toString());
}
}
else {
resultList.add("can't get the vaule");
}
autocompletePredictions.release();
}
});
textView.setText(resultList.get(0).toString());
谢谢。
最佳答案
我遇到了同样的问题,我按照以下步骤解决了这个问题
- 在开发人员控制台中启用适用于 Android 的 Google Places API,并且 在凭据页面上检查您的 key 是否仍然存在。
- 将所需的库添加到您的模块 (play-services-places:11.2.0+)。
使用下面的代码得到预测
Task<AutocompletePredictionBufferResponse> results = mGeoDataClient.getAutocompletePredictions(yourInputString, yourLatLngBounds, yourTypeFilter);
为下面的预测添加成功监听器
results.addOnSuccessListener(new OnSuccessListener<AutocompletePredictionBufferResponse>() { @Override public void onSuccess(AutocompletePredictionBufferResponse autocompletePredictions) { Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator(); suggesstions = new ArrayList<String>(autocompletePredictions.getCount()); if (iterator.hasNext()) { while (iterator.hasNext()) { AutocompletePrediction prediction = iterator.next(); //do your stuff with prediction here } }else { //Nothing matches... } autocompletePredictions.release(); } });
为下面的预测添加失败监听器
results.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(MapsActivity.this,"Error while fetching suggessions : "+e.getLocalizedMessage(),Toast.LENGTH_SHORT).show(); } });
如果以上所有代码 fragment 都正确放置,那么您可能会检查您的互联网连接。
希望以上代码对您有所帮助。
谢谢。
关于java - Places.GeoDataApi.getAutocompletePredictions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44006282/