In my app I am showing location of some other person by getting their location (latitude and longitude) from server at particular interval.
After getting I have to
Why is that a performance problem? Have you mesaured it? You're just changing an array of objects, not even creating new instances.
The AnnotationViews on the MapView
will be reused anyway. There shouldn't be any problems with that.
To change an annotation's coordinate without removing, re-creating and adding it again, create an annotation class where the coordinate
property is settable. A simple way to do this is to define the coordinate
property like this:
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
Alternatively, instead of defining your own class, you could also use the built-in MKPointAnnotation
class which has a settable coordinate
.
You initially create and add the annotations as usual. For example:
MKPointAnnotation *pa = [[MKPointAnnotation alloc] init];
pa.coordinate = someCoordinate;
pa.title = @"User1";
[mapView addAnnotation:pa];
[pa release];
Later, when you get an update from the server and the coordinates for "User1" change, you can either search for that user's annotation in the map view's annotations
array or store the references to the annotations in some other structure that allows quick access using a key like an NSMutableDictionary
.
Once you have found the annotation, you just set the annotation's coordinate
property to the new value and the map view will automatically move the annotation's view to the new location.
This example searches the annotations
array:
for (id<MKAnnotation> ann in mapView.annotations)
{
if ([ann.title isEqualToString:@"User1"])
{
ann.coordinate = theNewCoordinate;
break;
}
}
If you want to find the annotation using a different, custom property of your annotation class (say 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 lots of annotations with changing coordinates, I don't recommend searching for them one-at-a-time. Instead, you could store the references in a dictionary and look them up quickly using a key value.