3

My database enter image description here

In the above tree I have stored the current latitude and longitude of the driversAvailable. If there are multiple drivers present under driversAvailable tree then how can I show all of them on the map? I have written following code till now and it isn't working:

private DatabaseReference driverLoadLocationRef;
private ValueEventListener driverLoadLocationRefListener;
private void loadAllAvailableDrivers() {
    DatabaseReference driverLoading = FirebaseDatabase.getInstance().getReference().child("driversAvailable");
    GeoFire geoDriver = new GeoFire(driverLoading);
    GeoQuery geoQueryDriver = geoDriver.queryAtLocation(new GeoLocation(mLastLocation.getLatitude(),mLastLocation.getLongitude()),distance);
    geoQueryDriver.removeAllListeners();
    geoQueryDriver.addGeoQueryEventListener(new GeoQueryEventListener() {
        @Override
        public void onKeyEntered(final String key, GeoLocation location) {
            if (!driverLoad ) {
                driverLoad = true;
                driverLoadId = key;
                driverLoadLocationRef = FirebaseDatabase.getInstance().getReference().child("driversAvailable").child(driverFoundId).child("l");
                driverLoadLocationRefListener = driverLoadLocationRef.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        if (dataSnapshot.exists() ) //If doesnot exist check then app will crash
                        {
                            List<object> map = (List<object>) dataSnapshot.getValue();
                            double locationLoadLat = 0;
                            double locationLoadLng = 0;
                            if (map.get(0) != null)
                            {
                                locationLoadLat = Double.parseDouble(map.get(0).toString());
                            }
                            if (map.get(1) != null)
                            {
                                locationLoadLng = Double.parseDouble(map.get(1).toString());
                            }
                            LatLng driverLoadLatLng = new LatLng(locationLoadLat,locationLoadLng);
                            if (mDriverMarker != null) //If not added app crash since it will try to remove which doesnot exist
                            {
                                mDriverMarker.remove();
                            }
                            mDriverMarker = mMap.addMarker(new MarkerOptions().position(driverLoadLatLng).flat(true)
                                    .title(driverLoadId)
                                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.car3)));
                        }
                    }
                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        Toast.makeText(PassengerMapsActivity.this,"Failed",Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
        @Override
        public void onKeyExited(String key) {
        }
        @Override
        public void onKeyMoved(String key, GeoLocation location) {
        }
        @Override
        public void onGeoQueryReady() {
            if (distance <= LIMIT)
            {
                distance++;
                loadAllAvailableDrivers();
            }
        }
        @Override
        public void onGeoQueryError(DatabaseError error) {
        }
    });
}
Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77
  • i think you are not loading properly your latitude and longitude at .position – Gastón Saillén Mar 16 '18 at 20:33
  • Sir, can you tell me where is the problem in the code part, because the latitude and longitude positions are on the database but I am unable to represent it on the map. – Prakash Kumar Mar 16 '18 at 21:14
  • Doesn't seem like you are using GeoFire correctly. The 'onKeyEntered' method will be invoked for each driver that satisfies the query - and the 'location' parameter is the location of that driver so no need to requery for it. In your example, the 'driversAvailble' node tree is an area managed by Geofire and you don't normally access it directly - but obviously you _could_ since it is accessible. –  Mar 17 '18 at 23:58

1 Answers1

0

i think i have simpler way of implementing that!

Create a Marker array, Initialize the array with the number of entries(childrenCount) onDataChange. After that, embed another for..loop inside 'for(DataSnapshot ds : dataSnapshot.getChildren())' that iterates over the number of entries(childrenCount) found.

I assume you have a Model class that was used to push data to firebase. Use it to retrieve the specific cordinates. Av decided to replace your '0' and '1' to 'lat' and 'lon'.

private void loadAllAvailableDrivers() {
DatabaseReference driverLoading = FirebaseDatabase.getInstance().getReference("driversAvailable");
driverLoading.addValueEventListener(new ValueEventListener() {
    @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //trying to get several markers
            //Create an array and specify a size which will be initialized to children(driver) count
            int size = (int) dataSnapshot.getChildrenCount(); //
            Marker[] allMarkers = new Marker[size];
            map.clear();
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
               //Specify your model class here
                ModelClass modelObject=new ModelClass();
                //lets create a loop
                 for(int i=0;i<=size;i++) {
                    try {
                        //am assuming the model class uses variable 'lat',lon,name
                         modelObject.setLat(ds.getValue(ModelClass.class).getLat());
                         modelObject.setLon(ds.getValue(ModelClass.class).getLon());
                         modelObject.setName(ds.getValue(ModelClass.class).getName());

                        //lets retrieve the coordinates and store them in a variable
                        String myName=modelObject.getName();
                        Double latitude = Double.parseDouble(modelObject.getLat());
                        Double longitude = Double.parseDouble(modelObject.getLon());

                        //convert the coordinates to LatLng
                        LatLng latLng = new LatLng(latitude, longitude);
                        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

                        //Now lets add updated markers
                        //lets add updated marker
                     allMarkers[i] = map.addMarker(new MarkerOptions()
                             .icon(BitmapDescriptorFactory.fromResource(R.drawable.car3)).position(latLng).title(myName));
                 }catch (Exception ex){}
                 }


           }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Toast.makeText(PassengerMapsActivity.this,"Failed",Toast.LENGTH_SHORT).show();

        }
    });
 }