user1061793
user1061793

Reputation: 1077

How to get my current longitude and latitude from my Android device

I am using this code. but getting null in longitude and latitude.

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

Upvotes: 1

Views: 759

Answers (5)

Unnati Patadia
Unnati Patadia

Reputation: 732

implementation 'com.google.android.gms:play-services-location:11.6.0'

public class LocationExample Eextends AppCompatActivity implements LocationListener {

double latitude, longitude;
LocationManager locationManager;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        getLocation()
}

void getLocation() {
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (isNetworkEnabled) {
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //GlobalToast.toastMessage(this, "please provide location permission.");
                return;
            }
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 400, this);
        } else {
            boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            if (isGPSEnabled) {
                Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_FINE);
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 400, this);
            }
        }
    }    


 @Override
    public void onLocationChanged(Location location) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        Log.d("location", "change");

        Log.d("latitude", String.valueOf(latitude));
        Log.d("longitude", String.valueOf(longitude));
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {
        Toast.makeText(getApplicationContext(), "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
    }

}

Upvotes: 0

Munish Kapoor
Munish Kapoor

Reputation: 3339

Try This

public class LocationDemo extends Activity implements LocationListener {
private static final String TAG = "LocationDemo";
private static final String[] S = { "Out of Service",
        "Temporarily Unavailable", "Available" };

private TextView output;
private LocationManager locationManager;
private String bestProvider;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Get the output UI
    output = (TextView) findViewById(R.id.output);

    // Get the location manager
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    // List all providers:
    List<String> providers = locationManager.getAllProviders();
    for (String provider : providers) {
        printProvider(provider);
    }

    Criteria criteria = new Criteria();
    bestProvider = locationManager.getBestProvider(criteria, false);
    output.append("\n\nBEST Provider:\n");
    printProvider(bestProvider);

    output.append("\n\nLocations (starting with last known):");
    Location location = locationManager.getLastKnownLocation(bestProvider);
    printLocation(location);
}

/** Register for the updates when Activity is in foreground */
@Override
protected void onResume() {
    super.onResume();
    locationManager.requestLocationUpdates(bestProvider, 20000, 1, this);
}

/** Stop the updates when Activity is paused */
@Override
protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
}

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

public void onProviderDisabled(String provider) {
    // let okProvider be bestProvider
    // re-register for updates
    output.append("\n\nProvider Disabled: " + provider);
}

public void onProviderEnabled(String provider) {
    // is provider better than bestProvider?
    // is yes, bestProvider = provider
    output.append("\n\nProvider Enabled: " + provider);
}

public void onStatusChanged(String provider, int status, Bundle extras) {
    output.append("\n\nProvider Status Changed: " + provider + ", Status="
            + S[status] + ", Extras=" + extras);
}

private void printProvider(String provider) {
    LocationProvider info = locationManager.getProvider(provider);
    output.append(info.toString() + "\n\n");
}

private void printLocation(Location location) {
    if (location == null)
        output.append("\nLocation[unknown]\n\n");
    else
        output.append("\n\n" + location.toString());
}

}

// main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">

  <ScrollView android:layout_width="wrap_content"
  android:layout_height="wrap_content">
  <TextView android:id="@+id/output" android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
  </ScrollView>
 </LinearLayout>

Upvotes: 0

koti
koti

Reputation: 3701

did you added

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Permission to manifest file

Upvotes: 0

SERPRO
SERPRO

Reputation: 10067

Take a look at this tutorial: A Deep Dive Into Location

Basically, if you want to get the approximate location using the last known location, you should iterate through all the possible providers with a loop like this:

List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
  Location location = locationManager.getLastKnownLocation(provider);
  if (location != null) {
    float accuracy = location.getAccuracy();
    long time = location.getTime();

    if ((time > minTime && accuracy < bestAccuracy)) {
      bestResult = location;
      bestAccuracy = accuracy;
      bestTime = time;
    }
    else if (time < minTime && 
             bestAccuracy == Float.MAX_VALUE && time > bestTime){
      bestResult = location;
      bestTime = time;
    }
  }
}

Upvotes: 1

Rui Gaspar
Rui Gaspar

Reputation: 154

You can use the LocationManager. See the example:

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();

And place it in Manisfest:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Upvotes: 0

Related Questions