Do not insert repeated annotations on the map

2
I'm inserting some annotations that are coming from a JSON server, but I wanted to check if annotation is already on the map, if so, do not add it again . For they are being added one over the other. Can someone help me solve this problem?

My code adding the pins :

  // adiciona produtos ao mapa
    - (void)adicionaAnnotationsNoMapa:(id)objetos{
        NSMutableArray *annotationsPins = [[NSMutableArray alloc] init];

        for (NSDictionary *annotationDeProdutos in objetos) {
            CLLocationCoordinate2D location;
            AnnotationMap *myAnn;
            myAnn = [[AnnotationMap alloc] init];
            location.latitude = [[annotationDeProdutos objectForKey:@"latitude"] floatValue];
            location.longitude = [[annotationDeProdutos objectForKey:@"longitude"] floatValue];
            myAnn.coordinate = location;
            myAnn.title = [annotationDeProdutos objectForKey:@"name"];
            myAnn.subtitle = [NSString stringWithFormat:@"R$ %@",[annotationDeProdutos objectForKey:@"price"]];
            myAnn.categoria = [NSString stringWithFormat:@"%@", [annotationDeProdutos objectForKey:@"id_categoria"]];
            myAnn.idProduto = [NSString stringWithFormat:@"%@", [annotationDeProdutos objectForKey:@"id"]];
            [annotationsPins addObject:myAnn];
        }

        [self.mapView addAnnotations:annotationsPins];
    }
    
asked by anonymous 08.04.2015 / 05:22

1 answer

1

Within this iteration for you do, shortly after assigning the latitude and longitude values, you can use something as a block for this, so doing the comparison based on the distance between the coordinate to be inserted with those that already exist in the array .

Something like this:

__block NSInteger foundIndex = NSNotFound;

[annotationsPins enumerateObjectsUsingBlock:^(AnnotationMap *annotation, NSUInteger idx, BOOL *stop) {
    CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:location.latitude longitude:location.longitude];
    CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];

    if ([loc1 distanceFromLocation:loc2] <= 5.0f) {
        foundIndex = idx;
        *stop = YES;
    }
}];

if (foundIndex != NSNotFound) {
    // Achou coordenada, não faz as linhas abaixo
    continue;
}

// Prossegue iteração

What happens here is this: you use the enumerate block to scour your annotationsPins array and look for some coordinate that is less than 5 meters from the current coordinate ( loc1 ). If so, you break the block and continue.

If foundIndex is different from NSNotFound , it means that it found similar coordinates, so you do not have to continue what you have in for down.

    
08.04.2015 / 14:17