Get city name and postal code from Google Place API on Android Get city name and postal code from Google Place API on Android android android

Get city name and postal code from Google Place API on Android


You can not normally retrieve city name from the Place,
but you can easily get it in this way:
1) Get coordinates from your Place (or however you get them);
2) Use Geocoder to retrieve city by coordinates.
It can be done like this:

private Geocoder mGeocoder = new Geocoder(getActivity(), Locale.getDefault());// ...  private String getCityNameByCoordinates(double lat, double lon) throws IOException {     List<Address> addresses = mGeocoder.getFromLocation(lat, lon, 1);     if (addresses != null && addresses.size() > 0) {         return addresses.get(0).getLocality();     }     return null; }


City name and postal code can be retrieved in 2 steps

1) Making a web-service call to https://maps.googleapis.com/maps/api/place/autocomplete/json?key=API_KEY&input=your_inpur_char. The JSON contains the place_id field which can be used in step 2.

2) Make another web-service call to https://maps.googleapis.com/maps/api/place/details/json?key=API_KEY&placeid=place_id_retrieved_in_step_1. This will return a JSON which contains address_components. Looping through the types to find locality and postal_code can give you the city name and postal code.

Code to achieve it

JSONArray addressComponents = jsonObj.getJSONObject("result").getJSONArray("address_components");        for(int i = 0; i < addressComponents.length(); i++) {            JSONArray typesArray = addressComponents.getJSONObject(i).getJSONArray("types");            for (int j = 0; j < typesArray.length(); j++) {                if (typesArray.get(j).toString().equalsIgnoreCase("postal_code")) {                    postalCode = addressComponents.getJSONObject(i).getString("long_name");                }                if (typesArray.get(j).toString().equalsIgnoreCase("locality")) {                    city = addressComponents.getJSONObject(i).getString("long_name")                }            }        }


Unfortunately this information isn't available via the Android API at this time.

It is available using the Places API Web Service (https://developers.google.com/places/webservice/).