Android Get Latitude And Longitude From Address is the today’s main topic.
We will fetch the co ordinates in form of latitude and longitude from the address of the location.
There may be some case where user do not know his/her current location in terms of latitude and longitude but he can write his address.
In such case, you need to fetch the co ordinates from the address given by the user.
This tutorial will guide you how to insert this feature in your android application with easy and simple coding lines.
User will enter the address in the edit box. Our code will get the co ordinates (latitude and longitude) from this address using Address, Geocoder and Message class.
Read Fetched Address
Watch the below video to show how this demo tutorial is working.
Step 1. Geo Coding Class
First of all, make a new class named GeocodingLocation.java
Source code for GeocodingLocation.java is as the following
import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.IOException; import java.util.List; import java.util.Locale; public class GeocodingLocation { private static final String TAG = "GeocodingLocation"; public static void getAddressFromLocation(final String locationAddress, final Context context, final Handler handler) { Thread thread = new Thread() { @Override public void run() { Geocoder geocoder = new Geocoder(context, Locale.getDefault()); String result = null; try { List addressList = geocoder.getFromLocationName(locationAddress, 1); if (addressList != null && addressList.size() > 0) { Address address = (Address) addressList.get(0); StringBuilder sb = new StringBuilder(); sb.append(address.getLatitude()).append("\n"); sb.append(address.getLongitude()).append("\n"); result = sb.toString(); } } catch (IOException e) { Log.e(TAG, "Unable to connect to Geocoder", e); } finally { Message message = Message.obtain(); message.setTarget(handler); if (result != null) { message.what = 1; Bundle bundle = new Bundle(); result = "Address: " + locationAddress + "\n\nLatitude and Longitude :\n" + result; bundle.putString("address", result); message.setData(bundle); } else { message.what = 1; Bundle bundle = new Bundle(); result = "Address: " + locationAddress + "\n Unable to get Latitude and Longitude for this address location."; bundle.putString("address", result); message.setData(bundle); } message.sendToTarget(); } } }; thread.start(); } }
Above class is primarily using three classes : Geocoder, Address and Message.
Compiler will first start one thread.
Inside this thread, it will create the object of the Geocoder class.
Then it will fetch the latitude and longitude using .getFromLocationName() method.
An object of List class will hold the output given by .getFromLocationName() method. Object of Address class will get output from List class object.
After this, an object of StringBuilder class will fetch co ordinates and than a string variable will finally get latitude and longitude from given address.
Step 2. XML file for main activity
When you create a new project in android studio, system creates two files automatically.
One of them is activity_main.xml.
Copy the below code snippet in activity_main.xml.
<?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:background="#860808" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#fff" android:layout_marginTop="20dp" android:layout_marginLeft="20dp" android:text="Enter Address in below box" android:id="@+id/addressTV" android:textSize="19sp"/> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/etAdd" android:textColor="#fff" android:layout_marginTop="20dp" android:layout_marginLeft="20dp" android:text="Rajratna complex Tagore road Rajkot Gujarat India 360002 " /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Erase Box" android:layout_marginTop="20dp" android:layout_marginLeft="20dp" android:id="@+id/btnErase"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Get Latitude Longitude" android:layout_marginTop="20dp" android:layout_marginLeft="20dp" android:id="@+id/btn"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="19sp" android:textColor="#fff" android:text="Lat Long will appear here" android:id="@+id/tv" android:layout_marginTop="20dp" android:layout_marginLeft="20dp"/> </LinearLayout>
There are some UI widgets in the above file.
Two buttons, two text views and one edit text is present.
In the edit text, user can input the address. By default, I have written one address.
Below this edit text, there will be two buttons. One button will erase the text from the edit text when user clicks it.
Other button will fetch the latitude and longitude from the address when it is clicked.
Step 3. Writing Main File
Write down the below source code in MainActivity.java file
import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private Button button, btnErase; private TextView textView; private EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.tv); btnErase = findViewById(R.id.btnErase); editText = (EditText) findViewById(R.id.etAdd); btnErase.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editText.setText(""); } }); button = (Button) findViewById(R.id.btn); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { String address = editText.getText().toString(); GeocodingLocation locationAddress = new GeocodingLocation(); locationAddress.getAddressFromLocation(address, getApplicationContext(), new GeocoderHandler()); } }); } private class GeocoderHandler extends Handler { @Override public void handleMessage(Message message) { String locationAddress; switch (message.what) { case 1: Bundle bundle = message.getData(); locationAddress = bundle.getString("address"); Log.d("latttt",locationAddress); break; default: locationAddress = null; } textView.setText(locationAddress); } } }
Looking Main Class Deeply
Consider the below code
private Button button, btnErase; private TextView textView; private EditText editText;
Compiler will create the objects of Button, Text view and Edit text etc. classes.
Now look at the below code
btnErase.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { editText.setText(""); } });
Compiler will execute the above code when the user clicks on the erase button.
It will set the null or empty text on the edit text.
Now read the following code structure
button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { String address = editText.getText().toString(); GeocodingLocation locationAddress = new GeocodingLocation(); locationAddress.getAddressFromLocation(address, getApplicationContext(), new GeocoderHandler()); } });
When the user clicks “GET LATITUDE LONGITUDE” button, compiler will run the above code lines.
It will first get the address in the string format from the edit text.
Then it will create the object of the GeocodingLocation class.
Then compiler will user .getAddressFromLocation() method.
.getAddressFromLocation() method will get the address in string format as the first parameter, application context as a second parameter and object of GeocoderHandler() as the last parameter.
Below is the code writings for GeocoderHandler class.
private class GeocoderHandler extends Handler { @Override public void handleMessage(Message message) { String locationAddress; switch (message.what) { case 1: Bundle bundle = message.getData(); locationAddress = bundle.getString("address"); Log.d("latttt",locationAddress); break; default: locationAddress = null; } textView.setText(locationAddress); } }
Here, handleMessage() method will get the object of the Message class in it’s first parameter.
Then compiler will get the data from this object using Bundle class.
From this bundle, compiler will get the latitude and longitude in the string format using .getString(“address”) class.
Finally, compiler will set this latitude and longitude in the text view.
If you want to get address from latitude and longitude then read,
Android Get Location address from Latitude and Longitude
Android Get Current Address From Latitude and Longitude