Animesh Jena
Animesh Jena

Reputation: 1551

Latitude and longitude values are giving null values , 0.0

In my app,I am trying to get the user's current latitude and longitude value while logging in itself.But the problem is some times I am getting null values and some times even 0.0 as values.I even went through a similar post on stack overflow but could not get the solution.please help. here is my GPSTracker.java service class

    public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

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

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS settings");
        alertDialog.setCancelable(false);

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location)
    {

    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}

Upvotes: 0

Views: 3370

Answers (3)

AlexWien
AlexWien

Reputation: 28727

There are various reasons to get a null or (0.0, 0.) coordinate. Altough there exists a valid (0.0, 0.0) coordinate, in practise it is never a valid one, or designed that way to express invalid locations.
So you can safely ignore all null and (0.0, 0.0) locations.

Read the API how to determine whether a delivered location is valid! At iOS it is only valid if horicontalAccuracy is >= 0.
From Andorid Location docu:

"All locations generated by the LocationManager are guaranteed to have a valid latitude, longitude, and timestamp (both UTC time and elapsed real-time since boot), all other parameters are optional. "

So the situation you describe should not happen. Therefore just ignore that (0,0) locations!

Further rework your app: first after initialising you should get the last known location, then use OnLocationChanged() to get further location updates.

Upvotes: 1

Ibukun Muyide
Ibukun Muyide

Reputation: 1298

use this method

public class DashActivity extends ActionBarActivity implements
    GooglePlayServicesClient.ConnectionCallbacks,
    GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {

LatLng secondToLastLocation;
LocationClient mLocationClient;
double latitudeValue, longitudeValue;

// Milliseconds per second
private static final int MILLISECONDS_PER_SECOND = 1000;
// Update frequency in seconds
public static final int UPDATE_INTERVAL_IN_SECONDS = 5;
// Update frequency in milliseconds
private static final long UPDATE_INTERVAL =  MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;
// The fastest update frequency, in seconds
private static final int FASTEST_INTERVAL_IN_SECONDS = 1;
// A fast frequency ceiling in milliseconds
private static final long FASTEST_INTERVAL =  MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dash);
    mLocationClient = new LocationClient(this, this, this);
    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create();
    // Use high accuracy
    mLocationRequest.setPriority( LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Set the update interval to 5 seconds
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    // Set the fastest update interval to 1 second
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);

}


public double getLongitude() {
    return mLocationClient.getLastLocation().getLongitude();
}

public double getLatitude() {
    return mLocationClient.getLastLocation().getLatitude();
}


@Override
public void onConnectionFailed(ConnectionResult arg0) {
    Toast.makeText(this, "Connetion fail, Unable to detect location", Toast.LENGTH_LONG).show();
}

@Override
public void onConnected(Bundle arg0) {
    Toast.makeText(this, "Connected, dectecting location", Toast.LENGTH_LONG).show();
    mLocationClient.requestLocationUpdates(mLocationRequest, this);
    sendToServer();
}

@Override
public void onDisconnected() {
    Toast.makeText(this, "You are disconnected", Toast.LENGTH_LONG).show();
    timer.interrupt();
}

@Override
protected void onStop() {
    // Disconnecting the client invalidates it.
    mLocationClient.disconnect();
    super.onStop();
}


@Override
protected void onStart() {
    super.onStart();
    mLocationClient.connect();
}


@Override
public void onLocationChanged(Location location) {
    // assign some stuff here when location chaneges
}   

}

get the last Know location first from the method getLongitude() and getLongitude() then when ever there isa change in location you can get the know from from the onLocationChange() the rate at which location event detect changes in written in the first set of lines. you need to get the last saved location from the devices first, it works offline

Upvotes: 0

Ashish Agrawal
Ashish Agrawal

Reputation: 1977

You will get current location in OnLocationChanged() method

@Override
public void onLocationChanged(Location location)
{
      double lat = location.getLatitude();
      double lon = location.getLongitude();
}

Upvotes: 0

Related Questions