Android GPS with LocationManager to get current location – Example

September 27, 2012
By

In this article, we will create an Android application which displays latitude and longitude of the current location using GPS and Android’s LocationManager API.



An extension to this application is available in the article titled “Showing current location in Google Maps with GPS and LocationManager in Android“, where current location is displayed in Google Map.

This application is developed in Eclipse ( 4.2.0 ) with ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3 ) .



1. Create a new Android application project namely “LocationFromGPS”

Create a new Android application project

Figure 1 : Create a new Android application project


2. Design application launcher icon

Design application launcher icon

Figure 2 : Design application launcher icon


3. Create a blank activity to define the class MainActivity

Create a blank activity

Figure 3 : Create a blank activity


4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


5. Delete Android’s backward compatibility support library from the project, if exists

By default Eclipse ( 4.2.0) adds Android Support Library to  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.


6. Update the file res/values/strings.xml


<resources>
    <string name="app_name">LocationFromGPS</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Location From GPS</string>
    <string name="str_tv_location">Current Location</string>
</resources>


7. Update the file res/layout/activity_main.xml


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

    <TextView
        android:id="@+id/tv_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="@string/str_tv_location"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tv_longitude"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_location"
        android:layout_centerHorizontal="true" />

    <TextView
        android:id="@+id/tv_latitude"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_longitude"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>


8. Update the file res/values/styles.xml

<resources>
    <style name="AppTheme" parent="android:Theme" />
</resources>

9. Update the file res/values-v11/styles.xml

<resources>
    <style name="AppTheme" parent="android:Theme.Holo" />
</resources>

10. Update the file res/values-v14/styles.xml


<resources>
    <style name="AppTheme" parent="android:Theme.Holo" />
</resources>


11. Update the class MainActivity in the file src/in/wptrafficanalyzer/locationfromgps/MainActivitiy.java


package in.wptrafficanalyzer.locationfromgps;

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

public class MainActivity extends Activity implements LocationListener{

    LocationManager locationManager ;
    String provider;

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

        // Getting LocationManager object
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

        // Creating an empty criteria object
        Criteria criteria = new Criteria();

        // Getting the name of the provider that meets the criteria
        provider = locationManager.getBestProvider(criteria, false);

        if(provider!=null && !provider.equals("")){

            // Get the location from the given provider
            Location location = locationManager.getLastKnownLocation(provider);

            locationManager.requestLocationUpdates(provider, 20000, 1, this);

            if(location!=null)
                onLocationChanged(location);
            else
                Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();

        }else{
            Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public void onLocationChanged(Location location) {
        // Getting reference to TextView tv_longitude
        TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude);

        // Getting reference to TextView tv_latitude
        TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude);

        // Setting Current Longitude
        tvLongitude.setText("Longitude:" + location.getLongitude());

        // Setting Current Latitude
        tvLatitude.setText("Latitude:" + location.getLatitude() );
    }

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

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

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
}


12. Update the file AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.locationfromgps"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="15" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

13. Enable GPS in the emulator or device from Settings

Enabling GPS in Android 1.6 (Emulator)

Figure 5 : Enabling GPS in Android 1.6 (Emulator)


14. Set Longitude and Latitude of the location in Eclipse -> DDMS ( Perspective ) to run  this application in the emulator

Setting Longitude and Latitude in Eclipse ->DDMS Perspective

Figure 6 : Setting Longitude and Latitude in Eclipse ->DDMS Perspective


15. Screenshot of the application

Showing Longitude and Latitude of the current location

Figure 7 : Showing Longitude and Latitude of the current location


16. Download Source Code



17. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , ,

