iPhone Map Kit Tutorial
Step 4 – Animate the Pushpins
- In RootViewController.h add to the class RootViewController the protocol MKMapViewDelegate
- Switch back to RootViewController.m and insert in the viewDidLoad, just after the statement initializing mapView the line:
- Add the following method to RootViewController:
- Save, compile and run
mapView.delegate = self;
- (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;
}
Step 5 – Add Callouts
- Add in the method mapView:viewForAnnotation: after pinView.animatesDrop = YES the line:
- Switch to MapDemoAnnotation.h and add a _pinID member:
- Modify the definition of the initialization method definition to:
- Switch to MapDemoAnnotation.m and modify the initialization method implementation to initialize the _pinID:
- Add the following two methods:
- Switch to RootViewController.m and modify the for loop in viewDidLoad to look like this:
- Save, compile and run.
pinView.canShowCallout = YES;
NSUInteger _pinID;
- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate andID:(NSUInteger)pinID;
- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate andID:(NSUInteger)pinID{
self = [super init];
if (self != nil) {
_coordinate = coordinate;
_pinID = pinID;
}
return self;
}
- (NSString *)title {
return [NSString stringWithFormat:@"Pin %u", _pinID];
}
- (NSString *)subtitle {
return [NSString stringWithFormat:@"%.4f, %.4f", _coordinate.latitude, _coordinate.longitude];
}
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];
}


