1

I want to display latitude and longitude my current location.. For this rather than searching in Google, i searched in SO.

I just want to display my current location latitude and longitude.

See my code below :

public class LocationGetter extends Activity {

@Override

public void onCreate(Bundle savedInstanceState)
{

super.onCreate(savedInstanceState);

TextView tv = new TextView(this);

LocationManager mlocManager = 
                (LocationManager) getSystemService(Context.LOCATION_SERVICE);

LocationListener mlocListener = new LocationManagerHelper();

mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 100,mlocListener);

if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        tv.append("Latitude:- " + LocationManagerHelper.getLatitude()
                + '\n');
        tv.append("Longitude:- " + LocationManagerHelper.getLongitude()
                + '\n');

        Log.i("MyLocation1",Double.toString(LocationManagerHelper.getLatitude())+" "+Double.toString(LocationManagerHelper.getLongitude()));

} else {
    tv.setText("GPS is not turned on...");
}

/** set the content view to the TextView */
setContentView(tv);

}

/* Class My Location Listener */

public static class LocationManagerHelper implements LocationListener {

    private static double latitude;
    private static double longitude;

    @Override
    public void onLocationChanged(Location loc) {
        latitude = loc.getLatitude();
        longitude = loc.getLongitude();
        Log.i("MyLocation",Double.toString(latitude)+" "+Double.toString(longitude));
    }

    @Override
    public void onProviderDisabled(String provider) { }

    @Override
    public void onProviderEnabled(String provider) { }

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

    }

    public static double getLatitude() {
        return latitude;
    }

    public static double getLongitude() {
        return longitude;
    }

}

} 

I have also added permission in manifest file :

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

See the output i am getting :

enter image description here

Where i am going wrong ? I dont understand, its a simple code and why its not working ?

Kartik Domadiya
  • 29,868
  • 19
  • 93
  • 104

5 Answers5

2

I just verified your code and it works with these changes, you just need to move the tv.append() calls to the onLocationChanged() method as that is called each time, if you don't use that for the CallBack, then u will get the first set values only and it's only executed once.

        public void onLocationChanged(Location loc) {
            latitude = loc.getLatitude();
            longitude = loc.getLongitude();
            Log.i("MyLocation",Double.toString(latitude)+" "+Double.toString(longitude));
            tv.append("Latitude:- " + LocationManagerHelper.getLatitude()
                    + '\n');
            tv.append("Longitude:- " + LocationManagerHelper.getLongitude()
                    + '\n');

            Log.i("MyLocation1",Double.toString(LocationManagerHelper.getLatitude())+" "+Double.toString(LocationManagerHelper.getLongitude()));

        }

and I have used these permissions in AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />    
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />    
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />    

You can look at these and filter out the ones you won't be interested in. I have used a downloaded .gpx file from here

I've tested it on Android 2.2 though, Location Updates working

Swaroop
  • 908
  • 1
  • 12
  • 25
  • Let me try this. Will tell you after testing it. Should i test in phone ? – Kartik Domadiya Apr 07 '11 at 10:43
  • When i moved all tv.append calls to onLocationChanged, it didn display me anything. onLocationChanged is not getting called. – Kartik Domadiya Apr 07 '11 at 11:09
  • You should be sending location updates too for the onLocationChanged to get called from the DDMS Emulator Control panel. You can use Emulator or Device (Enable Real GPS /Mock Updates) for this. I tested on Android 2.2 emulator though. – Swaroop Apr 07 '11 at 12:07
2

You got location in Onlocationchanged

 public void onLocationChanged(Location loc) {
    latitude = loc.getLatitude();
    longitude = loc.getLongitude();
    Log.i("MyLocation",Double.toString(latitude)+" "+Double.toString(longitude));
  }

so the lattitude and longitude will be displayed only when the change from the current location.for checking you give some latitude and longitude and send from your emulator control in DDMS and after that you run your program.Sure it will show the location.

enter image description here

