如何从 PlaceAutocomplete api 获取城市和州名称?

How can i get City and State name from PlaceAutocomplete api?

我已经完成了获取城市名称的代码。但现在根据新要求,我还需要 com.google.android.gms.location.places.ui.PlaceAutocomplete api 中的州名称。 您可以参考我为获取城市所做的代码。

AutocompleteFilter autocompleteFilter = new AutocompleteFilter.Builder()
                    .setCountry("IN")
                    .setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS)
                    .build();

            Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)//MODE_OVERLAY
                    .setFilter(autocompleteFilter)
                    .build(this);
            startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);


 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
            Utils.dismissProgressBar();
            if (resultCode == RESULT_OK) {
                Place place = PlaceAutocomplete.getPlace(this, data);
                AppLog.log(TAG, "Place: " + place.getName());
                AppLog.log(TAG, "getAddress: " + place.getAddress());
                mCityName.setText(place.getName());
            } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
                Status status = PlaceAutocomplete.getStatus(this, data);
                AppLog.log(TAG, status.getStatusMessage());
                Toast.makeText(status.getStatusMessage(), true);
            } else if (resultCode == RESULT_CANCELED) {
                //Toast.makeText("Unable to find place", true);
            }
        }
    }

使用Geocoder我们可以得到城市名称。 试试这个。

final Place place = PlaceAutocomplete.getPlace(this,data);
Geocoder geocoder = new Geocoder(this);
try
{
    List<Address> addresses = geocoder.getFromLocation(place.getLatLng().latitude,place.getLatLng().longitude, 1);
    String address = addresses.get(0).getAddressLine(0);
    String city = addresses.get(0).getAddressLine(1);
    //String country = addresses.get(0).getAddressLine(2);  

} catch (IOException e){
    e.printStackTrace();
}

它对我有用:

final Place place = PlaceAutocomplete.getPlace(this,data);
Geocoder geocoder = new Geocoder(this);
try
{
    List<Address> addresses = geocoder.getFromLocation(place.getLatLng().latitude,place.getLatLng().longitude, 1);
    String city = addresses.get(0).getSubAdminArea();
    String country = addresses.get(0).getAdminArea();  

} catch (IOException e){
    e.printStackTrace();
}