相机不会在Google地图中关注用户当前位置

时间:2018-03-16 13:36:20

标签: android google-maps google-maps-api-3 google-maps-markers locationlistener

我有以下代码,当我启动应用程序时,我可以显示当前位置。

public class MainActivity extends AppCompatActivity implements LocationListener {
   //private fields

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (isGooglePlayServicesOk()) {
            getLocationPermissions();
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        this.location = location;
    //NO TOAST MESSAGE - NOTHING HAPPENS <=============
    Toast.makeText(context, location.getLatitude() + " / " + location.getLongitude(), Toast.LENGTH_SHORT).show();
    }

    //Other three empty methods onStatusChanged, onProviderEnabled and onProviderDisabled

    private void getDeviceLocation() {
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        try {
            if (locationPermissionsGranted) {
                Task task = fusedLocationProviderClient.getLastLocation();
                task.addOnCompleteListener(new OnCompleteListener() {
                    @Override
                    public void onComplete(@NonNull Task task) {
                        if (task.isSuccessful()) {
                            location = (Location) task.getResult();
                            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18f));
                        }
                    }
                });
            }
        } catch (SecurityException se) {
            Log.d(TAG, se.getMessage());
        }
    }

    public boolean isGooglePlayServicesOk() {
        //Method that check Google Play Services
    }

    private void initializeMap() {
        SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        supportMapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;

                if (locationPermissionsGranted) {
                    getDeviceLocation();
                    if (/* Manifest Conditions */) {return;}
                    mMap.setMyLocationEnabled(true);
                }
            }
        });
    }

    private void getLocationPermissions() {
        String[] permissions = {COARSE_LOCATION, FINE_LOCATION};
        if (ContextCompat.checkSelfPermission(this.getApplicationContext(), COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                locationPermissionsGranted = true;
                initializeMap();
            } else {
                ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
            }
        } else {
            ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        locationPermissionsGranted = false;

        switch (requestCode) {
            case LOCATION_PERMISSION_REQUEST_CODE: {
                if (grantResults.length > 0) {
                    for (int grantResult : grantResults) {
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            locationPermissionsGranted = false;
                            return;
                        }
                    }
                    locationPermissionsGranted = true;
                    initializeMap();
                }
            }
        }
    }
}

因此,每当我移动时,我都不会在地图中居中。为了让我再次进入地图的中心,我需要按位置按钮。我已经从onLocationChanged()接口实现了LocationListener方法但没有任何反应。甚至没有显示Toast消息。我怎样才能解决这个问题,所以我到处都是,始终保持在地图的中心?

提前致谢!

1 个答案:

答案 0 :(得分:1)

当您按照this tutorial要求实施该位置时,如最后所述,您需要关注this one以更新新位置。

创建回调:

mLocationCallback = new LocationCallback() {
  @Override
  public void onLocationResult(LocationResult locationResult) {
      if (locationResult == null) {
          return;
      }
      for (Location location : locationResult.getLocations()) {
          // Update UI with location data
          // ...
      }
  };
};

设置监听器/回调:

mFusedLocationClient.requestLocationUpdates(mLocationRequest,
  mLocationCallback,
  null /* Looper */);