Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current lat long android

I want to get the Location object on Button press. I know the LocationListener callbacks, however they execute only after a particular time or distance. I want to get Location instantaneously. Are there any methods to do so.

like image 322
user3921255 Avatar asked Aug 18 '26 21:08

user3921255


2 Answers

public class GPSHelper {

    private Context context;
    // flag for GPS Status
    private boolean isGPSEnabled = false;
    // flag for network status
    private boolean isNetworkEnabled = false;
    private LocationManager locationManager;
    private Location location;
    private double latitude;
    private double longitude;

    public GPSHelper(Context context) {
        this.context = context;

        locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);

    }   public void getMyLocation() {
        List<String> providers = locationManager.getProviders(true);

        Location l = null;
        for (int i = 0; i < providers.size(); i++) {
            l = locationManager.getLastKnownLocation(providers.get(i));
            if (l != null)
                break;
        }
        if (l != null) {
            latitude = l.getLatitude();
            longitude = l.getLongitude();
        }
    }

    public boolean isGPSenabled() {
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        return (isGPSEnabled || isNetworkEnabled);
    }

    /**
     * Function to get latitude
     */
    public double getLatitude() {
        return latitude;
    }

    /**
     * Function to get longitude
     */
    public double getLongitude() {
        return longitude;
    }
like image 67
John Avatar answered Aug 20 '26 10:08

John


You are welcome to call getLastKnownLocation() on LocationManager to retrieve the last known location for your requested location provider. However:

  • that location may be old
  • that location may be null

Hence, your code will need to be able to cope with both of those scenarios.

like image 21
CommonsWare Avatar answered Aug 20 '26 10:08

CommonsWare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!