Skip to content

Instantly share code, notes, and snippets.

@soulduse
Last active February 10, 2018 06:52
Show Gist options
  • Save soulduse/fe0dbe50d3f115b6ccd35af688335309 to your computer and use it in GitHub Desktop.
Save soulduse/fe0dbe50d3f115b6ccd35af688335309 to your computer and use it in GitHub Desktop.
Geocoder util with Kotlin
import android.location.Address
import android.location.Geocoder
import java.io.IOException
/**
* Created by soulduse on 2018. 2. 10..
*/
object GeocoderUtil {
fun getAddress(lat: Double, lon: Double): String{
val context = MyApplication.context!!
var addresses = mutableListOf<Address>()
var errorMessage = ""
var address: String ?= null
try {
addresses = Geocoder(context).getFromLocation(lat, lon, 1)
} catch (ioException: IOException) {
// Catch network or other I/O problems.
errorMessage = context.getString(R.string.service_not_available)
} catch (illegalArgumentException: IllegalArgumentException) {
// Catch invalid latitude or longitude values.
errorMessage = context.getString(R.string.invalid_lat_long_used)
}
if(addresses.isEmpty()) {
if(errorMessage.isEmpty()) {
errorMessage = context.getString(R.string.no_address_found)
}
}else{
val addressItem = addresses.first()
val addressFragments = (0 .. addressItem.maxAddressLineIndex).map { i ->
addressItem.getAddressLine(i)
.filterNot { // If you don't want to get some word, you can filter like this
"Some string".contains(it)
}
}
address = addressFragments.first()
}
return address ?: errorMessage
}
}
// Usage
val address = GeocoderUtil.getAddress(latitude, longtitude)
println(address) // print you want to get address
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment