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

爷,独闯天下 提交于 2021-02-04 08:20:11

问题


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


来源:https://stackoverflow.com/questions/47681030/how-to-update-marker-positions-with-data-from-firebase-google-maps-api-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!