iPhone Map Kit Tutorial


Step 4 – Animate the Pushpins

  1. In RootViewController.h add to the class RootViewController the protocol MKMapViewDelegate
  2. Switch back to RootViewController.m and insert in the viewDidLoad, just after the statement initializing mapView the line:
  3. mapView.delegate = self;

  4. Add the following method to RootViewController:

  5. - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {

    MKPinAnnotationView *pinView = (MKPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"Pin"];

    if(pinView == nil) {

    pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"Pin"];

    pinView.pinColor = MKPinAnnotationColorPurple;

    pinView.animatesDrop = YES;

    } else {

    pinView.annotation = annotation;

    }

    return pinView;

    }


  6. Save, compile and run

Step 5 – Add Callouts

  1. Add in the method mapView:viewForAnnotation: after pinView.animatesDrop = YES the line:

  2. pinView.canShowCallout = YES;


  3. Switch to MapDemoAnnotation.h and add a _pinID member:

  4. NSUInteger _pinID;


  5. Modify the definition of the initialization method definition to:

  6. - (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate andID:(NSUInteger)pinID;


  7. Switch to MapDemoAnnotation.m and modify the initialization method implementation to initialize the _pinID:
  8.  

    - (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate andID:(NSUInteger)pinID{

    self = [super init];

    if (self != nil) {

    _coordinate = coordinate;

    _pinID = pinID;

    }

    return self;

    }

     

  9. Add the following two methods:

  10. - (NSString *)title {

    return [NSString stringWithFormat:@"Pin %u", _pinID];

    }

     

    - (NSString *)subtitle {

    return [NSString stringWithFormat:@"%.4f, %.4f", _coordinate.latitude, _coordinate.longitude];

    }


  11. Switch to RootViewController.m and modify the for loop in viewDidLoad to look like this:

  12. NSUInteger count = 1;

    for(int i = 0; i < 10; i++) {

    CGFloat latDelta = rand()*.035/RAND_MAX – .02;

    CGFloat longDelta = rand()*.03/RAND_MAX – .015;

    CLLocationCoordinate2D newCoord = {coordinate.latitude+latDelta, coordinate.longitude+longDelta};

    MapDemoAnnotation* annotation = [[MapDemoAnnotation alloc]initWithCoordinate:newCoord andID:count++];

    [mapView addAnnotation:annotation];

    [annotation release];

    }


  13. Save, compile and run.

Previous Tutorial Page