views:

1065

answers:

4

Is it possible to move the coordinate of a MKAnnotation without adding and removing the annotation from the map?

A: 

It doesn't seem possible to change the coordinate of a MKAnnotation object and then inform the MKMapView of the change.

However, removing the previous annotation from the map, changing the coordinate of your annotation object and adding it back to the map works well.

[theMapView removeAnnotation:myAnnotation]; 
[myAnnotation setLatitude:newLatitude];
[theMapView addAnnotation:myAnnotation];

Why don't you want to do it this way?

Guillaume
+3  A: 

Don't know whether it's more generally possible, but it is if you have your own custom MKAnnotationView.

I was able to adapt the approach documented at http://spitzkoff.com/craig/?p=108 by Craig Spitzkoff:

  1. Give your custom MKAnnotationView a reference to your MKAnnotation object
  2. Add an updateCoordinates method to the MKAnnotation object and call it when you want to change location of the annotation
  3. Call regionChanged on the custom MKAnnotationView to let it know when to reposition itself (e.g. when MKAnnotation has updated coordinates)
  4. In drawRect on the internal view object owned by your custom MKAnnotationView you can reposition using the coordinates of the MKAnnotation (you're holding a reference to it).

You could likely simplify this approach further - you may not require an internal view object in all circumstances.

StephenT
Yeah that's the solution I came up with, seems weird to have drawRect determine it's own frame though.
DevDevDev
Are you able to provide a sample to this at all please?
Lee Armstrong
A: 

Take a look at my MapKitDragAndDrop sample, it allows you to update MKAnnotation and move MKAnnotationView on both iPhone OS 3 and iOS 4 (will use built-in dragging support).

digdog
A: 

I found a pretty simple method. I wanted to update my player's position smoothly without removing and then re-adding the player annotation. This works well for pre-iOS4 apps, and what it does is both move the pin and center the map on the pin's new location:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
[player setCoordinate:aLoc.coordinate];
[mapView setCenterCoordinate:aLoc.coordinate animated:NO];
[UIView commitAnimations];

Here's the same thing but using the recommended block feature for iOS4:

[UIView animateWithDuration:0.5 animations:^{
    [player setCoordinate:aLoc.coordinate];
    [mapView setCenterCoordinate:aLoc.coordinate animated:NO];
}];
spstanley
in which method are those code lines ?
Dragouf
Any method that's updating your pin's position. For me, I have another object sending my map view controller a new position, which I then use to update my player pin's position. But you could receive a new position from an external source, or by the user touching a button or using drag-and-drop, whatever.
spstanley