Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if mapView already contains an annotation

I have a method of adding secondary nearby annotations (ann2) when I tap on another annotation (ann1). But when I deselect and re-select the exact same annotation (ann1) the ann2 re-creates it self and is getting added again. Is there a way to check if the annotation already exists on the map and if yes then do nothing otherwise add the new annotation. I have already checked this: Restrict Duplicate Annotation on MapView but it did not help me.. Any advice is appreciated. This is what I have so far:

    fixedLocationsPin *pin = [[fixedLocationsPin alloc] init];
        pin.title = [NSString stringWithFormat:@"%@",nearestPlace];
        pin.subtitle = pinSubtitle;
        pin.coordinate = CLLocationCoordinate2DMake(newObject.lat, newObject.lon);

        for (fixedLocationsPin *pins in mapView.annotations) {
            if (MKMapRectContainsPoint(mapView.visibleMapRect, MKMapPointForCoordinate (pins.coordinate))) {
                NSLog(@"already in map");
            }else{
                [mapView addAnnotation:pin];
            }

In this case I get the log already on map but I also get the drop animation of the annotation adding to the map. Any ideas?

Thank you in advance..

like image 412
user1780591 Avatar asked Feb 28 '13 11:02

user1780591


1 Answers

Your for loop isn't checking if the annotation is on the screen, it is checking if the coordinates of the pin are currently within the visible area. Even if it was checking if the pin object was already in the mapView.annotations it would never be true, because you've only just created pin a few lines earlier, it can't possibly be the same object as on in the mapView.annotations. It might though have the same coordinates and title, and that's what you need to check:

bool found = false;
for (fixedLocationsPin *existingPin in mapView.annotations)
{
  if (([existingPin.title isEqualToString:pin.title] && 
       (existingPin.coordinate.latitude == pin.coordinate.latitude)
       (existingPin.coordinate.longitude == pin.coordinate.longitude))
  { 
    NSLog(@"already in map");
    found = true;
    break;
  }
}    
if (!found)
{
    [mapView addAnnotation:pin];
} 
like image 197
Craig Avatar answered Sep 30 '22 07:09

Craig