android - 带有 Places SDK 兼容库的 PlaceAutocompleteAdapter

标签 android google-play-services google-places-api google-places-autocomplete

我正在研究谷歌地图和搜索。

在 map 上搜索的唯一选项是 Google Places API。 https://developers.google.com/places/android-sdk/intro

其中还声明您播放服务版本的 SDK 已弃用。

所以我尝试用新的 SDK 来实现它。 现在我想要的不是自动完成来打开一个新 Activity ,而是希望它在我的自动完成中显示为列表。

所以我尝试实现这个: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;
            }

如果有人使用 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/

相关文章:

android - 如何在 android 中使用 Google 视觉 API 检测眨眼?

php - Google 使用 PHP 放置 API

android - 尽管我已按照文档中的步骤操作,但地点选择器(谷歌地图)会立即关闭

android - Android 中如何获取用户的当前位置

android - 如何为 Android 制作自定义地点选择器

android - 安卓的图表

android - 通过wifi访问Android设备中的本地主机网站

android - 移动屏幕上的布局不会改变

java - Parcelable Object Android 中的数据覆盖

android - Flutter ClassNotFoundException (java.lang.RuntimeException) 崩溃错误