Como posso bifurcado componente de endereço sábia que eu estou recebendo diretamente do Google Lugar API?

Tarun Sharma:

Quero chegar a cidade, estado, país, pino em uma variável diferente, como como eu estou recebendo o endereço, lat, e longitude. Mas eu não sei como eu posso obter o endereço componente-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);
        }
    });
}
 }

Eu só quero abordar em componentes como Endereço, Cidade, Estado, Pin.

Andrii Omelchenko:

Você deve usar não Address= place.getAddress(), mas .getAddressComponents()para fazer isso, porque .getAddress()retorna Stringcom endereço legível do lugar e na documentação oficial do Google escreveu:

Não analisar o endereço formatado programaticamente. Em vez disso você deve usar os componentes de endereço individuais, que a resposta da API inclui, além do campo de endereço formatado.

Então, você deve usar Place.getAddressComponents()para obter List<AddressComponent>e de nome get e tipo de cada componente de endereço . Ou utilize a pedido adicional de local de latitude / longitude e Geocoder.getFromLocation()como em exibição um endereço de localização Exemplo Oficial:

...
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));
    }
}
...

Também dê uma olhada em Guia do desenvolvedor .

PS Não use nomes em letras maiúsculas (por exemplo, Latitude) para variáveis - este é o estilo de classes. Nomeá-lo apenas latitude.

Acho que você gosta

Origin http://43.154.161.224:23101/article/api/json?id=333639&siteId=1
Recomendado
Clasificación