2016-02-27 72 views
2

我正在嘗試構建一個應用程序,它會顯示我在googleMap中的位置,並會每隔幾秒更新一次我的位置。在googleMap中更新位置(android)

這裏是我的代碼:

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

    protected static final String TAG = "location-updates-sample"; 

    /** 
    * The desired interval for location updates. Inexact. Updates may be more or less frequent. 
    */ 
    public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000; 

    /** 
    * The fastest rate for active location updates. Exact. Updates will never be more frequent 
    * than this value. 
    */ 
    public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 
      UPDATE_INTERVAL_IN_MILLISECONDS/2; 

    // Keys for storing activity state in the Bundle. 
    protected final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key"; 
    protected final static String LOCATION_KEY = "location-key"; 

    protected GoogleApiClient mGoogleApiClient; 
    protected LocationRequest mLocationRequest; 
    protected Location mCurrentLocation; 


    /** 
    * Tracks the status of the location updates request. Value changes when the user presses the 
    * Start Updates and Stop Updates buttons. 
    */ 
    protected Boolean mRequestingLocationUpdates; 
    private GoogleMap mMap; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_maps); 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 

     mRequestingLocationUpdates = false; 
     updateValuesFromBundle(savedInstanceState); 
     buildGoogleApiClient(); 
    } 

    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 
     LatLng loc = new LatLng(-34,151); 
     mMap.addMarker(new MarkerOptions().position(loc).title("my location")); 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(loc)); 
     startUpdates(); 
    } 

    private void updateValuesFromBundle(Bundle savedInstanceState) { 
     Log.i(TAG, "Updating values from bundle"); 
     if (savedInstanceState != null) { 
      if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) { 
       mRequestingLocationUpdates = savedInstanceState.getBoolean(
         REQUESTING_LOCATION_UPDATES_KEY); 
      } 

      // Update the value of mCurrentLocation from the Bundle and update the UI to show the 
      // correct latitude and longitude. 
      if (savedInstanceState.keySet().contains(LOCATION_KEY)) { 
       // Since LOCATION_KEY was found in the Bundle, we can be sure that mCurrentLocation 
       // is not null. 
       mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY); 
      } 
      updateUI(); 
     } 
    } 


    protected synchronized void buildGoogleApiClient() { 
     Log.i(TAG, "Building GoogleApiClient"); 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
     createLocationRequest(); 
    } 

    protected void createLocationRequest() { 
     mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); 
     mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    } 


    public void startUpdates() { // start updating location 
     if (!mRequestingLocationUpdates) { 
      mRequestingLocationUpdates = true; 
      LocationServices.FusedLocationApi.requestLocationUpdates(
        mGoogleApiClient, mLocationRequest, this); 
     } 
    } 

    public void stopUpdates() { // stop updating location 
     if (mRequestingLocationUpdates) { 
      mRequestingLocationUpdates = false; 
      LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
     } 
    } 
    /** 
    * Updates the latitude, the longitude, and the last location time in the UI. 
    */ 
    private void updateUI() { 
     LatLng loc = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()); 
     mMap.addMarker(new MarkerOptions().position(loc).title("my location")); 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(loc)); 
    } 

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

    @Override 
    public void onResume() { 
     super.onResume(); 
     if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { 
      LocationServices.FusedLocationApi.requestLocationUpdates(
        mGoogleApiClient, mLocationRequest, this); 
     } 
    } 

    @Override 
    protected void onPause() { 
     super.onPause(); 
     // Stop location updates to save battery, but don't disconnect the GoogleApiClient object. 
     if (mGoogleApiClient.isConnected()) { 
      LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
     } 
    } 

    @Override 
    protected void onStop() { 
     mGoogleApiClient.disconnect(); 
     super.onStop(); 
    } 

    /** 
    * Runs when a GoogleApiClient object successfully connects. 
    */ 
    @Override 
    public void onConnected(Bundle connectionHint) { 
     Log.i(TAG, "Connected to GoogleApiClient"); 

     if (mCurrentLocation == null) { 
      mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
      updateUI(); 
     } 

     if (mRequestingLocationUpdates) { 
      LocationServices.FusedLocationApi.requestLocationUpdates(
        mGoogleApiClient, mLocationRequest, this); 
     } 
    } 


    @Override 
    public void onLocationChanged(Location location) { 
     mCurrentLocation = location; 
     updateUI(); 
     Toast.makeText(this, getResources().getString(R.string.location_updated_message), 
       Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onConnectionSuspended(int cause) { 
     // The connection to Google Play services was lost for some reason. We call connect() to 
     // attempt to re-establish the connection. 
     Log.i(TAG, "Connection suspended"); 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onConnectionFailed(ConnectionResult result) { 
     // Refer to the javadoc for ConnectionResult to see what error codes might be returned in 
     // onConnectionFailed. 
     Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); 
    } 


    /** 
    * Stores activity data in the Bundle. 
    */ 
    public void onSaveInstanceState(Bundle savedInstanceState) { 
     savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, mRequestingLocationUpdates); 
     savedInstanceState.putParcelable(LOCATION_KEY, mCurrentLocation); 
     super.onSaveInstanceState(savedInstanceState); 
    } 
} 

