Any method of automatic address search from the user's current location? You do not need to fill in the address fields. Entering the zip code or clicking an address search button.
Any method of automatic address search from the user's current location? You do not need to fill in the address fields. Entering the zip code or clicking an address search button.
Take a look at the Geocoder class and your method getFromLocation .
You have a complete example on the website for Android developers, but in summary, it is something like:
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException ioException) {
Log.e(TAG, "Serviço indisponível", ioException);
} catch (IllegalArgumentException illegalArgumentException) {
Log.e(TAG, "Localização inválida", illegalArgumentException);
}
if(addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
// Esse é o endereço.
}
For more details, and a complete functional example, I recommend reading from the guide
Well, I'll separate my answer into 2 parts:
cep.setOnFocusChangeListener(OnFocusChangeListener { _, hasFocus ->
if (!hasFocus) {
if(Utils.validCep(cep.text.toString())){
//Request para o serviço de consulta do CEP
}
}
})
where: the zip code is my EditText
. I used the OnFocusChangeListener
method in this case because the way I mounted my form was the most appropriate in my view. But you can control via IMEOptions
or TextChangedListener
, as you prefer.
I'll also leave the function that validates the zip code below.
fun validCep(cep: String): Boolean {
val pattern = Pattern.compile("^[0-9]{5}-[0-9]{3}$")
val matcher = pattern.matcher(cep)
return matcher.find()
}
I like to use ViaCEP to do this.
Just send a request to the address viacep.com.br/ws/01001000/json/
, where 01001000 would be the zip code to query, and it returns you a JSON in this format:
{
"cep": "01001-000",
"logradouro": "Praça da Sé",
"complemento": "lado ímpar",
"bairro": "Sé",
"localidade": "São Paulo",
"uf": "SP",
"unidade": "",
"ibge": "3550308",
"gia": "1004"
}
Just take the return and set the address fields to your form in case of return 200
.
If you do not have a form to enter the ZIP code, the best way is to follow the answer using Geocoder, where you would get the location of the device for consultation.