To change the coordinate of an annotation without deleting, re-creating and adding it again, create an annotation class in which the coordinate property will be set. An easy way to do this is to define the coordinate property as follows:
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
Alternatively, instead of defining your own class, you can also use the built-in MKPointAnnotation class, which has a custom coordinate .
First you create and add annotations as usual. For instance:
MKPointAnnotation *pa = [[MKPointAnnotation alloc] init]; pa.coordinate = someCoordinate; pa.title = @"User1"; [mapView addAnnotation:pa]; [pa release];
Later, when you receive an update from the server and change the coordinates for changing "User1", you can either look for this user annotation in the map view annotations array, or store the links to the annotations in some other structure, provides quick access using a key like NSMutableDictionary .
After you find the annotation, you simply set the coordinate annotation property to a new value, and the map view automatically moves the annotation view to a new location.
This example searches for the array annotations :
for (id<MKAnnotation> ann in mapView.annotations) { if ([ann.title isEqualToString:@"User1"]) { ann.coordinate = theNewCoordinate; break; } }
If you want to find annotation using another, custom property of your annotation class (for example, some int named userIdNumber):
for (id<MKAnnotation> ann in mapView.annotations) { if ([ann isKindOfClass:[YourAnnotationClass class]]) { YourAnnotationClass *yacAnn = (YourAnnotationClass *)ann; if (yacAnn.userIdNumber == user1Id) { yacAnn.coordinate = theNewCoordinate; break; } } }
The above is just an example of how to change the coordinate. If you have many annotations with changing coordinates, I do not recommend looking for them in turn. Instead, you can save the links in the dictionary and quickly browse them using the key value.