1

In kotlin how do I get the city name of the current location from which I get the latitude and longitude values?

  • What have you tried so far? – Ammar Abdullah Aug 26 '22 at 07:21
  • I tried geocoder with getLocality() method but i had issues with implamentation. Every source i looked tried to done with java. I couldn't find any kotlin source for this. – Hakan Ulaş Aug 26 '22 at 07:42
  • private fun getCityName(lat: Double,long: Double):String{ var cityName:String = "" var countryName = "" var geoCoder = Geocoder(requireContext(), Locale.getDefault()) var Adress = geoCoder.getFromLocation(lat,long,3) cityName = Adress[0].locality println("Your City: " +cityName) return cityName } I'm trying to get the city name with this function but city name returns null – Hakan Ulaş Aug 26 '22 at 07:54
  • Do you have location permissions? – Ammar Abdullah Aug 26 '22 at 09:32
  • I solved the problem. The solve is in answers. – Hakan Ulaş Aug 26 '22 at 10:02

2 Answers2

2

The currently accepted answer will only partially fix the issue. You can test your code with different cities worldwide (Try Tokyo or Brasilia) and quickly see how it doesn't return a good result. Most likely the issue is in the other address formats.

The closest "universal" solution I've managed to find is this (it's not pretty, but so far worked with any city I've tried):

private fun getCityName(lat: Double,long: Double):String{
    var cityName: String?
    val geoCoder = Geocoder(this, Locale.getDefault())
    val address = geoCoder.getFromLocation(lat,long,1)
    cityName = address[0].adminArea
    if (cityName == null){
        cityName = address[0].locality
        if (cityName == null){
            cityName = address[0].subAdminArea
        }
    }
    return cityName
}
Kreso
  • 53
  • 6
0

First I tried to get city name with Adress[0].locality but returned null. Adress[0].adminArea gave the name of the city whose latitude and longitude I have.

private fun getCityName(lat: Double,long: Double):String{
        val cityName: String?
        val geoCoder = Geocoder(requireContext(), Locale.getDefault())
        val Adress = geoCoder.getFromLocation(lat,long,3)

        cityName = Adress[0].adminArea
       binding.txtCity.text = cityName
        return cityName
    }