Android Get Address From Latitude And Longitude | Get City Name

android get address from latitude and longitude, android get current address, android get latitude and longitude from address, android volley post request with parameters, android volley get request with parameters, android login and register using volley

Welcome to Android Get Address From Latitude And Longitude tutorial example.

You will learn get country, city name , postal code, pin code or zip code from latitude and longitude of any location.

For this purpose, we will use Geocoder and Address classes from android library.

Geocoder class will get the latitude and longitude of any place as an input and gives us the street address of that location as an output.

For more exposure, we will get the address from three different countries.

We will make one spinner, which has three different places and user will select place from this spinner.

After the selection, we will fetch the address of that selected place.

Look at below address

Load the below video to see the output of this tutorial example.

Now follow all the below steps to make above example.

Step 1. Permission of Internet

First of all, create a new project in the android studio.

While making a new project, select “Empty activity” as a template.

Now in the AndroidManifest.xml file, add the below line

<uses-permission android:name="android.permission.INTERNET" />

So the final source code for AndroidManifest.xml file is looking like the following

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.parsaniahardik.addresslatlong">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Internet is considered as the safe permission for user’s privacy. Hence, we do not need to ask for runtime permission in this tutorial.

Step 2. Write XML file

In the activity_main.xml file, add the below code snippet

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Spinner
        android:id="@+id/spinner"
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="60dp">


    </Spinner>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Full Address : "
            android:textColor="#000"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            android:textColor="#000"
            android:textSize="18sp" />


    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Feature : "
            android:textColor="#000"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/tvFeature"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            android:textColor="#000"
            android:textSize="18sp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Country : "
            android:textColor="#000"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/tvCountry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            android:textColor="#000"
            android:textSize="18sp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="State : "
            android:textColor="#000"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/tvState"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            android:textColor="#000"
            android:textSize="18sp" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="City : "
            android:textColor="#000"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/tvCity"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            android:textColor="#000"
            android:textSize="18sp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Pincode : "
            android:textColor="#000"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/tvPincode"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            android:textColor="#000"
            android:textSize="18sp" />

    </LinearLayout>

</LinearLayout>
  • I have added one spinner at the top of the file.
  • User will have to select any place from this spinner. We will fetch the address of that selected place.
  • Other text views will hold the information like full address, country name, city name, state name and pin code or zip code.

Step 3. Main JAVA file

Source code for MainActivity.java file is like the following code structure.

import android.location.Address;
import android.location.Geocoder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    String names[] = {"Taj mahal","Eiffel Tower","Burj khalifa"};
    Double latitude[] = {27.1750,48.8584,25.1972};
    Double longitude[] = {78.0422,2.2945,55.2744};
    private TextView textView, tvCountry, tvCity, tvState, tvPincode, tvFeature;
    private Spinner spinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        spinner = findViewById(R.id.spinner);

        textView = findViewById(R.id.tv);
        tvCountry = findViewById(R.id.tvCountry);
        tvState = findViewById(R.id.tvState);
        tvCity = findViewById(R.id.tvCity);
        tvPincode = findViewById(R.id.tvPincode);
        tvFeature = findViewById(R.id.tvFeature);

        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,   android.R.layout.simple_spinner_item, names);
        spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
        spinner.setAdapter(spinnerArrayAdapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                setTexts(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

 }

    private void setTexts(int position){

        Geocoder geocoder;
        List<Address> addresses = null;
        geocoder = new Geocoder(this, Locale.getDefault());

        try {
            addresses = geocoder.getFromLocation(latitude[position], longitude[position], 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.d("max"," "+addresses.get(0).getMaxAddressLineIndex());

        String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
        String city = addresses.get(0).getLocality();
        String state = addresses.get(0).getAdminArea();
        String country = addresses.get(0).getCountryName();
        String postalCode = addresses.get(0).getPostalCode();
        String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

        addresses.get(0).getAdminArea();
        textView.setText(address);
        tvFeature.setText(knownName);
        tvCountry.setText(country);
        tvState.setText(state);
        tvCity.setText(city);
        tvPincode.setText(postalCode);

    }

}

Starring At Main Activity

Let us look more deeply in main activity and understand what every line will do.

First of all, consider the below code lines

String names[] = {"Taj mahal","Eiffel Tower","Burj khalifa"};
    Double latitude[] = {27.1750,48.8584,25.1972};
    Double longitude[] = {78.0422,2.2945,55.2744};
    private TextView textView, tvCountry, tvCity, tvState, tvPincode, tvFeature;
    private Spinner spinner;
  • First line will create one string array. This string array contains the name of the famous places like Taj Mahal, Eiffel Tower and Burj Khalifa.
  • We will set these place names in the spinner and user will select place from that spinner.
  • Second line is the double array variable. It holds the values of the latitudes of the places.
  • For example, it’s first value is the latitude of Taj Mahal, second is of Eiffel tower and last is of Burj Khalifa.
  • Similarly, third line is the double array with longitude values of the places in similar order.
  • Fourth line will create some objects of the text view class which will hold values like country, city pin code etc.
  • Last one is the object of the spinner class.

Now read the below code snippet

ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,   android.R.layout.simple_spinner_item, names);
        spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
        spinner.setAdapter(spinnerArrayAdapter);
  • Using the first line, compiler will create the object of the array adapter.
  • Here, compiler will use the string array ( which include the names of the places ) as the data source.
  • Then second line will set the look and feel of the drop down menu for spinner.
  • Finally, last line will set the adapter to the spinner.

Now attend the below code

 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                setTexts(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
  • Compiler will execute the above code when the user clicks the spinner and selects any option.
  • Here, it will call the setTexts() method.
  • In the parameters of setTexts() method, compiler will put the selected position in an integer format.

Following are the coding lines for setTexts() method

 private void setTexts(int position){

        Geocoder geocoder;
        List<Address> addresses = null;
        geocoder = new Geocoder(this, Locale.getDefault());

        try {
            addresses = geocoder.getFromLocation(latitude[position], longitude[position], 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.d("max"," "+addresses.get(0).getMaxAddressLineIndex());

        String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
        String city = addresses.get(0).getLocality();
        String state = addresses.get(0).getAdminArea();
        String country = addresses.get(0).getCountryName();
        String postalCode = addresses.get(0).getPostalCode();
        String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

        addresses.get(0).getAdminArea();
        textView.setText(address);
        tvFeature.setText(knownName);
        tvCountry.setText(country);
        tvState.setText(state);
        tvCity.setText(city);
        tvPincode.setText(postalCode);

    }
  • At the staring of the method, compiler will create the object of Geocoder class and a list of Address class.
  • Then it will fetch the address using .getFromLocation() method.
  • Parameter for .getFromLocation() method are latitude and longitude of the place.
  • At this point, we have get the address from latitude and longitude.
  • Then compiler will get the full address, city, state, country, postal code and knownName in the string format.

And finally, set all these values into the various text views and we are ready for the app launch !

Download Code For Android Get Address From Latitude And Longitude

Download Source code for Address from LatLong