TheJadav

Android – Get address using lattitude and longitude (Lat, Lng) using 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

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

Share this content:

Share:

More Posts

How does data persistence work in Android?

Data persistence in Android is the ability to save data to the device so that it can be accessed later, even if the app is closed or the device is restarted. There are several ways to achieve data persistence in Android

Fragments and Activities: Two Pillars of Android Development

Fragments and Activities are both important components of Android development. Fragments are a good choice for creating reusable and dynamic UIs, while Activities are a good choice for managing the lifecycle of an app’s UI and implementing core features.

Table of Contents

Send Us A Message