iPhone:创建MKAnnotation

15

我能创建一个MKAnnotation吗,还是只读的?我有坐标,但手动使用setCoordinate创建MKAnnotation并不容易。

有什么想法吗?

3个回答

41

MKAnnotation是一个协议。因此,您需要编写自己的注释对象来实现此协议。所以你的MyAnnotation头文件应该像这样:

@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;

你的实现看起来像这样(MyAnnotation.m):

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

要将您的注释添加到地图上:

MyAnnotation * annotation = [[[MyAnnotation alloc] initWithCoordinate:coordinate] autorelease];
[self.mapView addAnnotation:annotation];
如果你想在注释气泡上添加标题和副标题,需要添加title和subtitle属性。

这正是我所需要的。-(id) initWithCoordinate:(CLLocationCoordinate2D)coord; 方法应该放在我的 .h 文件里还是 .m 文件里? - Nic Hubbard
没问题。我已经更新了答案并加入了更多细节 :) - RedBlueThing
如何为注释添加图像? - Nilesh Tupe
@NileshTupe 请查看这个问题:https://dev59.com/GHM_5IYBdhLWcg3w3nfz#1963460 - RedBlueThing
协议(以及Java中的接口)的整个目的是让您将事物视为其他事物。因此,即使在示例中,创建名为MyAnnotation的类也真的不好。您要放置在地图上的任何内容都应该是域对象,例如餐厅。然后,您可以使该域类实现此协议,然后将此可定位行为映射到它上面。 - Rob
显示剩余2条评论

33

在iPhone OS 4中,有一个新的类MKPointAnnotation,它是MKAnnotation协议的具体实现。


1
如果您只需要基本的注释,这非常方便。谢谢! - radven
4
MKPointAnnotation* pointAnnotation = [[MKPointAnnotation alloc] init]; pointAnnotation.coordinate = location.coordinate; [mkMapView addAnnotation:pointAnnotation];这段代码的意思是创建一个地图标注点对象,设置它的经纬度坐标,然后将该标注点添加到地图视图中。 - Dickey Singh

9

非常感谢,正是我所需要的。 - Elise van Looij

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接