Get country code from PlaceAutocompleteFragment android (Google Places API)

感情迁移 提交于 2019-12-04 16:03:48

With the Place object retrieved, you can get the Locale object associated :

Locale locale = place.getLocale();

With this Locale object you can then get the Country code via :

locale.getCountry();

And the country name with :

locale.getDisplayCountry();

You can look to more available methods at the docs : http://developer.android.com/reference/java/util/Locale.html

EDIT :

If Locale from the Place object is null you can use a Geocoder to get information from GPS coordinates :

LatLng coordinates = place.getLatLng(); // Get the coordinates from your place
Geocoder geocoder = new Geocoder(this, Locale.getDefault());

List<Address> addresses = geocoder.getFromLocation(
                coordinates.latitude,
                coordinates.longitude,
                1); // Only retrieve 1 address
Address address = addresses.get(0);

Then you can call these methods to get the informations you want

address.getCountryCode();
address.getCountryName();

More methods on the Address objects : http://developer.android.com/reference/android/location/Address.html

Be aware that the Geocoder methods should be call on a background thread to not block the UI and that it could also retrieve no answer.

Sonali

This will give the correct country code.

TelephonyManager tm = (TelephonyManager)activity.getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso(); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!