adithi
  • 973
  • 3
  • 11
  • 19
  • How can i feed latitude and longitude from DDMS ? – Kartik Domadiya Apr 07 '11 at 11:12
  • When you click the DDMS,ther will Emulator control window.If not there then you oprn it from window->show view.In that you will find Location controls.click the Manual tab and enter the latitude and longitude and click send and then run your program – adithi Apr 07 '11 at 11:58
  • Yes, thanks,Its done now..sending from emulator control is ok.. will i get my current location if i install this app in my mobile phone ? – Kartik Domadiya Apr 07 '11 at 12:00
  • Thanks for the reply..Giving an upvote for teaching me how to use DDMS..thanks – Kartik Domadiya Apr 07 '11 at 12:14
1

If you run this program in device then it show latitude and longitude 0.0 until we change our position.You must move at least 10 meter from your current position to see the output. Because without change current position onLocationChange() method does not fire and output will be 0.0

Himanshu
  • 31,810
  • 31
  • 111
  • 133
Sajal Saha
  • 169
  • 2
  • 12
0

Use the LocationManager.

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();

The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.

private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        longitude = location.getLongitude();
        latitude = location.getLatitude();
    }
}

lm.requestLocationUpdates(LocationManager.GPS, 2000, 10, locationListener);

You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.

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

You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.

Uday
  • 5,933
  • 9
  • 44
  • 76
0

I think with the emulator you can't get the GPS co-ordinates. If you are working with the mobile, try the GPS outside of your building. sometimes you won't get the GPS co-ordinates inside the building. If that time also you failed, then i will post the code that we got succeeded.

The below code just now i have tested and its works for me..

 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.Toast;

 public class GetGPS extends Activity {

String GPSPROVIDER = LocationManager.GPS_PROVIDER;
private  static final long MIN_GEOGRAPHIC_POOLING_TIME_PERIOD = 10000;
private  static final float MIN_GEOGRAPHIC_POOLING_DISTANCE = (float)5.0;

public LocationManager gpsLocationManager;

static Context context = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    context = this;

    /*Get a listener for GPS*/
    LocationListener gpsLocationListener = null;

    gpsLocationListener = new GpsLocationListener(this);

    /*Start Location Service for GPS*/
    gpsLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    /*Register GPS listener with Location Manager*/
    gpsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
            MIN_GEOGRAPHIC_POOLING_TIME_PERIOD,
            MIN_GEOGRAPHIC_POOLING_DISTANCE, gpsLocationListener);

    boolean isavailable = gpsLocationManager.isProviderEnabled(GPSPROVIDER);

    if(isavailable) {

        Location loc = gpsLocationManager.getLastKnownLocation("gps");

        if(loc != null) {
            double latitude = loc.getLatitude();
            double longitude = loc.getLongitude();

            Toast.makeText(GetGPS.this,"Longitude is  "+longitude + "   Latitude is   "+latitude, Toast.LENGTH_LONG).show();

        }
    }

}

public static class GpsLocationListener implements LocationListener {


    public GpsLocationListener(Context context){

    }

    public void onLocationChanged(Location loc) {

        if (loc != null) {

            double latitude = loc.getLatitude();
            double longitude = loc.getLongitude();

            Toast.makeText(context,"Longitude is  "+longitude + "   Latitude is   "+latitude, Toast.LENGTH_LONG).show();

        }

    }//End of onLocationChanged Method

    @Override
    public void onProviderDisabled(String provider) {

    }//End of onProviderDisabled Method

    @Override
    public void onProviderEnabled(String provider) {

    }//End of onProviderEnabled Method

    @Override
    public void onStatusChanged(String provider, int status,
            Bundle extras) {


    }//End of onStatusChanged Method

}//End of GpsLocationListener class
}

I tested this by moving the device from one place to another...

I hope it will helps..

Kartik Domadiya
  • 29,868
  • 19
  • 93
  • 104
uday
  • 1,625
  • 3
  • 14
  • 16
  • See the post here. about testing GPS app in emulator http://www.firstdroid.com/2010/04/29/android-development-using-gps-to-get-current-location-2/ – Kartik Domadiya Apr 07 '11 at 10:00
  • U can go though the above code that i have posted.. Its working for me.In that there is a listener which listens for every 10 sec to get the GPS co-ordinates. – uday Apr 07 '11 at 12:07
  • have you tried for Triangulation http://stackoverflow.com/questions/3145089/what-is-the-simplest-and-most-robust-way-to-get-the-users-current-location-in-an/3145655#3145655 .. can you help me in implementing this ?..just give an idea related to this >? – Kartik Domadiya Apr 07 '11 at 12:17