【问题标题】:Not able to remove all Annotation from mapview无法从地图视图中删除所有注释
【发布时间】:2013-01-02 05:37:12
【问题描述】:

我在从 MKMapView 中删除注释时遇到问题。我已经搜索过相同的答案并找到了很多答案,但找不到令人满意的答案。以下是我的代码摘要:

我已经创建了我的自定义类作为 MyMapViewPoints 并创建了一个函数作为

- initWithZTitle:(NSString *)title andCoordinate:(CLLocationCoordinate2D)location

每当我想添加注释时,我只需创建一个 MyMapViewPoints 对象和

[mapView addAnnotation:newAnnotation];

当我想删除所有地图视图点(注释)时,我执行以下代码:

for (int i =0; i < [mapView.annotations count]; i++) 
{ 
    if ([[mapView.annotations objectAtIndex:i] isKindOfClass:[MyMapViewPoints class]]) 
    {    
        MyMapViewPoints *obj = (MyMapViewPoints *)[mapView.annotations objectAtIndex:i];
        if(obj.type != 1)
            [mapView removeAnnotation:[mapView.annotations objectAtIndex:i]];
    } 
}

但是一些注释点仍然在地图上。如果我添加了六个点并尝试使用上述代码删除所有点,则保留 2 个地图视图点(注释)。有任何想法吗?

【问题讨论】:

    标签: iphone ios xcode annotations mkmapview


    【解决方案1】:

    试试这段代码……

    NSArray *existingpoints = mapView.annotations;
    if ([existingpoints count] > 0)
        [mapView removeAnnotations:existingpoints];
    

    更新:

    也试试这个代码...

    for (int i =0; i < [mapView.annotations count]; i++) { 
        if ([[mapView.annotations objectAtIndex:i] isKindOfClass:[MyMapViewPoints class]]) {                      
             [mapView removeAnnotation:[mapView.annotations objectAtIndex:i]]; 
           } 
    }
    

    【讨论】:

    • @SangamAngre 在此代码之后,您确定您没有从某处添加引脚并等待我会为此发布一些其他代码..
    • 我正在从一个函数中添加地图视图点,并在地图上添加了一个按钮作为 ClearAll。当我单击此功能时,我正在执行代码。这两个功能仅在同一个 viewController 中。
    • 我想你想删除所有注释而不是 useLocation 你用 1 定义的类型对吗??
    • @SangamAngre 也为您的自定义类尝试此代码 .. 但上面的代码对我来说也很有效,但试试这个..
    • 我想我只在一个条件下使用了相同的代码。并且类型不适用于 userLocation。我有多种类型的注释,以便我可以决定它的阴影效果和外观以及它的用途。
    【解决方案2】:

    将您的数据源数组添加到以下行并删除所有注释

    [yourMapview removeAnnotations:datasourceArray];
    

    【讨论】:

      【解决方案3】:

      您正在修改一个数组,同时还尝试遍历它。在该循环i=0 的第一次迭代期间,如果它与类匹配,则将其从注释中删除。如果您删除索引 0 处的项目,它们都会向上移动 1,因此索引 1 处的项目现在位于索引 0。但是您也将 i 增加 1,并且在下一个循环期间您查看索引 1,完全丢失了现在已移动到索引 0 的项目。

      index 0 1 2 3
      item  A B C D
      

      检查索引 0,删除索引 0 处的项目。

      index 0 1 2
      item  B C D
      

      现在检查 1 处的索引 你已经跳过了 B

      您应该尝试这些解决方案 How to delete all Annotations on a MKMapView

      此外,[yourMapView annotations] 不承诺以任何特定顺序返回它们,因此每次调用它时,索引都可能不同。如果您想通过注释进行任何循环,最好将其保存为 NSArray* 并从那时起引用该副本。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-03
        相关资源
        最近更新 更多