Skip to content

Instantly share code, notes, and snippets.

@florinmuscalu
Created February 3, 2021 14:43
Show Gist options
  • Save florinmuscalu/0be70d0121b3782ecc3fb982b58f1b07 to your computer and use it in GitHub Desktop.
Save florinmuscalu/0be70d0121b3782ecc3fb982b58f1b07 to your computer and use it in GitHub Desktop.
public LatLng getLocation() {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(),"Request permission first!", Toast.LENGTH_LONG).show();
return null;
}
LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
double lat, lon;
try {
lat = location.getLatitude();
lon = location.getLongitude();
return new LatLng(lat, lon);
} catch (NullPointerException e) {
e.printStackTrace();
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment