В вашем текущем коде текущее местоположение обновляется только при нажатии «кнопки включения».
Однако в этом коде вы добавляете новый OnClickListener
к этой кнопке каждый раз, когда местоположение обновляется. Вместо этого вы должны определить OnClickListener
to publi sh текущее значение latLng
(которое в коде ниже я переименовал в mLatLng
, чтобы следовать соглашениям).
// Firebase services
private FirebaseAuth mAuth;
private FirebaseDatabase mDatabase;
// Firebase objects
private FirebaseUser mUser;
private DatabaseReference mUserRef;
// Java objects
private SupportMapFragment mMapFragment;
private LatLng mLatLng;
private String mUserId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
Intent intent = getIntent();
mUserId = intent.getStringExtra("userid");
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser(); // unused?
mDatabase = FirebaseDatabase.getInstance();
mUserRef = mDatabase.child("User").child(mUserId);
if(requestSinglePermission()){
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mMapFragment.getMapAsync(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
checkLocation();
}
final MapsActivity2 self = this;
Button btnEnable = (Button) findViewById(R.id.enable_btn);
btnEnable.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// On click, saves last location to Firebase RTDB
long latitude = self.mLatLng.getLatitude();
long longitude = self.mLatLng.getLongitude();
String pushId = mUserRef.push().getKey();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/Latitude/" + pushId, latitude);
childUpdates.put("/Longitude/" + pushId, longitude);
mUserRef.updateChildren(childUpdates)
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "btnEnable#onClick:onFailure", databaseError.toException());
}
});
}
});
}
@Override
public void onLocationChanged(Location location) {
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Toast.makeText(this, msg+userId, Toast.LENGTH_SHORT).show();
this.mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
this.mMapFragment.getMapAsync(this);
}
Если вы хотите сохранить текущее местоположение в базе данных при каждом обновлении местоположения, вы будете использовать:
@Override
public void onLocationChanged(Location location) {
long latitude = location.getLatitude();
long longitude = location.getLongitude();
String msg = "Updated Location: " +
Double.toString(latitude) + "," +
Double.toString(longitude);
Toast.makeText(this, msg+userId, Toast.LENGTH_SHORT).show();
this.mLatLng = new LatLng(latitude, longitude);
String pushId = mUserRef.push().getKey();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/Latitude/" + pushId, latitude);
childUpdates.put("/Longitude/" + pushId, longitude);
mUserRef.updateChildren(childUpdates)
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "onLocationChanged:onFailure", databaseError.toException());
}
});
this.mMapFragment.getMapAsync(this);
}