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 ?
If you have read the Google Places Autocomplete doc,you must know about API properties. you can use the type as '(region)' and will return you many results (plus country). And if you look inside address_components field (it's array with dynamic length),you will see,that the last item of array is what you need.
Go to APIs & Services → Dashboard → Enable APIs & Services at the top and Choose Maps Javascript API from the API Library. This will open up the Map JavaScript API page, and Enable it.
Places API is not free, however, once you set up your billing account, you will be entitled for a one time $300 free credit(usable for Google Cloud Platform products) and a monthly recurring $200 free credit(exclusive for Google Maps Platform products), after consuming the credits, you will receive an OVER_QUERY_LIMIT ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With