Without clicking any button, how to directly get the current location and move the camera to it.
Also, I found that there is a button on the right top of the map. When c
I am explaining, How to get current location and Directly move to the camera to current location with assuming that you have implemented map-v2. For more details, You can refer official doc.
Add location service in gradle
implementation "com.google.android.gms:play-services-location:11.0.1"
Add location permission in manifest file
Make sure you ask for RunTimePermission. I am using Ask-Permission for that. Its easy to use.
Now refer below code to get the current location and display it on a map.
private FusedLocationProviderClient mFusedLocationProviderClient;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFusedLocationProviderClient = LocationServices
.getFusedLocationProviderClient(getActivity());
}
private void getDeviceLocation() {
try {
if (mLocationPermissionGranted) {
Task locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
Location location = task.getResult();
LatLng currentLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(currentLatLng,
DEFAULT_ZOOM);
googleMap.moveCamera(update);
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
When user granted location permission call above getDeviceLocation() method
private void updateLocationUI() {
if (googleMap == null) {
return;
}
try {
if (mLocationPermissionGranted) {
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
getDeviceLocation();
} else {
googleMap.setMyLocationEnabled(false);
googleMap.getUiSettings().setMyLocationButtonEnabled(false);
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}