0

I'm trying to follow along a simple Google Maps Android Tutorial but I'm running into a problem with my GoogleMap object, it seems as though it has the value of null when the onLocationChanged method is fired, I tried checking for the null object inside that method but doing so doesn't set the marker.

Is this the way to use onLocationChanged? because comments I've seen from Google indicate that the onMapReady function is used to add markers and listeners. Do I need to go about a different way of hooking up my LocationListener?

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

  public static final String TAG = MapsActivity.class.getSimpleName();

  private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

  private GoogleMap mMap;
  private GoogleApiClient mGoogleApiClient;
  private LocationRequest mLocationRequest;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_maps);
      // Obtain the SupportMapFragment and get notified when the map is ready to be used.
      SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
              .findFragmentById(R.id.map);

      mGoogleApiClient = new GoogleApiClient.Builder(this)
              .addConnectionCallbacks(this)
              .addOnConnectionFailedListener(this)
              .addApi(LocationServices.API)
              .build();

      // Create a LocationRequest object
      mLocationRequest = LocationRequest.create()
              .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
              .setInterval(10 * 1000)     // 10 seconds, in milliseconds
              .setFastestInterval(1 * 1000); // 1 second, in milliseconds
  }

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

  @Override
  public void onConnected(Bundle bundle) {
      Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

      // no prior location
      if(location == null) {
          LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
      } else {
          handleNewLocation(location);
      }

      double latitude = location.getLatitude();
      double longitude = location.getLongitude();

      Log.i(TAG, "Latitude: " + latitude + " Longitude" + longitude);
  }

  @Override
  public void onConnectionSuspended(int i) {
      Log.i(TAG, "LocationServices has been suspended. Please reconnect");
  }

  @Override
  public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
      if(connectionResult.hasResolution()) {
          try {
              // Start an Activity that tries to resolve the error
              connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
          } catch (IntentSender.SendIntentException e) {
              e.printStackTrace();
          }
      } else {
          Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
      }
  }

  @Override
  protected void onResume() {
      super.onResume();
      mGoogleApiClient.connect();
  }

  @Override
  protected void onPause() {
      super.onPause();
      if(mGoogleApiClient.isConnected()) {
           LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
          mGoogleApiClient.disconnect();
      }
  }

  private void handleNewLocation(Location location) {

      double currentLatitude = location.getLatitude();
      double currentLongitude = location.getLongitude();

      LatLng latLng = new LatLng(currentLatitude, currentLongitude);

      MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("I am here!");

      mMap.addMarker(markerOptions);
      mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

  }

  @Override
  public void onLocationChanged(Location location) {
      handleNewLocation(location);
  }

}

LAB
  • 83
  • 1
  • 8
  • Working code here: http://stackoverflow.com/questions/34582370/how-can-i-show-current-location-on-a-google-map-on-android-marshmallow – Daniel Nugent Oct 15 '16 at 17:31

2 Answers2

1

you need to add location listener inside the onMapReady() , so that only after google map is ready you get the callback for location change.

Deepak John
  • 967
  • 1
  • 7
  • 19
0

From the documentation:

A GoogleMap must be acquired using getMapAsync(OnMapReadyCallback). This class automatically initializes the maps system and the view.

You are missing the getMapAsync() call. You should add it to onCreate().

And you could then either set a boolean to true mapReady = true; in onMapReady() and check
if (mapReady) { // Do stuff }
or just always check
if (mMap != null) { // Do stuff }
when using it.

Otherwise the code looks okay at a quick glance, but I didn't really debug it in my head.

Shweta Nandha
  • 728
  • 1
  • 8
  • 19
Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30