Get country code from PlaceAutocompleteFragment android (Google Places API)

限于喜欢 提交于 2019-12-06 07:28:12

问题


In Google Places API for Android, I am using PlaceAutocompleteFragment for displaying the city/country.
Here am getting the address, name, placeId, etc.
Place object contains only these fields.

@Override
public void onPlaceSelected(Place place) {

    Log.i(TAG, "Place Selected: " + place.getName());

    // Format the returned place's details and display them in the TextView.
    mPlaceDetailsText.setText(formatPlaceDetails(getResources(), place.getName(), place.getId(),
            place.getAddress(), place.getPhoneNumber()+" "+place.getAttributions()+" :: "+place.getLocale(), place.getWebsiteUri()));

}

But I want country code also. Is there any way to get the country code from places API ? If no, Is there any alternate service for getting the country name & code while typing ?


回答1:


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.




回答2:


This will give the correct country code.

TelephonyManager tm = (TelephonyManager)activity.getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso(); 


来源:https://stackoverflow.com/questions/37051900/get-country-code-from-placeautocompletefragment-android-google-places-api

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