32

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?

leshka
  • 1,764
  • 6
  • 32
  • 42

3 Answers3

54

I reckon this callback was not very thoroughly though by the Android team, but, it's what we have.

Whenever you call mMap.addMarker(); it returns the generated marker. You can then use a HashMap or some other data holder structure to remember it.

// Create the hash map on the beginning
WeakHashMap <Marker, Object> haspMap = new WeakHashMap <Marker, Object>();


// whenever adding your marker
Marker m = mMap.addMarker(new MarkerOptions().position(lat, lng).title("Hello World").icon(icon_bmp));
haspMap.put(m, your_data);
Budius
  • 39,391
  • 16
  • 102
  • 144
  • 8
    I recommend `WeakHashMap`, so when a `Marker` gets garbage-collected, so will its associated `WeakHashMap` entry and `Object` value. But, yes, unfortunately this seems to be the only option at present. – CommonsWare Dec 27 '12 at 12:25
  • 1
    makes sense to me. I edited my answer to be WeakHashMap. Is that ok? – Budius Dec 27 '12 at 12:28
  • 5
    bzzzzt, wrong! I had to use an HashMap, otherwise the mapping gets somehow garbage collected. – dwery Aug 31 '13 at 01:57
  • 11
    The documentation says that marker object may change, so don't use the marker as the key, use m.getId(). – dwery Aug 31 '13 at 02:05
  • hi @dwery , I can't find that on the documentation. Could you point to a link, please? – Budius Dec 18 '13 at 10:50
  • @dwery If you do so, you have no chance to remove the marker because you don't have the reference. – DarkLeafyGreen Sep 24 '14 at 11:35
  • @CommonsWare unless you use this WeakHashMap throughout the app it is not useful for this purpose. – Rafael Nov 16 '16 at 14:04
36

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

Zamrony P. Juhara
  • 5,222
  • 2
  • 24
  • 40
8

Another option would be to create a Map whose keys is marker.getId() and the value is our object.

In this way, we wouldn't keep a reference to a Marker in memory, and wouldn't have to worry about garbage collected markers.

Here you can see more answers.

Community
  • 1
  • 1
Sanete
  • 621
  • 1
  • 6
  • 4