How do I update the location of an MKAnnotation object on a mapView?

Viewed 3235

I have the following code, which aims to loop through all the annotations on the current apple map view and update their location coordinates.

for existingMarker in self.mapView.annotations {

    existingMarker.coordinate.latitude = 12.12121212
    existingMarker.coordinate.longitude = 14.312121121          
}

Sadly this is not allowed. I am told that 'coordinate' is a get only property. So this is obviously not how I am meant to update the MKAnnotation's location of annotations already drawn on a mapView. How can I do this then? Specifically I would like to do this and have the map "redraw" with the new coordinates ASAP. I am sure this must be possible as it seems like a common use case.

2 Answers

For Swift, you just need to make the coordinate field a var, and then type MKAnnotation when trying to mutate:

protocol MutableAnnotation : NSObject, MKAnnotation {
    dynamic var coordinate: CLLocationCoordinate2D { get set }
}

class MyAnnotation : MutableAnnotation {
    dynamic var coordinate: CLLocationCoordinate2D
}

// ...

func updateLocation(_ annotation: MKAnnotation, coordinate: CLLocationCoordinate2D)
{
    guard let mutable = annotation as? MutableAnnotation else { return }
    mutable.coordinate = coordinate
}

Related