如何将Google Maps Android API v2标记链接到对象

时间:2013-01-14 01:28:39

标签: android google-maps-android-api-2

我在地图中动态添加非固定数量的标记,每个标记都与我的POCO类的一个实例相关。

我需要链接它们,以便当用户点击其中一个标记时,我会在自定义InfoWindow中显示其余数据。

你有什么建议?

PS:我每次用户平移或缩放地图时添加新标记,我担心应用程序过载。是否放置了不可见标记?

2 个答案:

答案 0 :(得分:5)

我建议使用HashMap或类似的东西。当您遍历对象列表并为它们创建标记时,还要将标记添加到列表中,使用对象的ID作为键,将标记作为值:

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)));
     }
}

然后,您可以使用OnInfoWindowClickListener在地图中查找点击标记的对象ID,并使用相应的数据执行某些操作,例如打开包含详细信息的新活动。

答案 1 :(得分:0)

我知道这篇文章很旧,但是如果你在Android工作室使用预制地图Activity

在设置地图

  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));     
}

然后在:

  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());
                }
            });
  }
 }