Search code examples
androidandroid-mapsgoogle-maps-android-api-2

Associate an object with Marker (google map v2)


In my app I have some objects that have their location displayed on the map using markers. The problem is that the only way I've found to handle marker clicks is

googleMap.setOnMarkerClickListener(new ... {
    @Override
    public void onMarkerClick(Marker marker) {
       // how to get the object associated to marker???
    }
})

In other words I get the Marker object while the only interface that I have allows me to set just MarkerOptions.

Any way to associate Marker with an object?


Solution

  • You can associate arbitrary object by using Marker's setTag() method

    Marker amarker = mMap.addMarker(new MarkerOptions().position(lat, lng).title("Hello World"));
    amarker.setTag(new SomeData());
    

    To retrieve data associated with marker, you simply read it using its getTag() and then cast it to its original type.

    SomeData adata = (SomeData) amarker.getTag();
    

    More information