So I’m pulling my hair out over this one. I’ve been tracking down a bug in my app. Originally, I was trying to load long / lat coordinates from a database and do a for loop, adding each annotation to the map view. This seemed simple enough, but for some reason when I tried to add the annotations in the loop it would only show 1 annotation in the end.
So, using the code below, I decided to try and simply add two annotations to MKMapView to be sure that I can do this in the first place, and it doesn’t work!
[NewAnnotation setLongitude:-104.6200448];
[NewAnnotation setLongitude:50.4908343];
NewAnnotation *newAnnotation = [[NewAnnotation alloc] init];
[self.mapAnnotations insertObject:newAnnotation atIndex:0];
[newAnnotation release];
[CelebsAnnotation setLongitude:-90.6200448];
[CelebsAnnotation setLatitude:51.4908343];
CelebsAnnotation *celebsAnnotation = [[CelebsAnnotation alloc] init];
[self.mapAnnotations insertObject:celebsAnnotation atIndex:1];
[celebsAnnotation release];
[self.mapView addAnnotations:mapAnnotations];
The annotations show up in their correct locations if I only add one of them to the mapAnnotations array (I have to adjust the index to 0 if I only add the CelebsAnnotation), but when I try to add both, they show up in the same location on the map!? Any ideas as to why this would happen? I am so confused and frustrated..
Your problem is here,
You are creating a new
CLLocationCoordinate2Devery timecoordinateis requested an you are setting this to the static variablesClongitude & Clatitude. Since these are static variables, you will be returning similarCLLocationCoordinate2Dobjects for all instances ofCelebsAnnotation. So basically all instances will have the same coordinate.You should rather have an
init..method that takes in aCLLocationCoordinate2Dobject and set it to an instance variable. For example, look atthis tutorial.You will end up doing something like this,