此前,Android 版 Places SDK 是通过 Google Play 服务提供的。Android 版 Places SDK 的 Google Play 服务版本已弃用,Google 将于 2019 年 7 月 29 日之前将其关闭。
但是,新版本的 Android 版 Places SDK 作为静态客户端库进行分发。
新 SDK 客户端库的依赖项
implementation 'com.google.android.libraries.places:places:1.0.0'
您可以使用以下两种方法之一在 Android 应用程序中添加 Google 地点自动完成功能:
1) Either embed a AutocompleteSupportFragment
OR
2) Use an intent to launch the autocomplete activity.
我通过嵌入下面的 AutocompleteSupportFragment 创建了一个演示应用程序:-
package com.places_api_demo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.util.Arrays;
import com.google.android.gms.common.api.Status;
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.AutocompleteSupportFragment;
import com.google.android.libraries.places.widget.listener.PlaceSelectionListener;
import com.google.android.libraries.places.api.Places;
import static com.google.android.libraries.places.api.model.Place.Field.LAT_LNG;
public class MainActivity extends AppCompatActivity {
String TAG = "placeautocomplete";
TextView txtView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtView = findViewById(R.id.txtView);
// Initialize Places.
Places.initialize(getApplicationContext(), "REPLACE YOUR API KEY HERE");
// Create a new Places client instance.
PlacesClient placesClient = Places.createClient(this);
// Initialize the AutocompleteSupportFragment.
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
// Specify the types of place data to return.
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG));
// Set up a PlaceSelectionListener to handle the response.
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
txtView.setText(place.getName()+"\n"+place.getId()+"\n"+ place.getLatLng());
Log.i(TAG, "Place: " + place.getName() + ", " + place.getLatLng());
}
@Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});
}
}
指定要返回的地点数据的类型也很重要
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.LAT_LNG, Place.Field.ID, Place.Field.NAME));
有关地点数据字段的更多详细信息,请参阅此处 https://developers.google.com/places/android-sdk/reference/com/google/android/libraries/places/api/model/Place.Field