1

I have done as below in Kotlin to get the Address from LatLng using GeoCoder in Android :

 private fun getAddress(latLng: LatLng): String {
    // 1
    val geocoder = Geocoder(this)
    val addresses: List<Address>?
    val address: Address?
    var addressText = ""

    try {
        // 2
        addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)
        // 3
        if (null != addresses && !addresses.isEmpty()) {
            address = addresses[0]
            for (i in 0 until address.maxAddressLineIndex) {
                addressText += if (i == 0) address.getAddressLine(i) else "\n" + address.getAddressLine(i)
            }
        }
    } catch (e: IOException) {
        Log.e("MapsActivity", e.localizedMessage)
    }

    Log.e("ADDRESS TEXT >>",""+addressText)

    return addressText
}

But, Am getting 0 for address.maxAddressLineIndex.

address and addresses[0] has the values. I checked by debugging it.

And that's why my for loop is not executing inside.

What might be the issue? Any Solution please.

Jaimin Modi
  • 1,530
  • 4
  • 20
  • 72

2 Answers2

0

I’m not quite sure about what You are trying to implement but I believe You want to access an address based on given coordinates. The for loop I believe is executing and like You said, it’s returning the value 0. This zero is not the number of addresses associated with the coordinates but the index at which the address You have supplied can be accessed for the available AddressLines. So it means there is only one address at index zero.

So since You know it’s one address linked to the address line at those coordinates, then You can access the data at this index directly.

if (null != addresses && !addresses.isEmpty()) {
    address = addresses[0]
    addressText = “$address.locality , $address.latitude” //etc and other methods You can access.....
}

Hope that It helps but if You still want to access the addresses via the loop, its better You have the maximumAddressLine more than zero.

It worked well.

Jaimil Patel
  • 1,301
  • 6
  • 13
AlphaCode
  • 11
  • 1
0

the problem that you are facing is that maxAddressLineIndex returns an index starting from 0.

The quickest fix is just to add 1 to the for loop as it goes until address.maxAddressLineIndex.

for (i in 0 until address.maxAddressLineIndex + 1) {
                addressText += if (i == 0) address.getAddressLine(i) else "\n" + address.getAddressLine(i)
            }

This should solve the problem.