How to link Google Maps Android API v2 Marker to an object

徘徊边缘 提交于 2019-12-03 22:34:11

问题


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 of the markers, I show the rest of the data inside the custom InfoWindow.

What do you suggest?

PS: I add new markers everytime the user pans or zooms the map and I worried about overloading the app. Are the non visible markers disposed?


回答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 displayed
     if(!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.




回答2:


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

In the set up map

  private void setUpMap() {


    Map<String,someObject>markerInfoList = new HashMap<String,someObject>();

  // get the marker Id as String
       String id =  mMap.addMarker(new MarkerOptions().position(new LatLng(/*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 :

  private void setUpMapIfNeeded() {
  ///...
 if (mMap != null) {
   //if a marker is clicked
   mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
                @Override
                public void onInfoWindowClick(Marker marker) {
                    someObject = markerInfoList.get(marker.getId());
                }
            });
  }
 }


来源:https://stackoverflow.com/questions/14310280/how-to-link-google-maps-android-api-v2-marker-to-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!