Местоположение в Map Activity не установлено сразу?

Я хочу, чтобы моя активность на карте увеличивалась до текущего местоположения пользователя при открытии карты. Если я включу службы определения местоположения перед запуском приложения, оно будет работать нормально. Когда я отключаю службы определения местоположения и запускаю свое приложение, пользователю предлагается включить службы определения местоположения. Чтобы включить его, им нужно перейти к настройкам, а когда они нанесут ответный удар, карта должна приблизиться к их текущему местоположению. Я поместил свой zoomToLocation в setUpMap(), который вызывается в OnResume(), но по какой-то причине он не работает.

Код:

Проверка службы геолокации:

private boolean checkLocationEnabled() {
    //credits: http://stackoverflow.com/questions/10311834/how-to-check-if-location-services-are-enabled
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    final boolean gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    boolean networkEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if (!gpsEnabled) {
        AlertDialog.Builder gpsAlertBuilder = new AlertDialog.Builder(this);
        gpsAlertBuilder.setTitle("Location Services Must Be Turned On");
        gpsAlertBuilder.setMessage("Would you like to turn them on now? (Note: if not, you will be unable to use the map to find breweries. You will still be able to search for them.");
        gpsAlertBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                Intent enableGPSIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(enableGPSIntent);
            }
        });
        gpsAlertBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });
        AlertDialog gpsAlert = gpsAlertBuilder.create();
        gpsAlert.show();
    }

    return gpsEnabled;


}

Методы Zoom и zoomToLocation():

 private void zoom(Location location) {
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
            new LatLng(location.getLatitude(), location.getLongitude()), 13));

    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
            .zoom(17)                   // Sets the zoom// Sets the orientation of the camera to east// Sets the tilt of the camera to 30 degrees
            .build();                   // Creates a CameraPosition from the builder
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}

private void zoomToLocation() {
    //credits: http://stackoverflow.com/questions/18425141/android-google-maps-api-v2-zoom-to-current-location
    //http://stackoverflow.com/questions/14502102/zoom-on-current-user-location-displayed/14511032#14511032
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();

    Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
    if (location != null) {

        zoom(location);

    } else {

       return;
    }

}

Метод setUpMap:

private void setUpMap() {
    UiSettings settings = mMap.getUiSettings();
    settings.setZoomControlsEnabled(true);
    settings.setZoomGesturesEnabled(true);
    mMap.setMyLocationEnabled(true);
    settings.setMyLocationButtonEnabled(true);
    setUpActionBar();
    if(checkLocationEnabled()) {
        zoomToLocation();

    }
}

Метод OnResume:

 protected void onResume() {
    super.onResume();
    setUpMapIfNeeded(); //setUpMap called in setUpMapIfNeeded
}

И, наконец, метод mySetUpMapIfNeeded():

  private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
            setUpActionBar();
        }
    }
}

person Bender Rodriguez    schedule 30.07.2015    source источник


Ответы (1)


Ваш setUpMapIfNeeded() onResume, вероятно, называется.

Но в вашем setUpMapIfNeeded вы вызываете setUpMap() только в том случае, если первый mMap равен нулю. Что не является нулевым, когда вы возобновляете свое приложение. Вы должны установить уровень масштабирования с помощью какой-либо другой функции, отличной от setUpMap().

Что-то вроде этого.

private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
            setUpActionBar();
        }
    }
    else{
         //setup zoom level since your mMap isn't null.
    }
}
person Sharj    schedule 30.07.2015