How can I bifurcated address component wise which I am getting directly from Google Place API?

TARUN SHARMA :

I want to get the city, state, country, pin into a different variable like as I am getting the address, lat, and longitude. But I don't know how can I get address component-wise.

public class MainActivity extends AppCompatActivity {
String TAG = "placeautocomplete";
String API = "xxxxxxxxxxxxxxxxx";
String Latitude;
String Longitude;
double lat, lng;
String Address,Place_name,Phone,Complete_address;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    edit = findViewById(R.id.editText);
    txtView = findViewById(R.id.txtView);
    // Initialize Places.
    Places.initialize(getApplicationContext(), API);
    // Create a new Places client instance.
    PlacesClient placesClient = Places.createClient(this);

    // Initialize the AutocompleteSupportFragment.
    if (!Places.isInitialized()) {
        Places.initialize(getApplicationContext(), API);


    }

    // Initialize the AutocompleteSupportFragment.
    AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
            getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);

    assert autocompleteFragment != null;

    autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME,Place.Field.LAT_LNG, Place.Field.ADDRESS,Place.Field.PHONE_NUMBER));
    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            // TODO: Get info about the selected place.
            Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());

            if (place.getLatLng() !=null){
                lat =place.getLatLng().latitude;
                lng =place.getLatLng().longitude;

            }
            Latitude = String.valueOf(lat);
            Longitude= String.valueOf(lng);
            Address= place.getAddress();
            Place_name = place.getName();
            Phone = place.getPhoneNumber();

        }
        @Override
        public void onError(Status status) {
            // TODO: Handle the error.
            Log.i(TAG, "An error occurred: " + status);
        }
    });
}
 }

I just want to address in components like Address, City, State, Pin.

Andrii Omelchenko :

You should use not Address= place.getAddress() but .getAddressComponents() for do that, because .getAddress() returns String with human-readable address of place and in Official Documentation Google wrote:

Do not parse the formatted address programmatically. Instead you should use the individual address components, which the API response includes in addition to the formatted address field.

So, you should use Place.getAddressComponents() to get List<AddressComponent> and than get name and type of each address component. Or use additional request for place lat/lng and Geocoder.getFromLocation() like in Display a location address Official Example:

...
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;

...
addresses = geocoder.getFromLocation(
            Latitude,    // <-- your Latitude = String.valueOf(lat);
            Longitude,   // <- your Longitude= String.valueOf(lng);
            location.getLongitude(),
            // In this sample, get just a single address.
            1);

// Handle case where no address was found.
if (addresses == null || addresses.size()  == 0) {
    if (errorMessage.isEmpty()) {
        errorMessage = getString(R.string.no_address_found);
        Log.e(TAG, errorMessage);
    }
    deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
} else {
    Address address = addresses.get(0);
    ArrayList<String> addressFragments = new ArrayList<String>();

    // Fetch the address lines using getAddressLine,
    // join them, and send them to the thread.
    for(int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
        addressFragments.add(address.getAddressLine(i));
    }
}
...

Also take a look at Developer Guide.

P.S. Do not use capitalized names (for example, Latitude) for variables - this is the style for classes. Name it just latitude.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326738&siteId=1