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

时间:2018-04-04 08:49:09

标签: android google-maps google-maps-android-api-2

我已经完成了这段代码来获取城市名称。但现在根据新的要求,我还需要来自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);
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

这样对我有用:

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();
}

答案 1 :(得分:0)

使用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();
}