简体   繁体   中英

How to update marker positions with data from Firebase Google Maps API Android

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.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM