Почему Google не отображает автоматический масштаб до местоположения пользователя при первом запуске? - PullRequest
0 голосов
/ 22 января 2019

Когда пользователь впервые входит в GoogleMapsActivity, он не переносит их автоматически в свое местоположение, пользователь должен нажать на маленькую кнопку со значком местоположения в правом верхнем углу, и он перенесет их в их местоположение.

Я пытался использовать newLatLngZoom (latLng, zoom), но это не сработало. И я прошел все предложенные вопросы, прежде чем отправлять этот вопрос, и ни один не работал. Некоторые были в iOS тоже. Я использую Android.

public class AppetiteMapsActivity extends FragmentActivity implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener

{

private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private static final String TAG = "AppetiteMapsActivity";
private Location lastLocation;
private Marker currentUserLocationMarker;
private LocationManager locationManager;
private com.google.android.gms.location.LocationListener listener;
private static final int Request_User_Location_Code= 99;

private long UPDATE_INTERVAL = 2 * 1000;  /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */


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


    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
    {
        checkUserLocationPermission();
    }

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    checkLocation();

}


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker in current user location and move the camera
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
    {
        buildGoogleApiClient();
        // Call current location of user
        mMap.setMyLocationEnabled(true);
    }

}

public boolean checkUserLocationPermission()
{
    if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
        {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
        }
        else
            {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
            }
            return false;
    }
    else
    {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
    switch(requestCode)
    {
        case Request_User_Location_Code:

            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                {
                    if (googleApiClient == null)
                    {
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }

            }

            else
            {
                Toast.makeText(this, R.string.on_request_permission_gps_not_located, Toast.LENGTH_LONG).show();
            }
            return;
    }
}

protected synchronized void buildGoogleApiClient()
{
    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    googleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {
    {

        locationRequest = new LocationRequest();
        locationRequest.setInterval(1100);
        locationRequest.setFastestInterval(1100);
        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        {
            LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
        }
    }
}

@Override
public void onConnectionSuspended(int i) {
    Log.i(TAG, "Connection Suspended");
    googleApiClient.connect();
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}

@Override
protected void onStart() {
    super.onStart();
    if (googleApiClient != null) {
        googleApiClient.connect();
    }
}

@Override
protected void onStop() {
    super.onStop();
    if (googleApiClient.isConnected()) {
        googleApiClient.disconnect();
    }
}

protected void startLocationUpdates() {
    // Create the location request
    locationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(UPDATE_INTERVAL)
            .setFastestInterval(FASTEST_INTERVAL);
    // Request location updates
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,
            locationRequest, this);
    Log.d("reque", "--->>>>");
}

@Override
public void onLocationChanged(Location location)
{
    lastLocation = location;
    if (currentUserLocationMarker!=null)
    {
        currentUserLocationMarker.remove();
    }

    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title(getString(R.string.user_current_location_marker_title));
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));

    currentUserLocationMarker = mMap.addMarker(markerOptions);


    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomBy(14));

    if(googleApiClient != null)
    {
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
    }

}

private boolean checkLocation() {
    if(!isLocationEnabled())
        showAlert();
    return isLocationEnabled();
}

private void showAlert() {
    final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle(R.string.show_alert_title_enable_location)
            .setMessage(getString(R.string.show_alert_location_settings_off_1) +
                    getString(R.string.show_alert_location_settings_off_2))
            .setPositiveButton(R.string.show_alert_positive_button_location_settings, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                    Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(myIntent);
                }
            })
            .setNegativeButton(R.string.explain_negative_button, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                }
            });
    dialog.show();
}

private boolean isLocationEnabled() {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}

}

Я ожидаю, что Карты Google автоматически перейдут в местоположение пользователей, когда они впервые зайдут в Активность в Картах Google, но вместо этого пользователь должен нажать кнопку местоположения в верхнем правом углу, чтобы отправить их туда. Спасибо за вашу помощь и советы заранее!

1 Ответ

0 голосов
/ 22 января 2019

Я пытался использовать newLatLngZoom(latLng, zoom), но это не сработало.

Используйте это так, оно будет работать:

mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng, zoom));
mMap.getUiSettings().setRotateGesturesEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);

Примечание:

  1. Сначала включите управление масштабированием.
  2. Затем вы делаете масштабирование.
  3. После этого вы отключаете управление масштабированием.

Надеюсь, это поможет.

Ссылка для дополнительной информации

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...