iOS刷新mapview上的注释

Jon*_*son 8 annotations mkmapview mkannotation mkannotationview ios

我有一个mapview,其中注释的坐标不断更新,但是当我使用setCoordinate时,注释不会移动.如何刷新注释以反映其坐标?

- (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 {

        }
    }];
}
Run Code Online (Sandbox Code Playgroud)

Row*_*man 18

更新(以反映解决方案):

拥有自己的自定义注释并实现setCoordinate和/或合成坐标可能会导致问题.

资料来源:http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/LocationAwarenessPG/AnnotatingMaps/AnnotatingMaps.html

以前的方案:

您只需删除所有注释,然后重新添加它们即可.

[mapView removeAnnotations:[mapView.annotations]];

[mapView addAnnotations:(NSArray *)];
Run Code Online (Sandbox Code Playgroud)

或删除它们并逐个重新添加:

for (id<MKAnnotation> annotation in mapView.annotations)
{
    [mapView removeAnnotation:annotation];
    // change coordinates etc
    [mapView addAnnotation:annotation]; 
}
Run Code Online (Sandbox Code Playgroud)

  • 您是否实现了setCoordinate方法或者将@synthesize坐标放在何处?这不太可能,但会导致问题. (3认同)

Nat*_*han 9

将添加注释分派给主线程,而不是尝试修改后台线程上的UI

dispatch_async(dispatch_get_main_queue()) {
    self.mapView.addAnnotation(annotation)
}
Run Code Online (Sandbox Code Playgroud)


bio*_*ker 6

Swift 3.0版Nathan的回答(谢谢Nathan):

DispatchQueue.main.async {
    mapView.addAnnotation(annotation)
}
Run Code Online (Sandbox Code Playgroud)

旁注,内森的答案应该有更多的赞成.我实际上需要这个帮助来删除注释,存在相同的问题,并通过将更新分派给主队列来修复.