【问题标题】:How to link Google Maps Android API v2 Marker to an object如何将 Google Maps Android API v2 Marker 链接到对象
【发布时间】:2013-01-14 01:28:38
【问题描述】:

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

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

你有什么建议?

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

【问题讨论】:

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


    【解决方案1】:

    我建议使用 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 并使用相应的数据做一些事情,例如打开一个带有详细信息的新活动。

    【讨论】:

    【解决方案2】:

    我知道这篇文章很旧,但如果你在 Android Studio 中使用预制地图 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());
                    }
                });
      }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-11
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      • 2013-03-24
      • 2023-04-02
      相关资源
      最近更新 更多