user1923613
user1923613

Reputation: 636

What's a typical way to identify markers and get the Object associated with it?

I'm using a map in one of my applications. I'd like to know what's a common/efficient way to get the associated Object of a marker when it is tapped.

What I've been planning to day is something like this:

First, I create an ArrayList of my Objects and a HashMap of those Objects using the markers returned by mMap.addMarker(...); as the index.

ArrayList<MyObject> items = new ArrayList<MyObject>();
HashMap<Marker, MyObject> markersAndObjects = new HashMap<Marker, MyObject>();

Now, I override onMarkerClick() like so

public boolean onMarkerClick(Marker clickedMarker) {
    // send the object returned by markersAndObjects.get(clickedMarker) for processing
    return false;
}

Any thoughts on this?

Upvotes: 2

Views: 3638

Answers (1)

azertiti
azertiti

Reputation: 3150

The recommended way to do this is to have a Hash with marker ID and your custom data. The Marker object might change if the activity is killed and restored but the ID will remain the same. You map would look like:

HashMap<String, MyObject> markersAndObjects = new HashMap<String, MyObject>();

Marker objects have a getId() method to get the ID.

[Later Edit]

As of August 2016 there is a new API and HashMap is no longer needed. See https://developers.google.com/android/reference/com/google/android/gms/maps/model/Marker.html#setTag(java.lang.Object)

Upvotes: 9

Related Questions