Skip to content Skip to sidebar Skip to footer

How To Link Google Maps Android Api V2 Marker To An Object

I'm adding dynamically a non-fixed amount of markers in a map, which each of them are related to one instance of my POCO class. I need to link them so when the user clicks on one o

Solution 1:

I suggest using a HashMap or something similar. As you iterate over your list of objects and create markers for them, also add the Marker to a list, using the ID of the object as the key, and the marker as the value:

private HashMap<Integer, Marker> markerMap = new HashMap<Integer, Marker>();

...

for(MarkerObject obj : this.markerObjects)
{
     //If the marker isn't already being displayedif(!markerMap.containsKey(obj.getId()))
     {
         //Add the Marker to the Map and keep track of it this.markerMap.put(obj.getId(), this.mMap.addMarker(getMarkerForObject(obj)));
     }
}

Then you can use a OnInfoWindowClickListener to find the object id of the tapped marker in your Map and do something with the corresponding data, like open a new activity with details.

Solution 2:

I know this post is old, but if you are using the prefab map Activity in Android studio

In the set up map

privatevoidsetUpMap() {


    Map<String,someObject>markerInfoList = newHashMap<String,someObject>();

  // get the marker Id as StringString id =  mMap.addMarker(newMarkerOptions().position(newLatLng(/*set Latitude*/,  /*setLongitude*/).title("Marker")).getId();
       //add the marker ID to Map this way you are not holding on to  GoogleMap object
        markerInfoList.put(id,mapppedHouses.get(i));     
}

Then in the :

privatevoidsetUpMapIfNeeded() {
  ///...if (mMap != null) {
   //if a marker is clicked
   mMap.setOnInfoWindowClickListener(newGoogleMap.OnInfoWindowClickListener() {
                @OverridepublicvoidonInfoWindowClick(Marker marker) {
                    someObject = markerInfoList.get(marker.getId());
                }
            });
  }
 }

Post a Comment for "How To Link Google Maps Android Api V2 Marker To An Object"