43 Responses to Android GPS with LocationManager to get current location – Example

  1. subash on February 5, 2013 at 9:36 pm

    I am getting multiple markers and overide error in mainactivity.java
    please reply me soon

    • george on February 5, 2013 at 9:49 pm

      Which method is showing override error?

      • gaurav bisht on June 1, 2015 at 3:06 pm

        public void on location changed method then got error..

  2. siri on February 21, 2013 at 12:55 pm

    how to increase these current location values upto 10 showing in a list

    • george on February 22, 2013 at 6:25 am

      Sorry, i am not getting you.

  3. siri on February 21, 2013 at 12:57 pm

    it was urgent

  4. gowtham on February 26, 2013 at 3:08 pm

    Wow It works thanx george

  5. Christopher on March 19, 2013 at 6:23 pm

    when i load it in a blackberry 10 device it cannot access gps and return my location

  6. marzhan on April 7, 2013 at 8:41 pm

    Thank you very much!!! It works excellently!!! It is the only project that works on my phone!!!!!!!!!!))))))))))))

  7. Aman Prajapati on May 15, 2013 at 6:45 pm

    Can this latitude and longitude change with movement of device?

  8. Aman Prajapati on May 15, 2013 at 6:52 pm

    Can we change the value of latitude and longitude with this code where we are roaming?

  9. Aniket Mane on June 10, 2013 at 3:48 pm

    Thanksssss buddy

  10. Randika on July 11, 2013 at 2:59 pm

    Thanks for the tutorial, I’m gonna follow the whole series!
    Cheers!!!

  11. ramya on July 28, 2013 at 10:44 am

    please say me, is it necessary to send values from the emulator control

  12. chals on August 20, 2013 at 5:04 pm

    Can it be possible to save it on some server from where other can get it as real time navigation

  13. Deepak mehta on September 24, 2013 at 3:31 pm

    please help its showing me my old location which is last updated previously on my phone too far from my current location..

  14. ali on November 10, 2013 at 6:19 pm

    how can i use latitude and longitude values or pass lat/long values in broadcast receiver class. It would be gr8 if u help me.

  15. vs on December 16, 2013 at 2:18 pm

    Hi George,
    Could you help GPS app creation by use of JNI. My hardware uses UART GPS, for that wrote c application, works fine and gives correct latitude, longitude, UTC time, Position and Data validation.
    I have to create jni for GPS app can you help me how it is possible.

    Thanks,
    vs

  16. juliya on February 22, 2014 at 12:17 pm

    hi,
    please help me to create a location based application.The app is for changing the profile(silent/normal) based on the location.
    plz help me..

  17. bkta on March 14, 2014 at 6:55 pm

    how can i get the city name ?

  18. mohammed on April 10, 2014 at 2:04 pm

    Dear
    Mr . George Mathew
    Please Help
    Can I get a mobile location by using IMEI number

    Thanks,

  19. sudhakar on August 19, 2014 at 10:53 am

    hi sir i got the lat and long current thk u for tutorial.
    I am doing a app in that i need to show the current location throught google map and to point some places in it ,can u help me. i didn’t got.

  20. سارا on August 31, 2014 at 3:04 am

    I have a question? does it work just outdoor? it doesn’t work in home?

  21. sayali on September 16, 2014 at 10:24 am

    i want to a code for getting current location automatically in gps and displaying destination with total distance. n should display the shortest distance

  22. balaji on October 15, 2014 at 12:32 pm

    hi after getting lat and long value,how to hide gps traking icon ?

  23. pragadees on November 20, 2014 at 11:15 am

    Hi George Mathew,
    Please Tell me How to get a friends location latitude and longitude

  24. Anand on November 27, 2014 at 3:36 pm

    Hi George thanks a lot for this tutorial

  25. manvi on March 18, 2015 at 5:48 pm

    i want to track current location of other ppl that are on my contact list..
    how to do it .. plz rply ???

    • yogesh on April 3, 2015 at 4:09 pm

      hello manvi
      if get such type of code then please also forword on my email :- meyogeshvalecha@gmail.com

    • James Lanel on October 27, 2015 at 11:27 am

      Even me, i would like to know how to track current location of other ppl. Plz let me know if u guys got the code.

  26. Sagar raiyani on March 31, 2015 at 5:01 pm

    Hello George Mathew,

    I have more than 10 location with lat long but how to compare nearest location with my location, Please help me…

  27. Prajakta Gitte on April 4, 2015 at 11:36 am

    Hi,
    I have resolved all problems.your code is very helpful for me,thnx a lot.

  28. Pushpender on May 19, 2015 at 2:01 pm

    sir, how can i store these credentials into database or into a text file?

  29. SelvaGanesh on May 23, 2015 at 7:05 pm

    Hai Sir I need to Know How to Save the Latitude and longitude values in sqlite in android
    plz help me as soon as possible

  30. ravi on May 26, 2015 at 11:36 pm

    hi i m ravi and i want to creatr a gps system to get location

  31. Vanitha on June 2, 2015 at 10:41 am

    hi!! your tutorial is very helpful for me. i need some clarification the value of longitude and latitude is always retrieving false value.

  32. Dan Blum on June 29, 2015 at 12:56 am

    This application worked great in Android Studio, with one exception: the menu.activity_main, I renamed to the default ‘menu_main.

  33. amar on September 30, 2015 at 1:17 pm

    How to display google map on android application?

  34. afiqah on December 2, 2015 at 6:18 am

    would you mind to help me developing sms location where we can send the location viz sms?

  35. Merlin on January 28, 2016 at 2:45 pm

    Actually GPS positioning works fine, but NETWORK positioning doesn’t. When I have turned devices GPS on coordinates keep changing while i am moving, but doesn’t happen same when I have turn it off and relay on the NETWORK_PROVIDER..!!!

  36. lucy on March 5, 2016 at 8:17 pm

    hai im working on project for finding alternative routes for same destination could you please help me with this project i would like to know if i can get a source code regarding the project

  37. Ali on April 1, 2016 at 12:34 pm

    hy dear I copy your code as it but not receive any value in TxtView

  38. Shefali on July 12, 2016 at 10:24 am

    I want to save the location and display it in application later.

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner