private final HashMap<String, Marker> hm=new HashMap<String, Marker>();
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference userLocationRef = db.child("UserLocation");
db.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
userLocationRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String userID = String.valueOf(ds.child("userID").getValue());
double lat = ds.child("You").child("l").child("0").getValue(Double.class);
double lng = ds.child("You").child("l").child("1").getValue(Double.class);
Log.d("TAG", lat + ", " + lng); //Check the values
Log.d("TAG", userID+"hi"); //Check the values
//Add location on Google Map
LatLng location = new LatLng(lat, lng);
if (hm.containsKey(userID)) {
hm.get(userID).remove();
}
currentLocationMarker = mMap.addMarker(new MarkerOptions().position(location).title(userID));
currentLocationMarker.showInfoWindow();
hm.put(userID, currentLocationMarker);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});}
The above code is used to retrieve multiple users' real-time locations from a real-time firebase. The structure of the real-time firebase is shown below:
When the location of the multiple user's changes, the markers start to update the location of the users, but the problem is when the markers begin to update the new location of users, the old markers of the users were not removed.
The problem happened as the image shown below:
So, the problem is how to remove the old markers of multiple markers, and the map can only show one marker for each user? Thanks if you can help!