Search Tutorials

Loading...

Monday, 28 October 2013

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.

Related Tutorials:-

Advance Android Google Map 2 Tutorial with Examples - Part 1

Advance Android Google Map 2 Tutorial with Examples - Part 2

Android Sensor | Motion detection Tutorial

Convert Text to Speech Tutorial

Android Shared Preferences Tutorial

64 comments:

  1. Muito bom e como mostrar no mapa a minha localização atual

    ReplyDelete
    Replies
    1. Obrigado, eu não postar relacionada ao Mapa, mas eu tenho um bom link para compartilhar, por favor vê-lo por google map e se você tem qualquer problema de perguntar.

      http://umut.tekguc.info/en/content/google-android-map-v2-step-step

      In English:

      Thanks , I didn't post related to Map but i have a good link to share, please see it for google map and if you have any problem than ask.

      http://umut.tekguc.info/en/content/google-android-map-v2-step-step

      Delete
    2. u all need to update google play.... and your gps and locations must be enabled

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. i was use this code and create apk or install it on a my device but it give the message "no provider"
    whats the problem plz giv me rply for that prblm

    ReplyDelete
    Replies
    1. This problem will come only when you don't have sim in your phone or your network is unreachable.

      Delete
    2. me too facing the same issue.. displaying as no provider

      Delete
    3. same problem no provider any solution plz

      Delete
    4. i am facing same problem... :( no provide..

      Delete
    5. This comment has been removed by the author.

      Delete
    6. u all need to update google play.... and your gps and locations must be enabled

      Delete
  4. their are several errors in it,i tried a lot but no help

    ReplyDelete
    Replies
    1. this is working code bro..where you are getting problem?

      Delete
    2. i try to include both wifi on/off & location in main activity class? tell me if i m wrong? & yeah if u can come on hangouts it wud be a fast chat as i already msgd u sir,please?

      Delete
    3. yes you can include both wifi and location program in main activity class.

      Delete
    4. i did but it shows several errors? how to remove them, i m copying my main activity code here in next comment!

      Delete
    5. import android.app.Activity;
      import android.content.Intent;
      import android.location.LocationListener;
      import android.net.wifi.WifiManager;
      import android.os.Bundle;
      import android.view.MenuItem;
      import android.view.View;
      import android.widget.Button;


      public abstract class MainActivity extends Activity implements LocationListener{
      WifiManager wm;
      LocationManager lm;
      TextView lt, ln;
      String provider;
      Location l;
      @Override
      public 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();

      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
      }
      }



      }
      public void call(View v)
      {
      Intent i=new Intent(this, activityclick.class);
      startActivity(i);
      finish();
      }

      public void wifioff(View v)
      {
      Button b1=(Button)findViewById(R.id.button2);
      wm=(WifiManager)getSystemService(WIFI_SERVICE);

      if(wm.isWifiEnabled())
      {
      b1.setText("Wifi ON");
      wm.setWifiEnabled(false);
      }
      else
      {
      b1.setText("Wifi OFF");
      wm.setWifiEnabled(true);
      }
      }







      @Override
      public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      int id = item.getItemId();
      if (id == R.id.action_settings) {
      return true;
      }
      return super.onOptionsItemSelected(item);
      }
      }

      Delete
    6. i think this is working code..where you are getting problem or errors?

      Delete
    7. why did you use it as an abstract class?

      Delete
    8. give me ur mail id i will send u the screenshots, or reply on mine. rishabhcena1@gmail.com

      Delete
    9. does it tell the location via data pack or wifi?

      Delete
    10. email id is given on contact us page and every page:info@coders-hub.com
      and it will give location via data pack or wifi both.

      Delete
  5. Nice tutorial ... it working fine..mohsin

    ReplyDelete
  6. have you try with facebook sdk application.. if you have any sample kindly post the link ..

    ReplyDelete
    Replies
    1. check this link bro .. http://www.coders-hub.com/2014/07/how-to-add-facebook-sdk-in-android.html

      Delete
  7. Hi,
    i would like to insert a button to change Longitude and Latitude on the diisplay if i change my position, like this:


    updpo.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {

    }
    });

    but i'mnot sure on code to insert, can you give me some suggestions?
    thanks

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. hello sir,
      i didn't try this code...what is the output of this code? join me on hangout for fast conversion.
      Thanks

      Delete
  11. This comment has been removed by the author.

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. Hi, what do you thin about?

    package com.example.geosms;

    import android.os.Bundle;
    import android.app.Activity;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.Toast;
    import android.location.Criteria;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.content.Context;
    import android.widget.TextView;

    public class MainActivity extends Activity {
    LocationManager lm;
    TextView lt, ln;
    String provider;
    Location l;
    MyLocationListener mylistener;

    @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);


    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);
    mylistener = new MyLocationListener();

    if(l!=null)
    {
    mylistener.onLocationChanged(l);

    }
    else
    {
    ln.setText("No longitude");
    lt.setText("No latitude");
    }
    // i customized the update settings

    lm.requestLocationUpdates(provider, 200, 1, mylistener);

    }

    }

    private class MyLocationListener implements LocationListener {
    @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

    }
    }

    ReplyDelete
  16. any body tell me how to use this code to find location of another person throug emi numbr

    ReplyDelete
  17. app crashes as soon as i start it! please help! i just copy pasted your code!

    ReplyDelete
  18. Working fine my phone Samsung-GT S5282

    ReplyDelete
  19. This code doesn't work for me either! It just returns null and shows me no provider! I tured on my GPS, my data internet.. still it doesnt work!

    ReplyDelete
    Replies
    1. I don't know but here it is working fine and i am developing application using this code and showing me correct info with address. May i know your android mobile version. Mine is 4.1

      Delete
    2. I want to send my location by sms when my battery is low...
      plz help me i am new on android..

      Delete
    3. Read "Battery status from broadcast receiver" and "How to send large sms" post and merge both...you have done.

      Delete
  20. how to get geofencing in my application?

    i am using little fluffy location library,it is updating the location but it not created any geofencing.

    Is there any simple library to do geofencing ?,please help me,i am very confusing my mail id-hanumancse33@gmail.com

    ReplyDelete
    Replies
    1. No need to use any library just write your own code because android location code is not hard as i given in this post.

      Delete
  21. bro its giving a latitude and longitude properly...but while i add the code to find address it shows...your application has stopped unfortunately...

    logcat:

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nikilsanghvi.gps/com.example.nikilsanghvi.gps.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
    at android.app.ActivityThread.access$800(ActivityThread.java:144)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5221)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
    at com.example.nikilsanghvi.gps.MainActivity.onCreate(MainActivity.java:83)
    at android.app.Activity.performCreate(Activity.java:5933)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
                at android.app.ActivityThread.access$800(ActivityThread.java:144)
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
                at android.os.Handler.dispatchMessage(Handler.java:102)
                at android.os.Looper.loop(Looper.java:135)
                at android.app.ActivityThread.main(ActivityThread.java:5221)
                at java.lang.reflect.Method.invoke(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:372)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

    ReplyDelete
  22. i need apk for this program

    ReplyDelete
    Replies
    1. check here apk link. http://www.coders-hub.com/2015/02/advance-android-google-map-2-tutorial-with-example.html

      Delete
  23. hello sir ... i m looking for a code that can tracker location of other person can u help me .. plz

    ReplyDelete
  24. sir it will gives no provider in my emulator........

    ReplyDelete
  25. Sir i have followed all the steps but when i run the application on my device, it says "Unfortunately, application stopped working." Can you please explain the problem??

    ReplyDelete
  26. always run else condition NO PROVIDER how to fix and code working properly??



    ReplyDelete
  27. hii when i use the distance between two locations it gives me error in l1.setLatitude(location.getLatitude()); cant resolve location can you help please

    ReplyDelete
  28. i have a erreur in l=lm.getLastKnownLocation(provider); !!!
    any solutions??

    ReplyDelete
  29. i have a erreur in l=lm.getLastKnownLocation(provider); !!!
    any solutions??

    ReplyDelete
  30. This comment has been removed by a blog administrator.

    ReplyDelete
  31. based on your tutorial i tried to use it as per my requirement but i faced following problem:
    before stating the problem i'll explain what i am trying to to do.
    After getting the latitude and longitude of the current position i want to use it directly on the map i'e display current location of user on the map.
    But PROBLEM that i encountered is it gave the current location i,e latutude and longitude of user at first try but when i turned of and turned on the gprs and it gave the null value. code is as follows:

    public class CurrentLocation extends FragmentActivity implements OnMapReadyCallback, com.google.android.gms.location.LocationListener {

    private GoogleMap mMap;
    LocationManager lm;
    String provider;
    Location l;

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

    if (Utility.checkNetworkAvailability(this)) {
    try {
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
    .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);


    } catch (Exception e) {
    e.printStackTrace();
    }
    } else {
    Toast.makeText(this, "No Internet!! Please connect to the internet", Toast.LENGTH_SHORT).show();
    }


    lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    Criteria c = new Criteria();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    return;
    }
    l = lm.getLastKnownLocation(provider);
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {

    mMap = googleMap;



    if(l != null)
    {

    double lng=l.getLongitude();
    double lat=l.getLatitude();
    LatLng curentLocation = new LatLng(lat,lng);
    MarkerOptions mo=new MarkerOptions().position(curentLocation).title("You are here!").snippet("" + curentLocation).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); //change color as your need
    mMap.addMarker(mo);
    }
    else
    {

    Toast.makeText(this, "Please! make sure you have turn on your GPRS or LOCATION of the device", Toast.LENGTH_SHORT).show();
    }

    }

    @Override
    public void onLocationChanged(Location location) {


    }


    }

    ReplyDelete
  32. if anybody have any project code send me and you get any knowledge share with me (naveen628361@gmail.com)thank you

    ReplyDelete
  33. This comment has been removed by the author.

    ReplyDelete
  34. hey will you help me for inner navigation system of any building or any other structure???

    ReplyDelete
  35. I will master android dev from THIS AMAZING SITE! full of kisses from me ^_^

    ReplyDelete
  36. Hi Mohsin ... thanks for your code and i want to gps Tracker as we use in uber to see where the location car and my location.

    ReplyDelete
  37. write this above but it give force stop

    ReplyDelete

Back to Top