我正在尝试创建一个简单的android应用程序,它必须以片段和设备的最后已知位置显示地图。我想使用Google来定位,但是每当我调用fusedLocationProviderClient.getLastLocation方法时,结果总是为null,地图上显示的位置总是纬度0,经度0。
公共类MapsFragment扩展片段{
FusedLocationProviderClient client;
double latitude, longitude;
private OnMapReadyCallback callback = new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
//Check condition
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
//When permission is granted, call method
getCurrentLocation();
} else {
//When permission is not granted, request permission
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
}
//LatLng object creation
LatLng latLng = new LatLng(latitude, longitude);
//Set map coordinates using latLng object
googleMap.addMarker(new MarkerOptions().position(latLng).title("Current Position"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
};
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_maps, container, false);
return v;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment mapFragment =
(SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
if (mapFragment != null) {
mapFragment.getMapAsync(callback);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//Check condition
if (requestCode == 100 && (grantResults.length > 0) && (grantResults[0] + grantResults[1] ==
PackageManager.PERMISSION_GRANTED)) {
//When permission are granted, call method
getCurrentLocation();
} else {
Toast.makeText(getActivity(), "Permission denied", Toast.LENGTH_SHORT).show();
}
}
@SuppressLint("MissingPermission")
private void getCurrentLocation() {
client = LocationServices.getFusedLocationProviderClient(getActivity());
//Initialize location manager, whose allow to get periodic updates of the location
LocationManager locationManager = (LocationManager) getActivity()
.getSystemService(Context.LOCATION_SERVICE);
//Check condition, when GPS and NETWORK provider are enabled, WORK
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
//When location is enabled, get last location, THE PROBLEM IS THERE
client.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
Location location = task.getResult();
//Check condition
if (location != null) {
//When location result is not null, set latitude and longitude
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
//When location result is not null, initialize location request
LocationRequest locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10000)
.setFastestInterval(1000)
.setNumUpdates(1);
//Initialize location callback
LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(@NonNull LocationResult locationResult) {
//Initialize location
Location location1 = locationResult.getLastLocation();
//Set latitude and longitude
latitude = location1.getLatitude();
longitude = location1.getLatitude();
}
};
//Request location updates
client.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}
}
});
} else {
//When location service is not enabled, open location setting
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
发布于 2021-12-20 14:38:26
最后一个位置是设备上的一个缓存位置,因此获得null意味着最近没有使用该位置。如果您先打开google地图或使用您的gps位置的东西,让它得到您的位置,然后返回到您的应用程序中,您将得到一个有效的位置。
https://stackoverflow.com/questions/70423403
复制相似问题