Search code examples
iosmkmapviewmapkitmkannotation

Restrict Duplicate Annotation on MapView


How do i restrict duplicate annotation on unique location of latitude and longitude.

When i am adding annotation on map, i can add annotation on one point having same lat and long, for example i add a pin on the map at lat = 37.785834 and long = -122.406417 and name it as Bob's house then next time when i again add a annotation pin at that place and it takes same lat and long and i can save it as Steve House, but it should not happen i want it to show a type of alert that this location has already occupied, choose a different location, so that no lat long should have duplicate entries. This has nothing to do with zoom or anything.

now i want a code to query and check in database whether the user is tapping the annotation at the same latitude and longitude ie, i never want to create a duplicate entry for same lat/long value by checking in the database.....

Example code:

#pragma mark - 
- (void) addSite2 { 
    AddSiteInfoViewController *vc = [[[AddSiteInfoViewController alloc] initWithCoordinate:pinAnnotation.coordinate] autorelease]; 
    [self.delegate pushViewController:vc animated:YES];
}

Solution

  • If the annotation is already shown in the map, you can use the following code (without having to check the database):

    #pragma mark - 
    - (void) addSite2 { 
        NSUInteger index = [self.mapView.annotations indexOfObjectPassingTest:
                            ^BOOL(MKAnnotation *anot1, NSUInteger index, BOOL *stop){
                                return (CLCOORDINATES_EQUAL( anot1.coordinate, pinAnnotation.coordinate));
                        }];
        if (index == NSNotFound)
        {
            AddSiteInfoViewController *vc = [[[AddSiteInfoViewController alloc] initWithCoordinate:pinAnnotation.coordinate] autorelease]; 
            [self.delegate pushViewController:vc animated:YES];
        }
    }
    

    (Mostly written on top of my head, so a typo or minor error could exist.)

    If, in fact, the annotation is not shown... use the solution given in the comments by Rajneesh071: Extracting Unique Objects from a Data Array