0

我需要检查新创建的 OverlayItem 的数据是否已经存在于地图上已显示的 OverlayItems 列表中。我编写了一个代码来检查 OverlayItem 的数据是否已经存在,但我遇到了错误。如何从 Overlay 中提取 OverlayItem?

我当前的代码是这样的:

//where mapOverlays = mapView.getOverlays() and overlayItem is the newly created overlayItem
public boolean isExisting(List<Overlays> mapOverlays, OverlayItem overlayItem)
{
    ItemizedOverlay overlay;
    OverlayItem itemToCompare;

    for(int i = 0; i < mapOverlays.size(); i++)
    {
        overlay = (ItemizedOverlay)mapOverlays; //I am getting an error here: java.util.Collections$SynchronizedRandomAccessList (from e.getMessage()). The stack trace does not contain any specific exception but only the trace of the error pointing to this line.
        existingOverlayItem = overlay.getItem(i);

        if(itemToCompare.getPoint().equals(overlayItem.getPoint())
            && itemToCompare.getSnippet().equals(overlayItem.getSnippet())
            && itemToCompare.getTitle().equals(overlayItem.getTitle()))
            return true; //if all data are the same
    }

    return false;
}
4

3 回答 3

0

我不知道 MapOverlay, 但您可能无法将 List 放入 MapOverlay

于 2012-02-10T09:59:35.757 回答
0

这段代码看起来有点奇怪。itemToCompare 在哪里?我看不到它在任何地方宣布。如果 itemToCompare 与 overlayItem 是同一个类,为什么不在类中覆盖 equals 并使用它而不是比较每个参数?

更好的是,在 Class 中覆盖 equals 将授予您访问权限:

mapOverlays.contains(overlayItem); 

So your entire isExisting method will be replaced by the call above. You can see more information on how equals work here.

于 2012-02-10T10:15:36.637 回答
0

Thanks all for answering my question. I found out that my problem happens because I'm casting mapOverlays to a wrong class.

Also, instead of extracting OverlayItem from mapOverlays (which I can't find out how), I am just making the validation inside addOverlay(OverlayItem overlayItem). I can't do this before because I am always reinitializing the value of my itemizedOverlay. As such, I can't compare the newly added OverlayItem to the old ones because itemizedOverlay does not hold the old values anymore. What I did is instead of always reinitializing itemizedOverlay, I am just always clearing mapOverlays which equals to mapView.getOverlays().clear().

于 2012-02-13T09:20:00.587 回答