7
我試圖在我的應用程序內的谷歌地圖上顯示用戶的當前位置,但我不想隨着用戶移動而不斷更新位置。他的初始位置應該記錄並顯示,直到他關閉應用程序。我寫了下面的代碼是:使用谷歌地點在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();
}
這段代碼的問題是,我得到了lat, lng
後onMapReady
功能已執行完畢。我認爲解決此問題的方法之一是創建一個AsyncTask
以確保在地圖之前檢索位置數據。但是,我試圖以不會使用AsyncTask
的方式實現此功能。