How to update marker positions with data from Fire

2019-02-28 12:52发布

问题:

I'm creating an app that makes a real time tracking of users using Firebase Database. Every user is displayed in the map using markers.

When there is a new location update, the marker has to be updated. The problem is that with Firebase method onDataChange() or similars every time a new location update is retrieved, I can't access to the old marker to remove it and create a new one or just update the old marker, because the marker doesn't exist.

I tried it saving markers in SharedPreferences using Gson, but when I pass the marker to json, the app crashes.

Does anyone know how can I update the markers?

This is written inside the onDataChange():

           for (User user: usersList) {
                Gson gson = new Gson();

                /*
                String previousJson = preferences.getString(user.getId()+"-marker", "");
                Marker previousMarker = gson.fromJson(previousJson, Marker.class);
                if (previousMarker!=null) markerAnterior.remove();
                */

                final LatLng latlng = new LatLng(user.getLastLocation().getLatitude(), user.getLastLocation().getLongitude());

                MarkerOptions markerOptions = new MarkerOptions()
                        .position(latlng)
                        .title(user.getId());

                Marker marker= mMap.addMarker(markerOptions);

             //   String newJson = gson.toJson(marker); //CRASH
            //    editor.putString(user.getId()+"-marker", newJson);
            //    editor.commit();

            }

Thank you.

回答1:

Create a HashMap instance variable that will map user IDs to Markers:

private Map<String, Marker> mMarkerMap = new HashMap<>();

Then, populate new Markers in the HashMap so you can retrieve them later.

If the Marker already exists, just update the location:

for (User user : usersList) {

    final LatLng latlng = new LatLng(user.getLastLocation().getLatitude(), user.getLastLocation().getLongitude());

    Marker previousMarker = mMarkerMap.get(user.getId());
    if (previousMarker != null) {
        //previous marker exists, update position:
        previousMarker.setPosition(latlng);
    } else {
        //No previous marker, create a new one:
        MarkerOptions markerOptions = new MarkerOptions()
                .position(latlng)
                .title(user.getId());

        Marker marker = mMap.addMarker(markerOptions);

        //put this new marker in the HashMap:
        mMarkerMap.put(user.getId(), marker);
    }
}