6

I want to find latitude and longitude of my current location in an android application. I just need it when I am stable with my phone.

My code is:

LocationManager locationManager;
    locationManager = (LocationManager)getSystemService
    (Context.LOCATION_SERVICE);
    Location location = locationManager.getLastKnownLocation
    (LocationManager.GPS_PROVIDER);


    locationManager.requestLocationUpdates(                
             LocationManager.GPS_PROVIDER,0,0,(LocationListener) this);
    updateWithNewLocation(location);
    }

    private void updateWithNewLocation(Location location) {
    TextView myLocationText = (TextView)findViewById(R.id.myLocationText);

    String latLongString;

    if (location != null) {
    double lat = location.getLatitude();
    double lng = location.getLongitude();
    latLongString = "Lat:" + lat + "\nLong:" + lng;
    } else {
    latLongString = "No location found";
    }

    myLocationText.setText("Your Current Position is:\n" +
    latLongString);
    }

After running it on emulator i always find "no location found". Why this is so?

Cœur
  • 37,241
  • 25
  • 195
  • 267
rashmi
  • 167
  • 1
  • 1
  • 6
  • Can you show us your code so we can see why it doesn't work? This question has been asked already quite a few times on StackOverflow. Do a search and you might already find an answer to your problem. – Maurits Rijk Feb 12 '10 at 09:10
  • You will not get GPS from your emulator .Try on real device. – Dhruvisha May 04 '12 at 09:19

4 Answers4

17
public class GPSmap extends Activity {

    GeoPoint geoPoint;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LocationManager locManager;
        setContentView(R.layout.main);
        locManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,
            500.0f, locationListener);
        Location location = locManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
        }
    }

    private void updateWithNewLocation(Location location) {
        TextView myLocationText = (TextView) findViewById(R.id.text);
        String latLongString = "";
        if (location != null) {
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            latLongString = "Lat:" + lat + "\nLong:" + lng;
        } else {
            latLongString = "No location found";
        }
        myLocationText.setText("Your Current Position is:\n" + latLongString);
    }

    private final LocationListener locationListener = new LocationListener() {

        public void onLocationChanged(Location location) {
            updateWithNewLocation(location);
        }

        public void onProviderDisabled(String provider) {
            updateWithNewLocation(null);
        }

        public void onProviderEnabled(String provider) {}

        public void onStatusChanged(String provider,int status,Bundle extras){}
    };
}

If you will use this code, you will get answer.

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
JohnNick
  • 1,756
  • 5
  • 21
  • 27
4

The GPS radio is not kept on all of the time, as it seriously drains the battery. At the point when you are calling getLastKnownLocation(), the radio is probably off.

You need to do your requestLocationUpdates() first, then wait for a fix to be supplied to your LocationListener. Any time after that (until you removeUpdates()), getLastKnownLocation() should return a non-null value.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • "Any time ... until you `removeUpdates()`, `getLastKnownLocation()` should return a non-null value" - so if one calls `removeUpdates()` the location returned by `getLastKnownLocation()` will be null afterwards ? Does it not persist, say, until a reboot ? Is this documented somewhere ? – Mr_and_Mrs_D Jul 18 '13 at 15:13
  • @Mr_and_Mrs_D: "so if one calls removeUpdates() the location returned by getLastKnownLocation() will be null afterwards ? " -- it is more that there is no guarantee of how long you will continue to get a non-`null` value. "Is this documented somewhere ?" -- no, which is the point. Only while you *know* the device is actively seeking location data can you feel confident that `getLastKnownLocation()` has a chance of returning non-`null` data. Once *you* are no longer requesting location fixes, all bets are off. – CommonsWare Jul 18 '13 at 15:19
  • a-ha - so even if the providers are enabled `getLastKnownLocation()` will start returning null after some point (removed in time from last request for location updates by any app I guess) - any links discussing that ? one would assume once a last location is obtained this would remain available till reboot - or till (all ? relevant ?) provider(s) _disabled_ maybe – Mr_and_Mrs_D Jul 18 '13 at 15:24
  • @Mr_and_Mrs_D: "getLastKnownLocation() will start returning null after some point" -- again, it is more that the behavior is undocumented and therefore intrinsically unreliable. "one would assume once a last location is obtained this would remain available till reboot - or till (all ? relevant ?) provider(s) disabled maybe" -- I certainly would not assume that. – CommonsWare Jul 18 '13 at 15:31
  • thank you - so in brief the javadoc should read "call this method only after (you or some other app has issued) a call to `requestLocationUpdates()`" - btw I discovered [this](http://stackapps.com/questions/2051/reply-links-on-comments) today, it'll save you some typing :) – Mr_and_Mrs_D Jul 18 '13 at 15:41
2

I have search lots of tutorial but found this best one:

Using Criteria and BestProvider

    /** PROCESS for Get Longitude and Latitude **/
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.d("msg", "GPS:"+isGPSEnabled);

// check if GPS enabled     
if(isGPSEnabled){
    /*
    longitude = 70.80079728674089;
    latitude =  22.29090332494221;
     */
     Criteria criteria = new Criteria();
     String provider = locationManager.getBestProvider(criteria, false);
     Location location = locationManager.getLastKnownLocation(provider);

    //new LoadPlaces().execute();
    //Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if(location != null)
    {
        longitude = location.getLongitude();
        latitude = location.getLatitude();
        Log.d("msg", "first lat long : "+latitude +" "+ longitude);
        //new LoadPlaces().execute();
    }else
    {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {

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

            }

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

            }

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

            }

            @Override
            public void onLocationChanged(Location location) {
                // TODO Auto-generated method stub
                longitude = location.getLongitude();
                latitude = location.getLatitude();
                Log.d("msg", "changed lat long : "+latitude +" "+ longitude);
            }
        });
    }

}
else
{
    showAlertforGPS();
}
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
1

The emulator by default, may not have any location associated. So it is not giving any.

To send a location, go to DDMS perspective in Eclipse, and enter the latitude and longitude and click Send. Then you will be able to see that in your application.

Let me know if you still have any issues.

nithinreddy
  • 6,167
  • 4
  • 38
  • 44