[英]Get country code from PlaceAutocomplete android (Google Places API)
We are using Google PlaceAutocomplete for city picker. 我们正在将Google PlaceAutocomplete用于城市选择器。 We need to get country code for picked city.
我们需要获取所选择城市的国家代码。 I am trying to use
place.getLocale()
but its null. 我正在尝试使用
place.getLocale()
但它为null。 Is there a way I can get Country ISO code from PlaceAutocomplete returned data. 有没有一种方法可以从PlaceAutocomplete返回的数据中获取国家/地区ISO代码。
in gradle: compile 'com.google.android.gms:play-services-places:10.0.1'
在gradle中:
compile 'com.google.android.gms:play-services-places:10.0.1'
code: 码:
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.
}
}
}
late but right answer 迟到但正确的答案
you can get country code using this 您可以使用此获取国家/地区代码
add Place.Field.ADDRESS_COMPONENTS
field into your fields list 将
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);
when you get the result into onActivityResult()
you'll get full details of location into that you will find country 当您将结果输入
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.