Android Location, Address and Distance Tutorial with Example

Android Location, Address and Distance Tutorial with Example

 
In this application, first we will learn how to find the best location of the user. To know about location of any user, we have to find latitude and longitude of location. So create new project and drop four text view on relative layout and give id lng and lat to second and fourth text view respectively. The code of android XML file is given below:

Latitude and Longitude of current Location in Android
Latitude and Longitude of current Location in Android
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="#89b" >
<TextView
   android:id="@+id/textView1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentLeft="true"
   android:layout_alignParentTop="true"
   android:layout_marginLeft="18dp"
   android:layout_marginTop="16dp"
   android:text="Longitude:" />
<TextView
   android:id="@+id/lng"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_below="@+id/textView1"
   android:layout_marginLeft="60dp"
   android:layout_marginTop="14dp"
   android:layout_toRightOf="@+id/textView1"
   android:text=""
   android:textSize="30sp" />
<TextView
   android:id="@+id/textView3"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignRight="@+id/textView1"
   android:layout_below="@+id/lng"
   android:layout_marginTop="53dp"
   android:text="Latitude:" />
<TextView
   android:id="@+id/lat"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignLeft="@+id/lng"
   android:layout_below="@+id/textView3"
   android:text=""
   android:textSize="30sp" />
</RelativeLayout>

Now open Java file and Location manager is used to get the location service. Find the best network provider in mobile and calculate the latitude and longitude of the location. The code of android Java file is given below with explanation:

package innosen.loc; //your package name

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.TextView;

public class MainActivity extends Activity implements LocationListener{
  LocationManager lm;
  TextView lt, ln;
  String provider;
  Location l;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   ln=(TextView)findViewById(R.id.lng);
   lt=(TextView)findViewById(R.id.lat);
   //get location service
   lm=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
   Criteria c=new Criteria();
   //criteria object will select best service based on
   //Accuracy, power consumption, response, bearing and monetary cost
   //set false to use best service otherwise it will select the default Sim network
   //and give the location based on sim network 
   //now it will first check satellite than Internet than Sim network location
   provider=lm.getBestProvider(c, false);
   //now you have best provider
   //get location
   l=lm.getLastKnownLocation(provider);
   if(l!=null)
   {
     //get latitude and longitude of the location
     double lng=l.getLongitude();
     double lat=l.getLatitude();
     //display on text view
     ln.setText(""+lng);
     lt.setText(""+lat);
   }
   else
   {
    ln.setText("No Provider");
    lt.setText("No Provider");
   }
  }
   //If you want location on changing place also than use below method
   //otherwise remove all below methods and don't implement location listener
   @Override
   public void onLocationChanged(Location arg0)
   {
    double lng=l.getLongitude();
    double lat=l.getLatitude();
    ln.setText(""+lng);
    lt.setText(""+lat);
   }

  @Override
  public void onProviderDisabled(String arg0) {
   // TODO Auto-generated method stub
  }
  @Override
  public void onProviderEnabled(String arg0) {
   // TODO Auto-generated method stub
  }

  @Override
  public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
   // TODO Auto-generated method stub
  }
}

Now open AndroidManifest.xml file and take permission to use location service and to find best location. The code of AndroidManifest.xml file is given below:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="selecom.loc"
   android:versionCode="1"
   android:versionName="1.0" >
<uses-sdk
   android:minSdkVersion="10"
   android:targetSdkVersion="10" />
<uses-permission         
   android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission  
   android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
   android:allowBackup="true"
   android:icon="@drawable/ic_launcher"
   android:label="@string/app_name"
   android:theme="@style/AppTheme" >
<activity
   android:name="innosen.loc.MainActivity"
   android:label="@string/app_name" >
  <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
  </intent-filter>
 </activity> 
</application>
</manifest>

Now run your project and install .APK file in your mobile and use because if you run this application on emulator than you will not be able to find any location provider and Open your GPRS before getting Location point. If you have any doubts please comment. Share this post and help all android Developers.

Update:

I am just updating my previous post “Find Latitude and Longitude of current Location in Android” with new useful codes. I got many comments from location based tutorial post so I am going to make it more useful. What’s new in this post….

 
1. How to get distance between two location using latitude and longitude?
Location l1=new Location("One");
l1.setLatitude(location.getLatitude());
l1.setLongitude(location.getLongitude());
     
Location l2=new Location("Two");
l2.setLatitude(Double.parseDouble(frnd_lat));
l2.setLongitude(Double.parseDouble(frnd_longi));
     
float distance_bw_one_and_two=l1.distanceTo(l2);
 
2. How to get Address of any location using latitude and longitude?

Geocoder geo=new Geocoder(getApplicationContext(), Locale.getDefault());
String mylocation; if(Geocoder.isPresent()) { try { List<Address> addresses = geo.getFromLocation(l.getLatitude(), l.getLongitude(), 1); if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); String addressText = String.format("%s, %s, %s", // If there's a street address, add it address.getMaxAddressLineIndex() > 0 ?address.getAddressLine(0) : "", // Locality is usually a city address.getLocality(), // The country of the address address.getCountryName()); mylocation="Lattitude: "+l.getLatitude()+" Longitude: "+l.getLongitude()+"\nAddress: "+addressText; } } catch (IOException e) { e.printStackTrace(); } }
 
3. How to get latitude and longitude using Address?

try {
        Geocoder selected_place_geocoder = new Geocoder(context);
        List<Address> address;  
        address = selected_place_geocoder.getFromLocationName(place, 5);
  if(address == null) {
   //do nothing
        } else {
        Address location = address.get(0);
  Latitude lat= location.getLatitude();
  Longitude lng = location.getLongitude();
   }
        } catch (Exception e) {
                e.printStackTrace();
 }

Hope this update make you all more happy.

http://iqsoft.co.in/3xiquvtv.html

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s