2016-04-16 7 views
7

私は自分のアプリ内のGoogleマップにユーザーの現在の場所を表示しようとしていますが、ユーザーの移動に合わせて場所を更新したくありません。彼の最初の位置は記録され、彼がアプリを閉じるまで示されるべきだった。私は、このために以下のコードを書かれている:Googleの場所を使用してAndroidでonMapReadyの現在地を取得するAPI

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

このコードの問題はonMapReady機能が既に実行を終了した後、私はlat, lngを取得していますということです。私は、これを修正する方法の1つが、AsyncTaskを作成して、地図の前に位置データを取得することを確実にすると考えました。しかし、私はAsyncTaskを使用しない方法でこれを実装しようとしています。

答えて

6

だけonConnected()onMapReady()からマーカーを作成するコードを移動し、onMapReady()からonCreate()からの呼び出しbuildGoogleApiClient()コール移動:あなたが頻繁にgetLastLocation()への呼び出しからヌル取得することに注意してください、が

​​

を。 requestLocationUpdates()を使用し、最初の場所が来たらremoveLocationUpdates()に電話をかけることができます。 this answerを見てください。これはあなたがしようとしているものの完全な例です。

関連する問題