Search code examples
androidandroid-maps-v2infowindowmarkerdialogfragment

Dialog Fragment for each Map Marker in Google Maps?


I have a dialog fragment that is opened through an InfoWindowClickListener in google maps. I need a unique dialog fragment for each marker on the map. The dialog fragments are created as follows, for each place, in a loop sequentially:

public PlaceMarker(Place place) {
            this.place = place;
            this.marker = map.addMarker(new MarkerOptions()
                    .position(place.getLocation())
                    .title(this.place.getName())
                    .snippet(place.getInfo()));
            mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
                @Override
                public void onInfoWindowClick(Marker marker) {
                    FragmentManager manager = getFragmentManager();
                    //restdialog = RestaurantDialog.newInstance(place);
                    RestaurantDialog restdialog = new RestaurantDialog();
                    Bundle args = new Bundle();
                    args.putSerializable("place", place);
                    restdialog.setArguments(args);
                    restdialog.setTargetFragment(DefaultMap.this, 0);
                    restdialog.show(manager, place.getName());
                }
            });
        }

The problem that I am having is that, while the marker info windows are all exactly as I expect (each place has its own details above it), the dialog fragment for every marker click shows up as the most recently created dialog fragment (let me know if this does not make sense). Ie, if I create a placemarker for the following places, in this order: Baltimore, Philadelphia, Washington DC, the info windows for Baltimore, Philadelphia, and Washington DC will have the correct info window for each place when you click their markers, but upon clicking the info window you would only see the dialog fragment for Washington DC for all 3 places.

EDIT: I add the places from the for loop through this chunk of code, which takes the place and creates a new restaurantmarker for each place:

public void addPlace(Place place) {
    this.places.add(place); //this.places is a List<Place>
    this.markerBank.put(place, new PlaceMarker(place)); //this.markerBank is a HashMap <Place, PlaceMarker>
}

Solution

  • Your problem is that you are storing the last place in a variable called Place with this line:

    this.place = place;
    

    When your onInfoWindowClick fires, it uses the value in that variable. You need to have a list of places and associate each place with each marker. Use a HashMap for that. Something like:

    HashMap<Place, Marker> myList = new HashMap<>();
    

    I hope this helps.