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 annotation
Swift 3.0 version of Nathan's answer (thank you Nathan):
DispatchQueue.main.async {
mapView.addAnnotation(annotation)
}
Side note, Nathan's answer should have far more upvotes. I actually needed this help with removing an annotation, the same issue exists and is fixed by dispatching the update to the main queue.
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];
}
Removing all existing annotations, and re-adding the new or updated annotation list will refresh the mapView. Firstly I tried:
mapView.annotations.removeAll()
but received the error:
"Value of type '(MKMapRect) -> Set<AnyHashable>' has no member 'removeAll'"
However this worked:
for annotation in mapView.annotations{
mapView.removeAnnotation(annotation)
}
// .. code to add the new or updated annotation list
For dark mode purposes I needed to refresh the views of annotations. I had to call also the delegate method to recreate the view of the annotations.
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
[super traitCollectionDidChange:previousTraitCollection];
if (@available(iOS 13.0, *)) {
if ([self.traitCollection hasDifferentColorAppearanceComparedToTraitCollection:previousTraitCollection]) {
for (id<MKAnnotation> annotation in self.mapView.annotations) {
[self.mapView removeAnnotation:annotation];
[self.mapView addAnnotation:annotation];
[self mapView:self.mapView viewForAnnotation:annotation];
}
}
}
}
Just Add
mapView.reloadStyle(self)
Dispatch the add annotation to the main thread rather then attempt to modify the UI on a background thread
dispatch_async(dispatch_get_main_queue()) {
self.mapView.addAnnotation(annotation)
}