在iOS中在地图上添加图钉的最简单方法

时间:2011-10-15 05:03:06

标签: objective-c

假设我有以下代码在视图上添加地图,在该位置添加 pin 最简单方法是什么。有人可以建议将代码段添加到我的代码中吗?

由于

- (void)viewDidLoad
{
    MKMapView *map = [[MKMapView alloc] initWithFrame:CGRectMake(2, 2, 300, 300)];
    MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };

    region.center.latitude = 22.278355;
    region.center.longitude = 114.181713;

    region.span.longitudeDelta = 0.01f;
    region.span.latitudeDelta = 0.01f;  

    [map setRegion:region animated:YES];
    [map regionThatFits:region];

    [self.view addSubview:map];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

更新:

xxx.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>


@interface ShopDetail : UIViewController <MKMapViewDelegate> {

}

@end

xxx.m

- (void)viewDidLoad
{
    MKMapView *map = [[MKMapView alloc] initWithFrame:CGRectMake(2, 2, 300, 300)];
    MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };

    region.center.latitude = 22.278355; //40.105085;
    region.center.longitude = 114.181713; //-83.005237;

    region.span.longitudeDelta = 0.01f;
    region.span.latitudeDelta = 0.01f;  

    [map setRegion:region animated:YES];
    [map regionThatFits:region];

    map.delegate = self;

    [self.view addSubview:map];

    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    MKPinAnnotationView *pav = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];

    NSLog(@"called viewForAnnotation");

    pav.pinColor = MKPinAnnotationColorGreen;
    return pav;
}

* NSLog(@“名为viewForAnnotation”);尚未执行。

1 个答案:

答案 0 :(得分:0)

  1. 设置地图的委托。
  2. 在地图上添加注释,以显示要显示图钉的位置。
  3. 当地图为您在步骤2中添加的注释调用委托的-mapView:viewForAnnotation:方法时,返回MKPinAnnotationView的实例。