Search code examples
iphoneiosmkmapviewmkannotationabaddressbook

Adding an unknown number of annotations to MKMapView


So I am using the map to add points for each person that has an address in the contacts, and I am having a bit of a hard time figuring out how to set it up for the unknown number of contacts. right now the way I have it set up, it is only adding a pin for the last contact in the list. here is some code: address is a string that is set from addressProperty.

if(addressProperty != nil)
       {
           [location geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
            NSMutableArray *array = [[NSMutableArray alloc]init];

            for(int a = 0; a < [placemarks count]; a++)
            {

               self.placeMarkData = [placemarks objectAtIndex:a];
                [point setCoordinate: self.placeMarkData.location.coordinate];

                [array addObject:point];
                pin.animatesDrop = YES;
                point.title = address;

                [map addAnnotations:array];
            }
                      }];
    }

So when I run the app I can see the pin being set in each location and moving to the next location until it ends on the last locations in the list. How can I add a point for each? I am sure it is an easy solution, but it is eluding me right now.


Solution

  • There must be a loop around all of this to be going through all the contacts. Is location a CLGeocoder? You shouldn't set two geocodeAddressString functions going on the same geocoder, you'll need to initialize a new one for each geocode your doing (unless you know for sure the previous geocode, which is asynchronous, has finished).

    Four other problems:

    • The point variable is the same one each time. As you change the coordinate you'll that point appear in different places on the map, but it's the same one so you'll never see more than on on the map at any time.
    • Because it is running asynchronously you should be writing and reading a variable outside the block. Right now two geocodes could get responses at the same time and one sets self.placeMarkData just as the other one is reading the location.coordinate from it.
    • What is pin used for?
    • Don't bother adding array to the map until you've finished filling it up. If you want the points on screen asap then add them individually to the map. Adding the entire array, then adding another thing to the array and adding the entire array again is a waste.