public class Game_Activity extends FragmentActivity implements OnMapReadyCallback {
private Location currentLocation;
private FusedLocationProviderClient fusedClient;
private static final int REQUEST_CODE =101;
private FrameLayout map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
map=findViewById(R.id.map);
fusedClient = LocationServices.getFusedLocationProviderClient(this);
getLocation();
}
private void getLocation() {
if (ActivityCompat.checkSelfPermission(
this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(
this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_CODE);
return;
}
Task<Location> task = fusedClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
currentLocation = location;
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
assert supportMapFragment != null;
supportMapFragment.getMapAsync(Game_Activity.this);
}
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
googleMap.getUiSettings().setScrollGesturesEnabled(false);
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("Player");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
googleMap.addMarker(markerOptions);
}
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,@NonNull int[] grantResults){
super.onRequestPermissionsResult(requestCode,permissions,grantResults);
if(requestCode == REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLocation();
}
}
}
}
这是我的代码,我试图为其制作一张地图,以便在启动它时将其缩放到我当前的位置(就像在 pokemon go 中一样),但它没有放大。我尝试调试并在成功方法中找到位置似乎保持为空,有人有任何修复吗?
解决问题
您可能收到空的当前位置。查看此[位置回调][1] https://developer.android.com/develop/sensors-and-location/location/request-updates 以获取最新位置