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=new ArrayList();

Then use list like this:

@Override
      public void onChildChanged(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:

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

At last do this:

private void updateShowing(final boolean isShow) {

    removeStudentMarkers();

    FirebaseDatabase.getInstance().getReference().child("Students")
        .addListenerForSingleValueEvent(new ValueEventListener() {
          @Override
          public void onDataChange(DataSnapshot snapshot) {
            for (DataSnapshot ds : snapshot.getChildren()) {
              ds.child("show").getRef().setValue(isShow);
            }
          }

          @Override
          public void onCancelled(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(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))));
}

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