I have some markers in my google map activity representing some shop locations. I need to write click event for each marker so i can open the corresponding site for each shop. I am using the following code to add markers.
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
for(int i = 0 ; i < shop.size() ; i++ ) {
createMarker(shop.get(i).getLat(), shop.get(i).getLon(), shop.get(i).getShopname(),"", R.drawable.ic_location_city);
}
mMap.setOnMarkerClickListener(ShoppingPage.this);
}
protected Marker createMarker(double latitude, double longitude, String title, String snippet, int iconResID) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 9f));
myMarker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.anchor(0.5f, 0.5f)
.title(title)
.snippet(snippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_city_black_24dp)));
return myMarker;
}
When i am trying to add click listener to the markers i can't add click listener to all of them.I could only add click event to the last added marker . But i need to make click event for every marker in the map. Please help me. This is my code for click event.
public boolean onMarkerClick(final Marker marker) {
if (marker.equals(myMarker))
{
//handle click here
Log.d("title",""+ marker.getTitle());
Log.d("position",""+ marker.getPosition());
}
return true;
}
Use this:
First make your app to implement GoogleMap.OnMarkerClickListener Then create a Marker array :
Marker[] marker = new Marker[20]; //change length of array according to you
then inside
onMapReady(){
mMap.setOnMarkerClickListener(this);
for(int i = 0 ; i < shop.size() ; i++ ) {
marker[i] = createMarker(shop.get(i).getLat(), shop.get(i).getLon(), shop.get(i).getShopname(),"", R.drawable.ic_location_city);
}
then finally
@Override
public boolean onMarkerClick(Marker marker) {
//you can get assests of the clicked marker
return false;
}
Hope it helps!!!