Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
Add Comment
Please, Sign In to add comment