find current location latitude and longitude in Android [duplicate]
Asked Answered
D

4

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?

Discourse answered 12/2, 2010 at 8:58 Comment(2)
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.Epicardium
You will not get GPS from your emulator .Try on real device.Scutt
M
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.

Musca answered 27/11, 2010 at 10:42 Comment(1)
If you will use this code, you will get answer.... but no acceptance.... shame.Heger
A
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.

Attalanta answered 12/2, 2010 at 12:14 Comment(5)
"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 ?Quake
@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.Attalanta
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 maybeQuake
@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.Attalanta
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 today, it'll save you some typing :)Quake
G
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();
}
Guillen answered 25/7, 2013 at 12:26 Comment(0)
M
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.

Mathew answered 9/8, 2012 at 14:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.