views:

1242

answers:

3

Can I create an MKAnnotation, or is it read only? I have coordinates, but I am not finding it easy to manually create an MKAnnotation with using setCoordinate.

Ideas?

+3  A: 

MKAnnotation is a protocol. So you need to write your own annotation object that implements this protocol. So you MyAnnotation header looks like:

@interface MyAnnotation : NSObject<MKAnnotation> {
    CLLocationCoordinate2D coordinate;
}

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;

// add an init method so you can set the coordinate property on startup
- (id) initWithCoordinate:(CLLocationCoordinate2D)coord;

and your implementation looks like (MyAnnotation.m):

- (id) initWithCoordinate:(CLLocationCoordinate2D)coord
{
    coordinate = coord;
}

So to add your annotation to the map:

MyAnnotation * annotation = [[[MyAnnotation alloc] initWithCoordinate:coordinate] autorelease];
[self.mapView addAnnotation:annotation];

If you wan't a title and subtitle on the annotation callout, you need to add the title and subtitle properties.

Cannonade
This is just what I needed. Where would I put the - (id) initWithCoordinate:(CLLocationCoordinate2D)coord; method? In my .h file or .m?
Nic Hubbard
No problem. I have updated the answer with some more detail :)
Cannonade
For some reason, I get no '-initWithCoord:' method found when I try to build and run.
Nic Hubbard
Sorry. My sample code was initWithCoord, it should be initWithCoordinate.
Cannonade
+1  A: 

Check apple MapCallouts project. Everything you need is in that file: http://developer.apple.com/iphone/library/samplecode/MapCallouts/Introduction/Intro.html

alecnash
+1  A: 

In iPhone OS 4 there is a new class MKPointAnnotation which is a concrete implementation of the MKAnnotation protocol.

joshrl