August 13, 2021

Android – Get address using lattitude and longitude (Lat, Lng) using Geocoder

By lj007

Geocoder

Geocoder class can be helper class which is useful for geocoding or reverse geocoding, that means we get lattitude and longitude from address or vica versa.
We need one location to get addess. If you don’t know how to get current location VISIT HERE.
Once we get location, it is easy to get location from Geocoder. First of all initialize Geocoder. I have created one variable.

val geoCoder = Geocoder(context, Locale.getDefault())

Retrive address from geocoder

        var addresses: List<Address> = emptyList()
        try {
            addresses = geoCoder.getFromLocation(position.latitude, position.longitude, 1)
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: IllegalArgumentException){
            e.printStackTrace()
        }

This will return list of Address. ‘Address’ is class from ‘android.location’ package so we don’t need to create it. Now, to display address, we need to get information from addresses

        if(addresses.isEmpty()){

        } else {
            val address = addresses[0]
            val addressFragment = with(address){
                (0..maxAddressLineIndex).map { getAddressLine(it) }
            }
            //this displays first address, but you can loop it and display all addresses.

            tvAddress.text = addressFragment.joinToString("\n")
        }

Here is one image that shows the address return from one location:

Android – Get address using lattitude and longitude (Lat, Lng) using Geocoder