2016-04-16 10 views
7

Sto tentando di visualizzare la posizione corrente dell'utente sulla mappa di google all'interno della mia app, ma non voglio continuare ad aggiornare la posizione mentre l'utente si sposta. La sua posizione iniziale dovrebbe essere registrata e mostrata finché non chiude l'app. Ho scritto il seguente codice per questo:Ottieni la posizione corrente in onMapReady in Android utilizzando l'API di google locations

private GoogleMap mMap; 
protected GoogleApiClient mGoogleApiClient; 
Location mLastLocation; 
double lat =0, lng=0; 

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

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


} 

private void buildGoogleApiClient() { 
    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 
} 


/** 
* Manipulates the map once available. 
* This callback is triggered when the map is ready to be used. 
* This is where we can add markers or lines, add listeners or move the camera. In this case, 
* we just add a marker near Sydney, Australia. 
* If Google Play services is not installed on the device, the user will be prompted to install 
* it inside the SupportMapFragment. This method will only be triggered once the user has 
* installed Google Play services and returned to the app. 
*/ 
@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 

    // Add a marker in Sydney and move the camera 
    mMap.setMyLocationEnabled(true); 

    LatLng loc = new LatLng(lat, lng); 
    mMap.addMarker(new MarkerOptions().position(loc).title("New Marker")); 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(loc)); 
} 

@Override 
public void onConnected(Bundle bundle) { 
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
      mGoogleApiClient); 
    if (mLastLocation != null) { 
     lat = mLastLocation.getLatitude(); 
     lng = mLastLocation.getLongitude(); 
    } 
} 

@Override 
protected void onStart() { 
    super.onStart(); 

    mGoogleApiClient.connect(); 
} 

Il problema con questo codice è che sto ottenendo l'esecuzione lat, lng dopo la funzione onMapReady ha già finito. Ho pensato che uno dei modi per correggere questo sarebbe creare un AsyncTask per garantire che i dati sulla posizione vengano recuperati prima della mappa. Tuttavia, sto cercando di implementarlo in modo da non utilizzare AsyncTask.

risposta

6

Basta muovere il codice che crea i marcatori da onMapReady() a onConnected(), e spostare la chiamata buildGoogleApiClient() chiamata onCreate()-onMapReady():

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

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

} 


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

    // Add a marker in Sydney and move the camera 
    mMap.setMyLocationEnabled(true); 

    //add this here: 
    buildGoogleApiClient(); 

    //LatLng loc = new LatLng(lat, lng); 
    //mMap.addMarker(new MarkerOptions().position(loc).title("New Marker")); 
    //mMap.moveCamera(CameraUpdateFactory.newLatLng(loc)); 
} 

@Override 
public void onConnected(Bundle bundle) { 
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
      mGoogleApiClient); 
    if (mLastLocation != null) { 
     lat = mLastLocation.getLatitude(); 
     lng = mLastLocation.getLongitude(); 

     LatLng loc = new LatLng(lat, lng); 
     mMap.addMarker(new MarkerOptions().position(loc).title("New Marker")); 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(loc)); 
    } 
} 

Anche se, notare che è spesso ottenere nulla dalla chiamata a getLastLocation(). Puoi utilizzare requestLocationUpdates() e chiamare removeLocationUpdates() quando arriva la prima posizione. Dai uno sguardo allo this answer, ha un esempio completo di esattamente quello che stai cercando di fare.

Problemi correlati