views:

72

answers:

2

Hi,

I need the correct way of getting latitude and longitude in android programatically. I viewed different sites and forums but still i could'nt get the correct one. The program should support for all the android versions.I use wifi to get my device connected to net.

A: 

Below implementation creates a locationlistener that records the updated values as strings for convenience which can be easily extracted. By using the LocationManager you abstract the underlying method (GPS/assissted-GPS, wifi, cell-tower) to retrieve the location.

Initialize first:

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
final myLocationListner ll = new myLocationListner();

LocationListener:

public class myLocationListner implements LocationListener {

        public static String lattitude = "";
    public static String longitude = "";

    @Override
    public void onLocationChanged(Location loc) {
        String temp_lattitude = String.valueOf(loc.getLatitude());
        String temp_longitude = String.valueOf(loc.getLongitude());

        if(!("").equals(temp_lattitude))lattitude = temp_lattitude;
        if(!("").equals(temp_longitude))longitude = temp_longitude;
    }

    @Override
    public void onProviderDisabled(String arg0) {

    }

    @Override
    public void onProviderEnabled(String arg0) {

    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {

    }

}
Sameer Segal
Don't forget to register that `LocationListener` using `requestLocationUpdates()` and remove it later using `removeUpdates()`. Here is a sample project: http://github.com/commonsguy/cw-android/tree/master/Service/WeatherPlus/
CommonsWare
Thanks for your suggestions Sameer.Hope to follow it
Ganesh
A: 

Dont Worry, After scratching my head over few days, I got code working in over a few lines to get longitude and latitude values... I think this will help things go better, Thanks for your suggestions!!!!

private double[] getGPS() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
List<String> providers = lm.getProviders(true);

/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location l = null;

for (int i=providers.length();i>=0;i--) {
    l = lm.getLastKnownLocation(providers.get(i));
    if (l != null) break;
}

double[] gps = new double[2];
if (l != null) {
    gps[0] = l.getLatitude();
    gps[1] = l.getLongitude();
}
return gps;}
Ganesh