API FusedLocationProviderClient используется для получения текущего местоположения пользовательского устройства.Создайте экземпляр
private FusedLocationProviderClient mFusedLocationClient;
и инициализируйте его
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
. Убедитесь, что пользователь получил разрешение на размещение в приложении, либо запросите разрешение на местоположение во время выполнения.
onRequestPermissionsResult переопределяется для обработки результата запроса на разрешение.
В приведенном ниже классе вы видите ... в OnActivityResult мы получаем текущую широту и долготу.
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient mFusedLocationClient;
private double wayLatitude = 0.0, wayLongitude = 0.0;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private android.widget.Button btnLocation;
private TextView txtLocation;
private android.widget.Button btnContinueLocation;
private TextView txtContinueLocation;
private StringBuilder stringBuilder;
private boolean isContinue = false;
private boolean isGPS = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.txtContinueLocation = (TextView) findViewById(R.id.txtContinueLocation);
this.btnContinueLocation = (Button) findViewById(R.id.btnContinueLocation);
this.txtLocation = (TextView) findViewById(R.id.txtLocation);
this.btnLocation = (Button) findViewById(R.id.btnLocation);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10 * 1000); // 10 seconds
locationRequest.setFastestInterval(5 * 1000); // 5 seconds
new GpsUtils(this).turnGPSOn(new GpsUtils.onGpsListener() {
@Override
public void gpsStatus(boolean isGPSEnable) {
// turn on GPS
isGPS = isGPSEnable;
}
});
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
if (!isContinue) {
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
stringBuilder.append(wayLatitude);
stringBuilder.append("-");
stringBuilder.append(wayLongitude);
stringBuilder.append("\n\n");
txtContinueLocation.setText(stringBuilder.toString());
}
if (!isContinue && mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(locationCallback);
}
}
}
}
};
btnLocation.setOnClickListener(v -> {
if (!isGPS) {
Toast.makeText(this, "Please turn on GPS", Toast.LENGTH_SHORT).show();
return;
}
isContinue = false;
getLocation();
});
btnContinueLocation.setOnClickListener(v -> {
if (!isGPS) {
Toast.makeText(this, "Please turn on GPS", Toast.LENGTH_SHORT).show();
return;
}
isContinue = true;
stringBuilder = new StringBuilder();
getLocation();
});
}
private void getLocation() {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
AppConstants.LOCATION_REQUEST);
} else {
if (isContinue) {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, location -> {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
});
}
}
}
@SuppressLint("MissingPermission")
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1000: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (isContinue) {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, location -> {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
});
}
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == AppConstants.GPS_REQUEST) {
isGPS = true; // flag maintain before get location
}
}
}
}
Теперь Используя эти значения, вы добавляете маркер на карту, чтобы показать текущее местоположение.Пожалуйста, убедитесь, что вы выбрали местоположение пользователя в сервисе или в фоновом режиме.
В качестве предупреждения вы можете использовать:
private void getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
if (mLocationPermissionGranted) {
Task locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, 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.
mLastKnownLocation = task.getResult();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
});
}
} catch(SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
вызвать метод getDeviceLocation () вФункция onMapReady (карта GoogleMap).