android - 谷歌地图实用程序 : how to get all markers from ClusterManager<? >?

标签 android google-maps-android-api-2 marker markerclusterer

对不起我的英语

我尝试了 ClusterManager<?>.getMarkerCollection().getMarkers()方法,但它返回空集合。

我在我的应用程序中使用 Google Maps Utility Library .每次屏幕旋转后,我都会创建AsynkTask并在后台线程中从数据库中读取数据并将项目添加到 ClusterManager :

cursor.moveToFirst();
while (!cursor.isAfterLast()) {
    SomeData row = readSomeDataRow(cursor);
    clusterManager.addItem(new ClusterItemImpl(row));
    cursor.moveToNext();
}

AsyncTask完成它的工作(即在主线程中)我试图从 ClusterManager 中获取所有标记:

clusterManager.cluster();
// cluster manager returns empty collection  \|/
markers = clusterManager.getMarkerCollection().getMarkers(); 

但是ClusterManager返回空集合。

可能是我打电话的时候getMarkers() ClusterManager但不会在 map 上放置标记,稍后会做(可能在后台线程中)。如果是这样,那我怎么才能捕获那一刻呢?

最佳答案

我会给你一个很好的解决方法。首先,我将介绍一些背景。然后,我将告诉您修改代码的非常简单的方法。

背景:我们先从库代码看一下ClusterManager.addItem的实现:

public void addItem(T myItem) {
    this.mAlgorithmLock.writeLock().lock();

    try {
        this.mAlgorithm.addItem(myItem);
    } finally {
        this.mAlgorithmLock.writeLock().unlock();
    }

}

如您所见,当您调用 clusterManager.addItem 时,ClusterManager 会调用 this.mAlgorithm.addItem。 mAlgorithm 是您的项目存储的地方。现在让我们看看 ClusterManager 的默认构造函数:

public ClusterManager(Context context, GoogleMap map, MarkerManager markerManager) {
    ...
    this.mAlgorithm = new PreCachingAlgorithmDecorator(new  NonHierarchicalDistanceBasedAlgorithm());
    ...        
}

mAlgorithm 被实例化为包含 NonHierarchicalDistanceBasedAlgorithm 的 PreCachingAlgorithmDecorator。不幸的是,由于 mAlgorithm 被声明为私有(private)的,我们无法访问正在添加到算法中的项目。但是,很高兴有一个简单的解决方法!我们只需使用 ClusterManager.setAlgorithm 实例化 mAlgorithm。这允许我们访问算法类。

解决方法:这是您的代码,其中插入了解决方法。

  1. 将此声明与您的类变量放在一起:

    private Algorithm<Post> clusterManagerAlgorithm;
    
  2. 在您实例化您的 ClusterManager 的地方,紧接其后放置:

     // Instantiate the cluster manager algorithm as is done in the ClusterManager
     clusterManagerAlgorithm = new NonHierarchicalDistanceBasedAlgorithm();
    
     // Set this local algorithm in clusterManager
     clusterManager.setAlgorithm(clusterManagerAlgorithm);
    
  3. 您可以保留将项目插入集群的代码完全相同。

  4. 当您想访问插入的项目时,您只需使用算法而不是 ClusterManager:

    Collection<ClusterItemImpl> items = clusterManagerAlgorithm.getItems();
    

这将返回项目而不是标记对象,但我相信这是您需要的。

关于android - 谷歌地图实用程序 : how to get all markers from ClusterManager<? >?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22449438/

相关文章:

android - Android 是否支持同时多个 HTTP 请求?

angular - 如何将 map 设置为以标记为中心? - Angular 谷歌地图

android - 在android中更新 map 标记

android - Google Maps API v2 在 MapFragment 上绘制部分圆圈

android,从googlemap上的位图添加标记

android - onLocationChanged() 被调用太多次,即使设备没有移动

java - 通过谷歌地图中的 id 删除一组标记

android - 将 Jelly Bean 启动器移植到 GingerBread

android - 如何安装谷歌 repo ?

Android,保存图片在 'App Container'