How to get complete address (State, City, District) using Latitude and Longitude using Reverse Geocoding in Android ?

Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate. Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address. The amount of detail in a reverse geocoded location description may vary, for example one might contain the full street address of the closest building, while another might contain only a city name and postal code.

Set the following permission in app/src/main/AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

The last known location of the device is a useful starting point for the address lookup feature. Refer HERE for how to get the last known location.

The code used for reverse geodecoding is normally look like as below,

Location mLocation = null;

fusedLocationClient!!.lastLocation
        .addOnSuccessListener { location : Location? -&gt;;
            // Got last known location. In some rare situations this can be null.
        mLocation = location
                if (mLocation != null) {
                    getCompleteReadableAddress()
                }
        }
 
    fun getCompleteReadableAddress() {
        val geocoder = Geocoder(this, Locale.getDefault())
        // Address found using the Geocoder.
        var addresses: List&amp;lt;Address&amp;gt; = emptyList()
        if (mLocation != null) {
            Log.d(TAG,"Last known Latitude :: " + mLocation!!.getLatitude() + " Longitude :: " + mLocation!!.getLongitude()
            )
            try {
            addresses = geocoder.getFromLocation(
                mLocation!!.getLatitude(),
                mLocation!!.getLongitude(),
                // In this sample, we get just a single address.
                1
            )
            } catch (e: Exception) {
               e.printStackTrace()
            }
            if (addresses != null &amp;&amp; !addresses.isEmpty()) {
                val address = addresses[0]
                Log.d(TAG, "CompleteReadableAddress: " + address)
                Log.d(TAG, "Admin area " + address.adminArea)
            }
        }
    }

References – https://developer.android.com/training/location/display-address#kotlin

Follow Lynxbee

Leave a Reply / Ask Question