How to get location data (with code samples!)

Discussion in 'Android Hacks and Help' started by MrGlass, Dec 17, 2009.

  1. MrGlass
    Offline

    MrGlass New Member

    Joined:
    Dec 6, 2009
    Messages:
    12
    Likes Received:
    0
    Trophy Points:
    0
    OK, I searched long and hard for a guide to this and couldn't find one anywhere, so here goes:

    in brief, there are essentially 3 important parts to getting location data. You need to

    1. Request location permissions in the manifest
    2. Grab the location service
    3. Start a location listener
    the location listener seems to be the part most people miss. It watches for new location data and performs an action when the device location is updated.

    Below is a very basic sample that will display the devices latitude and longitude. If you run this in an emulator, make sure you simulate the gps data. There is plenty of documentation of doing that, but I found it easiest to use the location control (found in the emulator control panel in eclipse DDMS view) to pass a lat/long value.

    If you want help with this, feel free to reply below or contact me on twitter (@misterglass)

    Code:
    //hello.java
    package mrglass.androidapp1;
    
    import android.app.Activity;
    import android.content.Context;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.widget.TextView;
    
    public class hello extends Activity {
    
        private TextView mytext;
        private LocationManager locmgr = null;
        
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            
            mytext = (TextView) findViewById(R.id.mytext);
            
            //grab the location manager service
            locmgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
      
            mytext.setText("waiting for location");
        }
        
        //Start a location listener
        LocationListener onLocationChange=new LocationListener() {
            public void onLocationChanged(Location loc) {
                //sets and displays the lat/long when a location is provided
                String latlong = "Lat: " + loc.getLatitude() + " Long: " + loc.getLongitude();   
                mytext.setText(latlong);
            }
             
            public void onProviderDisabled(String provider) {
            // required for interface, not used
            }
             
            public void onProviderEnabled(String provider) {
            // required for interface, not used
            }
             
            public void onStatusChanged(String provider, int status,
            Bundle extras) {
            // required for interface, not used
            }
        };
        
        //pauses listener while app is inactive
        @Override
        public void onPause() {
            super.onPause();
            locmgr.removeUpdates(onLocationChange);
        }
        
        //reactivates listener when app is resumed
        @Override
        public void onResume() {
            super.onResume();
            locmgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,10000.0f,onLocationChange);
        }
    }
    
    
    //main.xml
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
    <TextView
        android:id="@+id/mytext"  
        android:textSize="15pt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    
        
    </LinearLayout>
    
    
    //manifest
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="mrglass.androidapp1"
          android:versionCode="2"
          android:versionName="0.2">
          
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        
        <application android:icon="@drawable/icon" android:label="@string/app_name">
            <activity android:name=".hello"
                      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>
        <uses-sdk android:minSdkVersion="6" />
    </manifest> 
    
  2. silverx10
    Offline

    silverx10 New Member

    Joined:
    Nov 22, 2009
    Messages:
    199
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    Virginia Beach, VA
    Wow.

    Now, I know you said you couldn't find any snippets out there for this, but... did you do this from what you've learned, or did you scavenge the net for snippets of code to splice into each other to make this?

    If the latter, then kudos. Very much so.
  3. MrGlass
    Offline

    MrGlass New Member

    Joined:
    Dec 6, 2009
    Messages:
    12
    Likes Received:
    0
    Trophy Points:
    0
  4. silverx10
    Offline

    silverx10 New Member

    Joined:
    Nov 22, 2009
    Messages:
    199
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    Virginia Beach, VA
    Outstanding.

    I think that I'm finally starting to get the hang of the code, myself. 'specially them thar overrides and such. Problem now is getting to know the Android API library to an intimate enough level that I know which to import, and which to overlook.
Search tags for this page

android get location

,

android get location example

,
android getlocation
,
android location example
,
android location sample code
,
android locationlistener example
,
android onlocationchanged example
,

locationlistener example

,
onlocationchanged android example
,
onlocationchanged example