Google Maps API v2: How to make markers clickable?

Malaka picture Malaka · Jan 9, 2013 · Viewed 166.2k times · Source

How to I make the markers in Android Google Maps API v2 become clickable so they will either bring up a menu with options or just start a new activity? I believe I made the markers in my app currently in a "newb" method. I didn't assign them a name or a method to be able to link it in with the rest of the required code.

googleMap.addMarker(new MarkerOptions()
        .position(latLng)
        .title("My Spot")
        .snippet("This is my spot!")
        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));

If you ANSWER this, please include a sample code of a marker being introduced with a unique name and then being set as clickable to open a new activity.

Answer

Pavel Dudka picture Pavel Dudka · Jan 9, 2013

All markers in Google Android Maps Api v2 are clickable. You don't need to set any additional properties to your marker. What you need to do - is to register marker click callback to your googleMap and handle click within callback:

public class MarkerDemoActivity extends android.support.v4.app.FragmentActivity
    implements OnMarkerClickListener
{
    private Marker myMarker;    

    private void setUpMap()
    {
        .......
        googleMap.setOnMarkerClickListener(this);

        myMarker = googleMap.addMarker(new MarkerOptions()
                    .position(latLng)
                    .title("My Spot")
                    .snippet("This is my spot!")
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
        ......
    }

    @Override
    public boolean onMarkerClick(final Marker marker) {

        if (marker.equals(myMarker)) 
        {
            //handle click here
        }
    }
}

here is a good guide on google about marker customization