Skip to content Skip to sidebar Skip to footer

Controlling Marker Visibility In Real-time Via Firebase

So I have students showing in the map and each one has show boolean value. I'm using this value to determine if the marker should show or not on the map using setVisible() method.!

Solution 1:

you have to remove markers before updating markers.Create a ArrayList to save Markers references.

ArrayList<Marker> studentMarkersList=newArrayList();

Then use list like this:

@Override
      publicvoidonChildChanged(DataSnapshot snapshot, String s) {

       LatLng latLng = new LatLng(snapshot.getValue(TestUserStudent.class).getLat(), 
       snapshot.getValue(TestUserStudent.class).getLang());
       boolean show = snapshot.getValue(TestUserStudent.class).isShow();

       if(show)
        {
             studentMarker = googleMap.addMarker(new MarkerOptions()
            .position(latLng)
            .title(item.getValue(TestUserStudent.class).getName() + "")
            .snippet(item.getValue(TestUserStudent.class).getSection() + "")
            .icon(BitmapDescriptorFactory.fromBitmap(
             getMarkerBitmapFromView(item.getValue(TestUserStudent.class)
              .getImg(), R.drawable.redMarker))));
             studentMarkersList.add(studentMarker);
        }



      }

Then define a method to remove markers:

privatevoidremoveStudentMarkers()
            {
                for(int i=0;i<studentMakersList.size();i++)
                {
                    studentMarkersList.get(i).remove();
                }
            }

At last do this:

privatevoidupdateShowing(final boolean isShow) {

    removeStudentMarkers();

    FirebaseDatabase.getInstance().getReference().child("Students")
        .addListenerForSingleValueEvent(newValueEventListener() {
          @OverridepublicvoidonDataChange(DataSnapshot snapshot) {
            for (DataSnapshot ds : snapshot.getChildren()) {
              ds.child("show").getRef().setValue(isShow);
            }
          }

          @OverridepublicvoidonCancelled(DatabaseError error) {
            Log.i( "onCancelled: ", error.getDetails() +"\n "+ error.getMessage());
          }
        });
    }

Solution 2:

Just do not create the marker when show == false on your onChildChanged method :

if (show) {
    studentMarker = googleMap.addMarker(newMarkerOptions()
    .position(latLng)
    .title(item.getValue(TestUserStudent.class).getName() + "")
    .snippet(item.getValue(TestUserStudent.class).getSection() + "")
    .icon(BitmapDescriptorFactory.fromBitmap( getMarkerBitmapFromView(item.getValue(TestUserStudent.class) .getImg(), R.drawable.redMarker))));
}

Post a Comment for "Controlling Marker Visibility In Real-time Via Firebase"