Skip to main content

Simplify Your Tax Calculations with GST Calculator 2024: The Ultimate Tool for Businesses and Individuals

How to fetch Latitude, Longitude from address and vice-versa(address from Latitude, Longitude) using Google Geo coder SDK in android| Kotlin

 In this Android development related article, you will get a simple solution that, how to get address using Latitude, Longitude and vice-versa. i.e latitude, longitude from an address text. It is very easy and simple. Read full article and carefully follow all the steps.



Here we use google Geocoder SDK.

Okay, first we create an android project in kotlin and create an Activity say MainActivity.kt. Use the below code-

Function get Latitude, Longitude from Address-

     fun getLatLngFromAddress(context: Context, mAddress: String): String {

        val coder = Geocoder(context)
        lateinit var address: List<Address>


        try {
            address = coder.getFromLocationName(mAddress, 5)
            if (address == null) {
                return "Fail to find Lat,Lng"
            }
            val location = address[0]



            return " Latitude: ${location.latitude}\n Longitude: ${location.longitude}"
        } catch (e: Exception) {
            return "Fail to find Lat,Lng"

        }
    }


Function get Address from Latitude, Longitude-

    fun getAddressFromLatLng(context: Context, latitude: String, longitude: String): String {
        val addresses: List<Address>
        val geocoder = Geocoder(context, Locale.getDefault())

        try {
            addresses = geocoder.getFromLocation(
                latitude.toDouble(),
                longitude.toDouble(),
                5
            )


            return if (addresses.isNotEmpty()) {
                val address =
                    addresses[0].getAddressLine(0)

                val city = addresses[0].locality
                val state = addresses[0].adminArea
                val country = addresses[0].countryName
                val postalCode = addresses[0].postalCode
                address
            } else {
                "No Address found"
            }


        } catch (e: Exception) {

            e.printStackTrace()
            return "Fail to search Address"
        }


    }


Full Source Code

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="35dp"
        android:text="@string/address_from_latitude_longitude"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/etLatitude"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="15dp"
        android:layout_marginTop="15dp"
        android:layout_marginEnd="15dp"
        android:digits="0123456789.-"
        android:hint="@string/enter_latitude"
        android:imeOptions="actionNext"
        android:inputType="numberDecimal"
        android:maxLength="25"
        app:layout_constraintTop_toBottomOf="@id/tvText1" />

    <EditText
        android:id="@+id/etLongitude"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="15dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="15dp"
        android:digits="0123456789.-"
        android:hint="@string/enter_longitude"
        android:imeOptions="actionDone"
        android:inputType="numberDecimal"
        android:maxLength="25"
        app:layout_constraintTop_toBottomOf="@id/etLatitude" />

    <Button
        android:id="@+id/btnGetAddress"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:background="@color/colorPrimary"
        android:minHeight="45dp"
        android:text="@string/get_address"
        app:layout_constraintEnd_toEndOf="@id/etLatitude"
        app:layout_constraintStart_toStartOf="@id/etLatitude"
        app:layout_constraintTop_toBottomOf="@id/etLongitude" />

    <TextView
        android:id="@+id/tvText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="35dp"
        android:text="Lat,Lng from Address"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/btnGetAddress" />

    <EditText
        android:id="@+id/etAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="15dp"
        android:layout_marginTop="15dp"
        android:layout_marginEnd="15dp"
        android:hint="@string/enter_address"
        android:maxLength="300"
        android:maxLines="5"
        app:layout_constraintTop_toBottomOf="@id/tvText2" />

    <Button
        android:id="@+id/btnGetLatLng"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:background="@color/colorPrimary"
        android:minHeight="45dp"
        android:text="@string/get_lat_lng"
        android:textAllCaps="false"
        app:layout_constraintEnd_toEndOf="@id/etAddress"
        app:layout_constraintStart_toStartOf="@id/etAddress"
        app:layout_constraintTop_toBottomOf="@id/etAddress" />

</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity.Kt




package com.example.location

import android.content.Context
import android.location.Address
import android.location.Geocoder
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

class MainActivity : AppCompatActivity() {
    private val context = this
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        btnGetAddress.setOnClickListener {
            val mLat = etLatitude.text.toString().trim()
            val mLng = etLongitude.text.toString().trim()
            if (mLat.isNotEmpty() && mLng.isNotEmpty()) {
                Toast.makeText(
                    context,
                    getAddressFromLatLng(context, mLat, mLng),
                    Toast.LENGTH_SHORT
                )
                    .show()
            } else {
                Toast.makeText(context, "Please Enter Lat,Lng", Toast.LENGTH_SHORT).show()
            }

        }







        btnGetLatLng.setOnClickListener {
            val mmAddress = etAddress.text.toString().trim()
            if (mmAddress.isNotEmpty()) {
                Toast.makeText(
                    context,
                    getLatLngFromAddress(context, mmAddress),
                    Toast.LENGTH_SHORT
                )
                    .show()
            } else {
                Toast.makeText(context, "Please Enter Address", Toast.LENGTH_SHORT).show()
            }
        }

    }

    fun getLatLngFromAddress(context: Context, mAddress: String): String {

        val coder = Geocoder(context)
        lateinit var address: List<Address>


        try {
            address = coder.getFromLocationName(mAddress, 5)
            if (address == null) {
                return "Fail to find Lat,Lng"
            }
            val location = address[0]

            return " Latitude: ${location.latitude}\n Longitude: ${location.longitude}"
        } catch (e: Exception) {
            return "Fail to find Lat,Lng"

        }
    }

    fun getAddressFromLatLng(context: Context, latitude: String, longitude: String): String {
        val addresses: List<Address>
        val geocoder = Geocoder(context, Locale.getDefault())

        try {
            addresses = geocoder.getFromLocation(
                latitude.toDouble(),
                longitude.toDouble(),
                5
            )


            return if (addresses.isNotEmpty()) {
                val address =
                    addresses[0].getAddressLine(0)

                val city = addresses[0].locality
                val state = addresses[0].adminArea
                val country = addresses[0].countryName
                val postalCode = addresses[0].postalCode
                address
            } else {
                "No Address found"
            }


        } catch (e: Exception) {

            e.printStackTrace()
            return "Fail to search Address"
        }


    }
}












Comments

Popular posts from this blog