How can I retrieve latitude and longitude fields from all Firebase Firestore documents?

Viewed 38

I attach my database

Each user registered in the "Users" collection has a field of "latitude" and "longitude" of type double.

Basically, I want to get all the latitude and longitude fields to insert different locations on the map, similar to this, but getting them from Firestore, as well as captioning them with the user's email .title(emailUser):

private DatabaseReference mDatabase;
 @Override
protected void onCreate(Bundle savedInstanceState)...

mDatabase = FirebaseDatabase.getInstance().getReference();

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

mDatabase.child("usuarios").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            for (Marker marker:realTimeMarkers){
                marker.remove();
            }
            for(DataSnapshot snapshot: dataSnapshot.getChildren()){
                MapsPojo mp = snapshot.getValue(MapsPojo.class);
                Double latitud = mp.getLatitud();
                Double longitud = mp.getLongitud();
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(new LatLng(latitud,longitud)).title("Usuario").snippet("BRINDADOR").icon(bitmapDescriptorFromVector(getApplicationContext(),R.drawable.ic_baseline_eco_24));
                tmpRealTimeMarkers.add(mMap.addMarker(markerOptions));
            }
            realTimeMarkers.clear();
            realTimeMarkers.addAll(tmpRealTimeMarkers);
        }
        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });

I attach my Firebase Realtime Database

1 Answers

To get the data from Firestore in the same way you're getting it from the Realtime Database, please use the following lines of code:

FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("usuarios").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                if (document != null) {
                    Double latitud = document.getDouble("latitud");
                    Double longitud = document.getDouble("longitud");
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions.position(new LatLng(latitud,longitud)).title("Usuario").snippet("BRINDADOR").icon(bitmapDescriptorFromVector(getApplicationContext(),R.drawable.ic_baseline_eco_24));
                    tmpRealTimeMarkers.add(mMap.addMarker(markerOptions));
                }
            }
        } else {
            Log.d(TAG, task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

I just added only the important data.

Related