从PlaceAutocomplete android(Google Places API)获取国家/地区代码

时间:2016-12-22 07:44:30

标签: android google-places-api

我们正在使用Google PlaceAutocomplete进行城市选择。我们需要获取已选城市的国家/地区代码。我正在尝试使用place.getLocale(),但它为null。有没有办法从PlaceAutocomplete返回数据中获取国家ISO代码。

在gradle中: compile 'com.google.android.gms:play-services-places:10.0.1'

代码:

private void openCityPicker() {
        try {
            AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
                    .setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES)
                    .build();
            Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                    .setFilter(typeFilter)
                    .build(this);
            startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
        } catch (GooglePlayServicesRepairableException e) {
            // TODO: Handle the error.
        } catch (GooglePlayServicesNotAvailableException e) {
            // TODO: Handle the error.
        }
    }

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                com.google.android.gms.location.places.Place googleApiPlace = PlaceAutocomplete.getPlace(this, data);
                Log.d(TAG, "onActivityResult: " + googleApiPlace.getAddress());

                Log.d(TAG, " googleApiPlace.getLocale().getCountry(): " + googleApiPlace.getLocale().getCountry());
                Log.d(TAG, " googleApiPlace.getLocale().getDisplayCountry(): " + googleApiPlace.getLocale().getDisplayCountry());

            } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
                Status status = PlaceAutocomplete.getStatus(this, data);
                // TODO: Handle the error.
                Log.i(TAG, status.getStatusMessage());

            } else if (resultCode == RESULT_CANCELED) {
                // The user canceled the operation.
            }
        } 
    }

1 个答案:

答案 0 :(得分:0)

迟到但正确的答案

您可以使用此代码获取国家/地区代码

Place.Field.ADDRESS_COMPONENTS字段添加到您的字段列表中

List<Place.Field> fields = Arrays.asList(Place.Field.ADDRESS_COMPONENTS);
Intent intent = new Autocomplete.IntentBuilder(
            AutocompleteActivityMode.FULLSCREEN, fields)
            .setTypeFilter(TypeFilter.CITIES)
            .build(mActivity);
startActivityForResult(intent, requestCode);

将结果输入onActivityResult()时,您将获得位置的完整详细信息,可以找到国家/地区

if (place.getAddressComponents() != null) {
    List<AddressComponent> addressComponents = place.getAddressComponents().asList();
    for (int i = 0; i < addressComponents.size(); i++) {
         if (addressComponents.get(i).getTypes().get(0).equals("country")) {
              countryCode = addressComponents.get(i).getShortName();
              break;
         }
    }
}