有谁知道如何在Android Studio中实施Google Place Picker API?试过教程,不成功。我想要一个工作的自动完成文本字段,其中显示了地点,当您点击它将显示在Google地图片段中的地方时。
答案 0 :(得分:16)
将依赖项添加到build.gradle
:
compile "com.google.android.gms:play-services-places:10.2.0"
将密钥添加到AndroidManifest.xml
:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/map_api_key"/>
您的活动/片段需要以下属性和方法:
private final static int PLACE_PICKER_REQUEST = 999;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
checkPermissionOnActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode){
case PLACE_PICKER_REQUEST:
Place place = PlacePicker.getPlace(this, data);
String placeName = String.format("Place: %s", place.getName());
double latitude = place.getLatLng().latitude
double longitude = place.getLatLng().longitude;
}
}
}
最后,这是打开PlacePicker
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
// for activty
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
// for fragment
//startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
答案 1 :(得分:0)
在Button clicklistner或您要打开PlacePicker的位置调用此方法:
private final static int PLACE_PICKER_REQUEST = 111;
private void openPlacePicker() {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
// for activty
startActivityForResult(builder.build(this), PLACE_PICKER_REQUEST);
// for fragment
//startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
并在onActivityResult上获取结果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case PLACE_PICKER_REQUEST:
Place place = PlacePicker.getPlace(this, data);
String placeName = String.format("Place: %s", place.getName());
double latitude = place.getLatLng().latitude;
double longitude = place.getLatLng().longitude;
LatLng coordinate = new LatLng(latitude, longitude);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(coordinate);
markerOptions.title(placeName); //Here Total Address is address which you want to show on marker
mGoogleMap.clear();
markerOptions.icon(
BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
markerOptions.getPosition();
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(coordinate));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
}
}