user984248
user984248

Reputation: 149

Multiple Pins on Map using data from Plist

I am trying to show multiple pins on a map using latitude and longitude from an array of dictionaries. The problem is it is only showing the pin for the last dictionary in the plist always.

Here is the method I have:

- (void)loadMapPins
{
MapAnnotation *annotation = [[MapAnnotation alloc] init];

for (int i=0; i<self.dataDictionary.count; i++){

    NSDictionary *dictionary = [NSDictionary dictionaryWithDictionary:[self.dataDictionary objectAtIndex:i]];

    double latitude = [[dictionary objectForKey:@"Latitude"] doubleValue];
    double longitude = [[dictionary objectForKey:@"Longitude"] doubleValue];

    CLLocationCoordinate2D coord = {.latitude =
        latitude, .longitude =  longitude};
    MKCoordinateRegion region = {coord};

    annotation.title = [dictionary objectForKey:@"Name"];
    annotation.subtitle = [dictionary objectForKey:@"Center Type"];
    annotation.coordinate = region.center;
    [mapView addAnnotation:annotation];
    }
}

I need it to go through the loop and drop the pins on the map accordingly. Any help/examples are appreciated.

Upvotes: 0

Views: 820

Answers (1)

Scott Heaberlin
Scott Heaberlin

Reputation: 3424

I think you want to move your annotation creation into your loop. From the looks of things you only created one, then in the loop you mutate it over and over again. When the loop completes, the last modification to your annotation variable reflects the last item in self.dataDictionary that you are iterating.

The code below creates a new annotation object each loop iteration.

- (void)loadMapPins
{

    for (int i=0; i<self.dataDictionary.count; i++){

    NSDictionary *dictionary = [NSDictionary dictionaryWithDictionary:[self.dataDictionary objectAtIndex:i]];

    double latitude = [[dictionary objectForKey:@"Latitude"] doubleValue];
    double longitude = [[dictionary objectForKey:@"Longitude"] doubleValue];

    CLLocationCoordinate2D coord = {.latitude =
        latitude, .longitude =  longitude};
    MKCoordinateRegion region = {coord};

    MapAnnotation *annotation = [[MapAnnotation alloc] init];
    annotation.title = [dictionary objectForKey:@"Name"];
    annotation.subtitle = [dictionary objectForKey:@"Center Type"];
    annotation.coordinate = region.center;
    [mapView addAnnotation:annotation];
    }
}

Hope this helps,

Scott H

Upvotes: 1

Related Questions