Before enabling the My Location layer, you must request location permission from the user. This sample does not include a request for location permission.
To simplify, in terms of lines of code, the request for the location permit can be made using the library EasyPermissions.
Then following the example of the official documentation of The My Location Layer my code works as follows for all versions of Android that contain Google services.
OnMyLocationClickListener
y OnMyLocationButtonClickListener
.implementation 'pub.devrel:easypermissions:2.0.1'
Forward results to EasyPermissions within method onRequestPermissionsResult()
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
Request permission and operate according to the user's response with requestLocationPermission()
requestLocationPermission()
and set the listeners to onMapReady()
.public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleMap.OnMyLocationClickListener,
GoogleMap.OnMyLocationButtonClickListener {
private final int REQUEST_LOCATION_PERMISSION = 1;
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
requestLocationPermission();
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@SuppressLint("MissingPermission")
@AfterPermissionGranted(REQUEST_LOCATION_PERMISSION)
public void requestLocationPermission() {
String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
if(EasyPermissions.hasPermissions(this, perms)) {
mMap.setMyLocationEnabled(true);
Toast.makeText(this, "Permission already granted", Toast.LENGTH_SHORT).show();
}
else {
EasyPermissions.requestPermissions(this, "Please grant the location permission", REQUEST_LOCATION_PERMISSION, perms);
}
}
@Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
return false;
}
@Override
public void onMyLocationClick(@NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
}
}