Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS refresh annotations on mapview

I have a mapview where the annotation's coordinates are constantly being updated but when I use setCoordinate, the annotation does not move. How do I refresh the annotations to reflect their coordinates?

- (void)updateUnits {

    PFQuery *query = [PFQuery queryWithClassName:@"devices"];
    [query whereKeyExists:@"location"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

        if (!error) {

            for (PFObject *row in objects) {

                PFGeoPoint *geoPoint = [row objectForKey:@"location"];
                CLLocationCoordinate2D coord = { geoPoint.latitude, geoPoint.longitude };

                for (id<MKAnnotation> ann in mapView.annotations) {

                    if ([ann.title isEqualToString:[row objectForKey:@"deviceid"]]) {

                        [ann setCoordinate:coord];

                        NSLog(@"latitude is: %f" , coord.latitude);
                        NSLog(@"Is called");
                        break;
                    }
                    else {

                        //[self.mapView removeAnnotation:ann];
                    }
                }
            }
        }
        else {

        }
    }];
}
like image 826
Jon Erickson Avatar asked Jan 03 '13 00:01

Jon Erickson


1 Answers

Updated (to reflect the solution):

Having your own custom annotations and implementing setCoordinate and/or synthesizing coordinate may cause issues.

Source: http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/LocationAwarenessPG/AnnotatingMaps/AnnotatingMaps.html

Previous solution:

You can simply remove all of the annotations and then re-add them.

[mapView removeAnnotations:[mapView.annotations]];

[mapView addAnnotations:(NSArray *)];

or remove them and re-add them one by one:

for (id<MKAnnotation> annotation in mapView.annotations)
{
    [mapView removeAnnotation:annotation];
    // change coordinates etc
    [mapView addAnnotation:annotation]; 
}
like image 157
Rowan Freeman Avatar answered Sep 20 '22 10:09

Rowan Freeman