GoogleMap is set to null onLocationChanged

时间:2016-10-15 17:18:17

标签: android google-maps

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);
  }

}

2 个答案:

答案 0 :(得分:1)

你需要在onMapReady()中添加位置监听器,这样只有在谷歌地图准备就绪后才能获得位置变更的回调。

答案 1 :(得分:0)

来自documentation

  

必须使用getMapAsync(OnMapReadyCallback)获取GoogleMap。   该类自动初始化地图系统和视图。

您错过了getMapAsync()来电。您应该将其添加到onCreate()

然后你可以在mapReady = true;中将布尔值设置为真onMapReady()并检查
if (mapReady) { // Do stuff }
始终检查
if (mMap != null) { // Do stuff }使用时。{/ p>

否则代码看起来没什么好看的,但我并没有真正调试它。