Guest User

Untitled

a guest
Feb 22nd, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. import android.location.Address
  2. import android.location.Geocoder
  3. import java.io.IOException
  4.  
  5. /**
  6. * Created by soulduse on 2018. 2. 10..
  7. */
  8. object GeocoderUtil {
  9.  
  10. fun getAddress(lat: Double, lon: Double): String{
  11. val context = MyApplication.context!!
  12. var addresses = mutableListOf<Address>()
  13. var errorMessage = ""
  14. var address: String ?= null
  15.  
  16. try {
  17. addresses = Geocoder(context).getFromLocation(lat, lon, 1)
  18. } catch (ioException: IOException) {
  19. // Catch network or other I/O problems.
  20. errorMessage = context.getString(R.string.service_not_available)
  21. } catch (illegalArgumentException: IllegalArgumentException) {
  22. // Catch invalid latitude or longitude values.
  23. errorMessage = context.getString(R.string.invalid_lat_long_used)
  24. }
  25.  
  26. if(addresses.isEmpty()) {
  27. if(errorMessage.isEmpty()) {
  28. errorMessage = context.getString(R.string.no_address_found)
  29. }
  30. }else{
  31. val addressItem = addresses.first()
  32. val addressFragments = (0 .. addressItem.maxAddressLineIndex).map { i ->
  33. addressItem.getAddressLine(i)
  34. .filterNot { // If you don't want to get some word, you can filter like this
  35. "Some string".contains(it)
  36. }
  37. }
  38.  
  39. address = addressFragments.first()
  40. }
  41.  
  42. return address ?: errorMessage
  43. }
  44. }
  45.  
  46.  
  47. // Usage
  48. val address = GeocoderUtil.getAddress(latitude, longtitude)
  49. println(address) // print you want to get address
Add Comment
Please, Sign In to add comment