How to extract latitude and longitude from firebase whenever they get updated? When i am trying to get it it returns Both the key-value pair, All i need is latest value.
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
databaseReference = FirebaseDatabase.getInstance().getReference("Routes").child("route1").child("Location");
ValueEventListener valueEventListener = databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {[enter image description here][1]
String lat = snapshot.child("Latitude").getValue().toString();
Toast.makeText(ParentsMapActivity.this, lat.toString(), Toast.LENGTH_LONG).show();
}
});
CodePudding user response:
The Latitude
and Longitude
nodes don't contain numeric values, but instead contain a child nodes that contains that value. From the looks of it, the extra child nodes (starting with -M
) were generated by calling push()
. If you remove that extra push()
call, your code can read the values from the resulting data.
CodePudding user response:
As per your requirement, the latest database value from firebase
must be obtained to plot on map .In mapsActivity, you can try the this.
override fun onResume() {
super.onResume()
//get instance of firebase database
database = FirebaseDatabase.getInstance().reference
//look for name from reference
database.child(getName!!).get().addOnSuccessListener {
//check that name is available or not if yes then->
if (it.exists()) {
val h = Handler()
h.postDelayed(object : Runnable {
private var time: Long = 0
override fun run() {
val latitude: Double = it.child("latitude").value.toString().toDouble()
//get the long latitude entity value form reference
val longitude: Double = it.child("longitude").value.toString().toDouble()
//assigning the positions of lat and long
position = LatLng(latitude, longitude)
mMap.clear()
mMap.addMarker(MarkerOptions().position(position).title("$getName"))
mMap.moveCamera(CameraUpdateFactory.newLatLng(position))
time = 1000
h.postDelayed(this, 1000)
}
}, 1000) // 1 second delay (takes millis)
mMap.animateCamera(CameraUpdateFactory.zoomTo(15f))
} else Toast.makeText(this, "Location doesn't exist", Toast.LENGTH_SHORT).show()
}.addOnFailureListener {
Toast.makeText(this, "Location didn't reach the database", Toast.LENGTH_SHORT).show()
}
}