Android Google Maps, how to make each Marker InfoWindow open different Activity?

Use a HashMap to store the marker ID and it’s corresponding identification of which Activity it should open.

Then, use a OnInfoWindowClickListener to get the event of a user clicking the info window, and use the HashMap to determine which Activity to open.

Declare the HashMap as an instance variable:

//Declare HashMap to store mapping of marker to Activity
HashMap<String, String> markerMap = new HashMap<String, String>();

Then, each time you add a Marker, make an entry in the HashMap:

        String id = null;

        Marker a1 = googleMap.addMarker(new MarkerOptions().position(a)
                .title(arr[0])
                .snippet(arr[1]));

        id = a1.getId();
        markerMap.put(id, "a1");

        Marker b1 = googleMap.addMarker(new MarkerOptions().position(b)
                .title(arr[9])
                .snippet(arr[10]));

        id = b1.getId();
        markerMap.put(id, "b1");

        Marker c1= googleMap.addMarker(new MarkerOptions().position(c)
                .title(arr[18])
                .snippet(arr[19]));

        id = c1.getId();
        markerMap.put(id, "c1");

        Marker d1= googleMap.addMarker(new MarkerOptions().position(d)
                .title(arr[27])
                .snippet(arr[28]));

        id = d1.getId();
        markerMap.put(id, "d1");
    }

And then define the info window click listener:

    googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {

            String m = markerMap.get(marker.getId());

            if (m.equals("a1")){
                Intent i = new Intent(MainActivity.this, ActivityA1.class);
                startActivity(i);
            }
            else if (m.equals("b1")){
                Intent i = new Intent(MainActivity.this, ActivityB1.class);
                startActivity(i);
            }
            else if (m.equals("c1")){
                Intent i = new Intent(MainActivity.this, ActivityC1.class);
                startActivity(i);
            }
            else if (m.equals("d1")){
                Intent i = new Intent(MainActivity.this, ActivityD1.class);
                startActivity(i);
            }
        }
    });

Leave a Comment