此代碼是從谷歌的樣本代碼的一部分,但我已經改變了一些東西,並增加了GoogleMap的,其onMapReady後僅崩潰()。

堆棧跟蹤:在執行任何操作

java.lang.IllegalStateException: GoogleApiClient is not connected yet. 
                    at com.google.android.gms.common.api.internal.zzh.zzb(Unknown Source) 
                    at com.google.android.gms.common.api.internal.zzl.zzb(Unknown Source) 
                    at com.google.android.gms.common.api.internal.zzj.zzb(Unknown Source) 
                    at com.google.android.gms.location.internal.zzd.requestLocationUpdates(Unknown Source) 
                    at com.idanofek.photomap.MapsActivity.startUpdates(MapsActivity.java:135) 
                    at com.idanofek.photomap.MapsActivity.onMapReady(MapsActivity.java:91) 
                    at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source) 
                    at com.google.android.gms.maps.internal.zzo$zza.onTransact(Unknown Source) 
                    at android.os.Binder.transact(Binder.java:387) 
                    at com.google.android.gms.maps.internal.be.a(SourceFile:82) 
                    at com.google.maps.api.android.lib6.e.fb.run(Unknown Source) 
                    at android.os.Handler.handleCallback(Handler.java:739) 
                    at android.os.Handler.dispatchMessage(Handler.java:95) 
                    at android.os.Looper.loop(Looper.java:148) 
                    at android.app.ActivityThread.main(ActivityThread.java:5417) 
                    at java.lang.reflect.Method.invoke(Native Method) 
                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
+0

你能否更新堆棧跟蹤? – JTeam

+0

您可以嘗試從onMapReady()調用buildGoogleApiClient(),並檢查onMapReady()中isConnected()的值 一個示例是https://github.com/codepath/android-google-maps-demo/blob /master/app/src/main/java/com/example/mapdemo/MapDemoActivity.java 從onMapReady()調用connectClient() – JTeam

+0

@JTeam:我嘗試從onMapReady()調用buildGoogleApiClient(),然後執行mGoogleApiClient .connect()。當我試圖檢查isConnected()的值時,它拋出了一個異常,即mGoogleApiClient爲null。 –

回答

0

之前,GoogleApiClient必須是使用 '連接()'方法連接。在調用onConnected(Bundle)回調之前,客戶端不會被視爲連接。

您應該從onConnected實例在活動的'onCreated(Bundle)'方法的客戶對象,然後調用connect()上在onStart()

你可以叫startLocationUpdate()()回調

@Override 
public void onConnected(Bundle connectionHint) { 
... 
if (mRequestingLocationUpdates) { 
startLocationUpdates(); 
} 
} 

protected void startLocationUpdates() { 
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this); 
} 

以下是關於位置更新的Google文檔:http://developer.android.com/training/location/receive-location-updates.html