本指南介绍了地点兼容性库与独立版 Places SDK for Android 之间的更改。如果您一直在使用地点兼容性库,而不是迁移到新的独立版本 Places SDK for Android,本指南将向您演示如何更新项目,以使用新版 Places SDK for Android。
届时,只能使用 Places SDK for Android 访问 Places SDK for Android 2.6.0 以上版本的功能和问题修复。Google 建议您尽快从兼容性库更新为新的 Places SDK for Android 版本。
发生了哪些变化?
主要变更如下:
- 新版 Places SDK for Android 以静态客户端库的形式分发。2019 年 1 月之前,Places SDK for Android 通过 Google Play 服务提供。自此之后,我们提供了地点兼容性库,以简化向新的 Places SDK for Android 的过渡。
- 此外,我们还提供了全新的方法。
- 返回地点详情的方法现在支持字段掩码。您可以使用字段掩码来指定返回哪些类型的地点数据。
- 用于报告错误的状态代码已得到改进。
- 自动补全功能现在支持会话令牌。
- 地点选取器已不再可用。
地点兼容性库简介
2019 年 1 月,随着独立版 Places SDK for Android 1.0 版的发布,Google 提供了一个兼容性库,以帮助从已停用的 Google Play 服务地点 SDK for Android (com.google.android.gms:play-services-places
) 进行迁移。
此兼容性库已暂时提供,用于将针对 Google Play 服务版本的 API 调用重定向到新的独立版本,直到开发者可以迁移其代码以在独立 SDK 中使用新名称。对于每个从 1.0 版到 2.6.0 版发布的 Places SDK for Android 版本,都发布了相应的地点兼容性库版本,以提供等效功能。
冻结并弃用地点兼容性库
自 2022 年 3 月 31 日起,适用于 Places SDK for Android 的所有版本的兼容性库都将被弃用。2.6.0 版是地点兼容性库的最后一个版本。届时,只能使用 Places SDK for Android 访问 Places SDK for Android 2.6.0 以上版本的功能和问题修复。
Google 建议您迁移到 Places SDK for Android,以使用 2.6.0 以上版本的新功能和关键 bug 修复。如果您目前使用的是兼容性库,请按照安装 Places SDK for Android 部分中的步骤操作,迁移到 Places SDK for Android。
安装客户端库
新版 Places SDK for Android 以静态客户端库的形式进行分发。
使用 Maven 将 Places SDK for Android 添加到您的 Android Studio 项目:
如果您目前使用的是地点兼容性库:
替换
dependencies
部分中的以下行:implementation 'com.google.android.libraries.places:places-compat:X.Y.Z'
下面这行代码会切换到 Places SDK for Android:
implementation 'com.google.android.libraries.places:places:3.1.0'
如果您目前使用的是 Play 服务版 Places SDK for Android:
替换
dependencies
部分中的以下行:implementation 'com.google.android.gms:play-services-places:X.Y.Z'
下面这行代码会切换到 Places SDK for Android:
implementation 'com.google.android.libraries.places:places:3.1.0'
同步您的 Gradle 项目。
将应用项目的
minSdkVersion
设置为 16 或更高版本。更新“由 Google 提供支持”素材资源:
@drawable/powered_by_google_light // OLD @drawable/places_powered_by_google_light // NEW @drawable/powered_by_google_dark // OLD @drawable/places_powered_by_google_dark // NEW
构建您的应用。如果您看到 Places SDK for Android 的转换后看到任何构建错误,请参阅下文,了解如何解决这些错误。
初始化新的 Places SDK 客户端
初始化新的 Places SDK 客户端,如以下示例所示:
// Add an import statement for the client library.
import com.google.android.libraries.places.api.Places;
...
// Initialize Places.
Places.initialize(getApplicationContext(), apiKey);
// Create a new Places client instance.
PlacesClient placesClient = Places.createClient(this);
状态代码
QPS 限制错误的状态代码已更改。QPS 限制错误现在通过 PlaceStatusCodes.OVER_QUERY_LIMIT
返回。没有更多 QPD。
添加了以下状态代码:
REQUEST_DENIED
- 表示请求已被拒绝。可能的原因包括:- 未提供 API 密钥。
- 提供的 API 密钥无效。
- Places API 尚未启用 Places API。
- 提供的 API 密钥存在不正确的密钥限制。
INVALID_REQUEST
- 表示请求因参数缺失或无效而无效。NOT_FOUND
- 表示给定请求没有结果。
新方法
新版本的 Places SDK for Android 引入了全新的方法,旨在实现一致性。所有新方法都遵循以下各项:
- 端点不再使用
get
动词。 - 请求和响应对象与相应客户端方法具有相同的名称。
- 请求对象现在有构建器;所需的参数会作为请求构建器参数进行传递。
- 缓冲区不再使用。
本部分将介绍新的方法,并介绍它们的工作原理。
按 ID 提取地点
使用 fetchPlace()
可获取特定地点的详细信息。fetchPlace()
功能类似于 getPlaceById()
。
请按以下步骤提取地点:
调用
fetchPlace()
,传递FetchPlaceRequest
对象,用于指定地点 ID 和字段列表,指定要返回的地点数据。// Define a Place ID. String placeId = "INSERT_PLACE_ID_HERE"; // Specify the fields to return. List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME); // Construct a request object, passing the place ID and fields array. FetchPlaceRequest request = FetchPlaceRequest.builder(placeId, placeFields) .build();
调用
addOnSuccessListener()
来处理FetchPlaceResponse
。系统会返回单个Place
结果。// Add a listener to handle the response. placesClient.fetchPlace(request).addOnSuccessListener((response) -> { Place place = response.getPlace(); Log.i(TAG, "Place found: " + place.getName()); }).addOnFailureListener((exception) -> { if (exception instanceof ApiException) { ApiException apiException = (ApiException) exception; int statusCode = apiException.getStatusCode(); // Handle error with given status code. Log.e(TAG, "Place not found: " + exception.getMessage()); } });
获取地点照片
使用 fetchPhoto()
可获取地点照片。fetchPhoto()
会返回地点的照片。请求照片的模式已简化。您现在可以直接从 Place
对象请求 PhotoMetadata
;不再需要单独的请求。照片的宽度或高度上限为 1600 像素。fetchPhoto()
函数类似于 getPhoto()
。
请按以下步骤获取地点照片:
设置向
fetchPlace()
拨打的电话。请务必在请求中包含PHOTO_METADATAS
字段:List<Place.Field> fields = Arrays.asList(Place.Field.PHOTO_METADATAS);
获取地点对象(此示例使用
fetchPlace()
,但您也可以使用findCurrentPlace()
):FetchPlaceRequest placeRequest = FetchPlaceRequest.builder(placeId, fields).build();
添加
OnSuccessListener
以从FetchPlaceResponse
中生成的Place
中获取照片元数据,然后使用生成的照片元数据获取位图和提供方说明文本:placesClient.fetchPlace(placeRequest).addOnSuccessListener((response) -> { Place place = response.getPlace(); // Get the photo metadata. PhotoMetadata photoMetadata = place.getPhotoMetadatas().get(0); // Get the attribution text. String attributions = photoMetadata.getAttributions(); // Create a FetchPhotoRequest. FetchPhotoRequest photoRequest = FetchPhotoRequest.builder(photoMetadata) .setMaxWidth(500) // Optional. .setMaxHeight(300) // Optional. .build(); placesClient.fetchPhoto(photoRequest).addOnSuccessListener((fetchPhotoResponse) -> { Bitmap bitmap = fetchPhotoResponse.getBitmap(); imageView.setImageBitmap(bitmap); }).addOnFailureListener((exception) -> { if (exception instanceof ApiException) { ApiException apiException = (ApiException) exception; int statusCode = apiException.getStatusCode(); // Handle error with given status code. Log.e(TAG, "Place not found: " + exception.getMessage()); } }); });
从用户所在位置查找地点
使用 findCurrentPlace()
查找用户设备的当前位置。findCurrentPlace()
会返回 PlaceLikelihood
列表,其中指出用户的设备最可能位于的地点。findCurrentPlace()
功能类似于 getCurrentPlace()
。
请按照以下步骤获取用户设备的当前位置:
确保您的应用会请求
ACCESS_FINE_LOCATION
和ACCESS_WIFI_STATE
权限。用户必须授予访问其当前设备位置信息的权限。如需了解详情,请参阅请求应用权限。创建一个
FindCurrentPlaceRequest
,其中包含要返回的地点数据类型的列表。// Use fields to define the data types to return. List<Place.Field> placeFields = Arrays.asList(Place.Field.NAME); // Use the builder to create a FindCurrentPlaceRequest. FindCurrentPlaceRequest request = FindCurrentPlaceRequest.builder(placeFields).build();
调用 findCurrentPlace 并处理响应,首先检查以验证用户是否已授予使用其设备位置信息的权限。
// Call findCurrentPlace and handle the response (first check that the user has granted permission). if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { placesClient.findCurrentPlace(request).addOnSuccessListener(((response) -> { for (PlaceLikelihood placeLikelihood : response.getPlaceLikelihoods()) { Log.i(TAG, String.format("Place '%s' has likelihood: %f", placeLikelihood.getPlace().getName(), placeLikelihood.getLikelihood())); textView.append(String.format("Place '%s' has likelihood: %f\n", placeLikelihood.getPlace().getName(), placeLikelihood.getLikelihood())); } })).addOnFailureListener((exception) -> { if (exception instanceof ApiException) { ApiException apiException = (ApiException) exception; Log.e(TAG, "Place not found: " + apiException.getStatusCode()); } }); } else { // A local method to request required permissions; // See https://developer.android.com/training/permissions/requesting getLocationPermission(); }
查找自动补全联想查询
使用 findAutocompletePredictions()
返回地点预测以响应用户搜索查询。findAutocompletePredictions()
功能类似于 getAutocompletePredictions()
。
以下示例展示了如何调用 findAutocompletePredictions()
:
// Create a new token for the autocomplete session. Pass this to FindAutocompletePredictionsRequest,
// and once again when the user makes a selection (for example when calling fetchPlace()).
AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
// Create a RectangularBounds object.
RectangularBounds bounds = RectangularBounds.newInstance(
new LatLng(-33.880490, 151.184363),
new LatLng(-33.858754, 151.229596));
// Use the builder to create a FindAutocompletePredictionsRequest.
FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
// Call either setLocationBias() OR setLocationRestriction().
.setLocationBias(bounds)
//.setLocationRestriction(bounds)
.setCountry("au")
.setTypesFilter(Arrays.asList(PlaceTypes.ADDRESS))
.setSessionToken(token)
.setQuery(query)
.build();
placesClient.findAutocompletePredictions(request).addOnSuccessListener((response) -> {
for (AutocompletePrediction prediction : response.getAutocompletePredictions()) {
Log.i(TAG, prediction.getPlaceId());
Log.i(TAG, prediction.getPrimaryText(null).toString());
}
}).addOnFailureListener((exception) -> {
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
Log.e(TAG, "Place not found: " + apiException.getStatusCode());
}
});
会话令牌
会话令牌将用户搜索的查询和选择阶段归入不同的会话,以便进行结算。我们建议您针对所有自动补全会话使用会话令牌。会话在用户开始输入查询内容时开始,并在用户选择地点时结束。在每个会话中,用户可以输入多项查询内容,并最终选择一个地点。会话结束后,令牌将失效;您的应用必须为每个会话生成一个新的令牌。
字段掩码
在返回地点详情的方法中,您必须指定要随每个请求返回哪些类型的地点数据。这有助于确保您只请求您实际使用的数据(并为其付费)。
如需指定要返回的数据类型,请在 FetchPlaceRequest
中传递 Place.Field
数组,如以下示例所示:
// Include address, ID, and phone number.
List<Place.Field> placeFields = Arrays.asList(Place.Field.ADDRESS,
Place.Field.ID,
Place.Field.PHONE_NUMBER);
您可以使用以下一个或多个字段:
Place.Field.ADDRESS
Place.Field.ID
Place.Field.LAT_LNG
Place.Field.NAME
Place.Field.OPENING_HOURS
Place.Field.PHONE_NUMBER
Place.Field.PHOTO_METADATAS
Place.Field.PLUS_CODE
Place.Field.PRICE_LEVEL
Place.Field.RATING
Place.Field.TYPES
Place.Field.USER_RATINGS_TOTAL
Place.Field.VIEWPORT
Place.Field.WEBSITE_URI
详细了解地点数据 SKU。
地点选择器和自动补全更新
本部分介绍了对地点 widget(地点选择器和自动补全)的更改。
程序化自动补全
我们对自动补全功能做出了以下更改:
PlaceAutocomplete
已重命名为Autocomplete
。- 已将
PlaceAutocomplete.getPlace
重命名为Autocomplete.getPlaceFromIntent
。 - 已将
PlaceAutocomplete.getStatus
重命名为Autocomplete.getStatusFromIntent
。
- 已将
PlaceAutocomplete.RESULT_ERROR
已重命名为AutocompleteActivity.RESULT_ERROR
(自动补全 fragment 的错误处理方式未更改)。
地点选取器
地点选取器已于 2019 年 1 月 29 日弃用。该功能已于 2019 年 7 月 29 日停用,不再提供。如果继续使用,将会显示错误消息。新的 SDK 不支持地点选取器。
自动补全 widget
自动补全 widget 已更新:
- 已从所有类中移除
Place
前缀。 - 新增了对会话令牌的支持。微件会在后台自动管理令牌。
- 添加了对字段掩码的支持,可让您选择在用户做出选择后返回哪些类型的地点数据。
下面几部分将介绍如何为您的项目添加自动补全 widget。
嵌入 AutocompleteFragment
如需添加自动补全 fragment,请按以下步骤操作:
将 fragment 添加到 activity 的 XML 布局中,如以下示例所示。
<fragment android:id="@+id/autocomplete_fragment" android:layout_width="match_parent" android:layout_height="wrap_content" android:name= "com.google.android.libraries.places.widget.AutocompleteSupportFragment" />
如需向 activity 添加自动补全 widget,请按以下步骤操作:
- 初始化
Places
,并传递应用上下文和 API 密钥。 - 初始化
AutocompleteSupportFragment
。 - 调用
setPlaceFields()
以指明您想获取的地点数据类型。 - 添加
PlaceSelectionListener
以处理结果,并处理可能发生的任何错误。
以下示例展示了如何向 activity 添加自动补全 widget:
/** * Initialize Places. For simplicity, the API key is hard-coded. In a production * environment we recommend using a secure mechanism to manage API keys. */ if (!Places.isInitialized()) { Places.initialize(getApplicationContext(), "YOUR_API_KEY"); } // Initialize the AutocompleteSupportFragment. AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment) getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment); autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME)); autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() { @Override public void onPlaceSelected(Place place) { // TODO: Get info about the selected place. Log.i(TAG, "Place: " + place.getName() + ", " + place.getId()); } @Override public void onError(Status status) { // TODO: Handle the error. Log.i(TAG, "An error occurred: " + status); } });
- 初始化
使用 intent 启动自动补全 activity
- 初始化
Places
,传递应用上下文和您的 API 密钥 - 使用
Autocomplete.IntentBuilder
创建 intent,并传递所需的PlaceAutocomplete
模式(全屏或叠加层)。该 intent 必须调用startActivityForResult
,并传入用于标识您的 intent 的请求代码。 - 替换
onActivityResult
回调以接收所选地点。
以下示例展示了如何使用 intent 启动自动补全功能,然后处理结果:
/**
* Initialize Places. For simplicity, the API key is hard-coded. In a production
* environment we recommend using a secure mechanism to manage API keys.
*/
if (!Places.isInitialized()) {
Places.initialize(getApplicationContext(), "YOUR_API_KEY");
}
...
// Set the fields to specify which types of place data to return.
List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
// Start the autocomplete intent.
Intent intent = new Autocomplete.IntentBuilder(
AutocompleteActivityMode.FULLSCREEN, fields)
.build(this);
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
...
/**
* Override the activity's onActivityResult(), check the request code, and
* do something with the returned place data (in this example its place name and place ID).
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
// TODO: Handle the error.
Status status = Autocomplete.getStatusFromIntent(data);
Log.i(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
}
地点选取器已不再可用
地点选取器已于 2019 年 1 月 29 日弃用。该功能已于 2019 年 7 月 29 日停用,不再提供。如果继续使用,将会显示错误消息。新的 SDK 不支持地点选取器。