25

I'm using Google Place API for Android with autocomplete

Everything works fine, but when I get the result as shown here, I don't have the city and postal code information.

    private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback
        = new ResultCallback<PlaceBuffer>() {
    @Override
    public void onResult(PlaceBuffer places) {
        if (!places.getStatus().isSuccess()) {
            // Request did not complete successfully
            Log.e(TAG, "Place query did not complete. Error: " + places.getStatus().toString());

            return;
        }
        // Get the Place object from the buffer.
        final Place place = places.get(0);

        // Format details of the place for display and show it in a TextView.
        mPlaceDetailsText.setText(formatPlaceDetails(getResources(), place.getName(),
                place.getId(), place.getAddress(), place.getPhoneNumber(),
                place.getWebsiteUri()));

        Log.i(TAG, "Place details received: " + place.getName());
    }
};

The Place class doesn't contain that information. I can get the full human readable address, the lat and long, etc.

How can I get the city and postal code from the autocomplete result?

ballade4op52
  • 2,142
  • 5
  • 27
  • 42
Plumillon Forge
  • 1,659
  • 1
  • 16
  • 31

6 Answers6

29

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;
 }
Leo DroidCoder
  • 14,527
  • 4
  • 62
  • 54
21

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")
                }
            }
        }
AbhishekB
  • 2,111
  • 3
  • 18
  • 23
  • Be aware - this technique can cause problems in some locations - I specifically ran into this problem with some New York addresses - Staten Island, Brooklyn, and the Bronx, as well as Clifton Park addresses use "sublocality", "administrative_area_level_3", or other types rather than "locality" for the proper "city" name used in the address – Kevin Foster Sep 29 '21 at 23:44
10

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
plexer
  • 4,542
  • 2
  • 23
  • 27
5
private Geocoder geocoder;
private final int REQUEST_PLACE_ADDRESS = 40;

onCreate

Places.initialize(context, getString(R.string.google_api_key));

Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, Arrays.asList(Place.Field.ADDRESS_COMPONENTS, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG)).build(context);
startActivityForResult(intent, REQUEST_PLACE_ADDRESS);

onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_PLACE_ADDRESS && resultCode == Activity.RESULT_OK) {
        Place place = Autocomplete.getPlaceFromIntent(data);
        Log.e("Data",Place_Data: Name: " + place.getName() + "\tLatLng: " + place.getLatLng() + "\tAddress: " + place.getAddress() + "\tAddress Component: " + place.getAddressComponents());

        try {
            List<Address> addresses;
            geocoder = new Geocoder(context, Locale.getDefault());

            try {
                addresses = geocoder.getFromLocation(place.getLatLng().latitude, place.getLatLng().longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
                String address1 = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
                String address2 = addresses.get(0).getAddressLine(1); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
                String city = addresses.get(0).getLocality();
                String state = addresses.get(0).getAdminArea();
                String country = addresses.get(0).getCountryName();
                String postalCode = addresses.get(0).getPostalCode();

                Log.e("Address1: ", "" + address1);
                Log.e("Address2: ", "" + address2);
                Log.e("AddressCity: ", "" + city);
                Log.e("AddressState: ", "" + state);
                Log.e("AddressCountry: ", "" + country);
                Log.e("AddressPostal: ", "" + postalCode);
                Log.e("AddressLatitude: ", "" + place.getLatLng().latitude);
                Log.e("AddressLongitude: ", "" + place.getLatLng().longitude);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //setMarker(latLng);
        }
    }
}
Ketan Ramani
  • 4,874
  • 37
  • 42
0

You can get address details from address array provided by Geoencoder.getFromLocation(lat , long , maxResults)

Here is the example code in kotlin:

private fun getPincode(latitude: Double, longitude: Double): String
 {
                var addresses: List<Address>? = null
                var city: String? = ""
                val geoCoder = Geocoder(this, Locale.getDefault())
              
        
                try {
                    addresses = geoCoder.getFromLocation(latitude, longitude, 1)
                    if (addresses != null && addresses.isNotEmpty()) {
    
                        val countryName = addresses[0].countryName
                        val state = addresses[0].subAdminArea
                        val address = addresses[0].featureName
                        val island = addresses[0].adminArea
        
                        try {
                            city = addresses[0].locality
                            if (city == null) city = addresses[0].subLocality
                            if (city == null) city = addresses[0].subAdminArea
                            if (city == null) city = addresses[0].adminArea
                            //  addressCity = city
                        } catch (e: Exception) {
                            //  addressCity = ""
                        }
        
                        val pinCode = addresses[0].postalCode
                        val latitudeAddress = addresses[0].latitude
                        val longitudeAddress = addresses[0].longitude
                       
                        return pinCode
                      }
                } catch (e: IOException) {
                    e.printStackTrace()
                    
                }
        
                return ""
}
-2

Not the best way, but the following can be useful:

 Log.i(TAG, "Place city and postal code: " + place.getAddress().subSequence(place.getName().length(),place.getAddress().length()));
ballade4op52
  • 2,142
  • 5
  • 27
  • 42
Gennady Kozlov
  • 1,011
  • 1
  • 11
  • 11
  • using a geocoder will definitely a better way to solve this issue, reference https://stackoverflow.com/a/35992244/1107579 – RayChongJH Dec 19 '18 at 05:13