2

Suppose I have the code below to add a map on a view, what is the simplest way to add a pin on the location. Could someone advise the code snippet to add to my code?

Thanks

- (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.
}

UPDATE:

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(@"called viewForAnnotation"); has not been executing.

Charles Yeung
  • 38,347
  • 30
  • 90
  • 130

1 Answers1

0
  1. Set the map's delegate.
  2. Add an annotation to the map for the spot where you want a pin to appear.
  3. Return an instance of MKPinAnnotationView when the map calls it's delegate's -mapView:viewForAnnotation: method for the annotation that you added in step 2.
Caleb
  • 124,013
  • 19
  • 183
  • 272