Android Google Maps, how to make each Marker InfoWindow open different Activity?
I use following code segment for display several locations on google map. I get those coordinates as a array. After displaying markers on the map i want to go for a activity after clicking Infowindows of marker. Each infowindow of single marker should have different activity after clicking it. I have 4 markers and i want to access 4 different activities by clicking infowindow. How should i implement this. Thank you
My code of put markers on map
Marker a1 = googleMap.addMarker(new MarkerOptions().position(a)
.title(arr[0])
.snippet(arr[1]) );
Marker b1 = googleMap.addMarker(new MarkerOptions().position(b)
.title(arr[9])
.snippet(arr[10]) );
Marker c1= googleMap.addMarker(new MarkerOptions().position(c)
.title(arr[18])
.snippet(arr[19]));
Marker d1= googleMap.addMarker(new MarkerOptions().position(d)
.title(arr[27])
.snippet(arr[28]));
Solution 1:
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);
}
}
});