Associate an object with Marker (google map v2)

2020-02-17 09:15发布

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?

3条回答
够拽才男人
2楼-- · 2020-02-17 09:25

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.

查看更多
Melony?
3楼-- · 2020-02-17 09:29

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);
查看更多
等我变得足够好
4楼-- · 2020-02-17 09:31

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

查看更多
登录 后发表回答