2

When the user first enters the GoogleMapsActivity it does not automatically take them to their location, the user has to click the little location icon button at the top right and it will take them to their location.

I have tried using newLatLngZoom(latLng, zoom) but that didn't work. And I went through all the suggested questions before posting this question, and none worked. Some were in iOS too. I am using 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);
}

}

I expect Google Maps to automatically go to the users location when they first go into the Google Maps Activity, but instead the user has to click the location button at the top right corner to send them there. Thanks for your help and advice in advanced!

Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
Treewallie
  • 346
  • 2
  • 13
  • Is there something in the documentation or elsewhere that leads you to believe a feature is missing? – greeble31 Jan 21 '19 at 22:14
  • I wouldn't think so. the startLocationUpdates says it is never used, but when I added it to the onCreate method, it crashed my app. And so far, everything works perfect, I just wish it would auto zoom to the users location when Google Maps Activity first starts, because as of right now, I have to manually click the little circle icon at the top right of the map to go to the user location. – Treewallie Jan 21 '19 at 22:29
  • While I see what you're saying, my point is "I don't think it's supposed to do that for you automatically". You had the right idea when you were trying to call `startLocationUpdates()`. It looks like you already have all this code written. Maybe ditch the deprecated `FusedLocationApi` -- see [here](https://stackoverflow.com/questions/44992014/how-to-get-current-location-in-googlemap-using-fusedlocationproviderclient). If your code crashes, use the stack trace to determine what went wrong. – greeble31 Jan 21 '19 at 23:50
  • Cool thanks a lot appreciate the advice! – Treewallie Jan 23 '19 at 00:24

1 Answers1

3

I have tried using newLatLngZoom(latLng, zoom) but that didn't work.

Use it like this, it will work:

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

Note:

  1. First, you Enable Zoom Controls.
  2. Then, you do the Zooming thing.
  3. After that, you Disable Zoom Controls.

Hope it helps.

Reference for more info

Suryakant Bharti
  • 673
  • 1
  • 6
  • 24
  • 2
    Awesome thanks for the great tip! I'm going to try adding this tomorrow when I'm back to coding! Have a great night! Appreciate the help. – Treewallie Jan 23 '19 at 00:25
  • 1
    Awesome! Worked! Thank you! We are both new too to stack overflow! Thanks for taking the time to help out! I appreciate it! If you have the time, please plus 1 my main post? Thank you! – Treewallie Jan 24 '19 at 17:48