declare your markers as fields, instead of local varaibles
Marker cmumarker , adminmarker, casmarker; // You can also keep the ids String cmumarkerId , adminmarkerId, casmarkerID; public void addMarkersToMap() { cmumarker = map.addMarker(new MarkerOptions() .position(cmu) .title("Central Mindanao University") .snippet("Population: 6,143")); cmumarker.showInfoWindow(); cmumarkerId=cmumarker.getID(); adminmarker = map.addMarker(new MarkerOptions() .position(admin) .title("Central Mindanao University Administration Building") .snippet("Population: 1,234") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))); adminmarkerId=adminmarker.getID(); casmarker = map.addMarker(new MarkerOptions() .position(cas) .title("College of Arts and Sciences") .snippet("Population: 1,234") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))); casmarkerId=casmarker.getID(); }
set the click listener to the markers, for example after you create the map, or at the end of
addMarkersToMap()
map.setOnMarkerClickListener(this);
override the
onMarkerClick(Marker marker)
function, and make your decisions@Override public boolean onMarkerClick(Marker marker) { if (marker.getId().equals(cmumarkerId)) { //do whatever you want return true; } if (marker.getId().equals(adminmarkerId)) { //do whatever you want return true; } if (marker.getId().equals(casmarkerId)) { //do whatever you want return true; } return false; }
Also, if you want the info window to be clicable, instead of the marker, you
- overrride the
public void onInfoWindowClick(Marker marker)
instead of the onMarkerClick - asign the listener by means of
map.setOnInfoWindowClickListener(this);
instead of map.setOnMarkerClickListener(this);
UPDATE:
If you have many markers, you can look for a better way of keeping the ids. Some people uses to compare directly the marker, by reference(ie. if (marker==adminmarker{...}) but sometimes it happens to be diferent objects with the same values, so the id is the most secure way of comparing them.