适用于 Android 的 Google Places SDK 已弃用,因此我们需要迁移Places API。要使用新的 Places API 实现AutoComplete Place .. 请按照以下步骤操作。
首先在开发者控制台中启用 PlacesAPI,然后通过在 gradle 中更新来安装客户端库。
(注意:您只能安装客户端库或兼容性库,不能同时安装)
implementation 'com.google.android.libraries.places:places:1.0.0'
现在在 Oncreate() 中初始化下面的代码;
// Add an import statement for the client library.
import com.google.android.libraries.places.api.Places;
// Initialize Places.
Places.initialize(getApplicationContext(), "***YOUR API KEY***");
// Create a new Places client instance.
PlacesClient placesClient = Places.createClient(this);
新 PlacesAPI 已初始化..
对于自动完成的地方使用下面的代码(你也可以使用自动完成片段)
// 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
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.
}
}
}
- 确保清单中的权限
- 生成的 API 密钥。
- 在开发控制台中启用了 Places API。
删除(如果您添加了)
implementation 'com.google.android.gms:play-services-places:16.0.0'
需要的头文件
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.google.android.libraries.places.widget.Autocomplete;
import com.google.android.libraries.places.widget.AutocompleteActivity;
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode;
希望这会有所帮助..