O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

9.2. Handling the Events of a Map View

Problem

You want to handle various events that a map view can send to its delegate.

Solution

Assign a delegate object that conforms to the MKMapViewDelegate protocol to the delegate property of an instance of the MKMapView class:

- (void)viewDidLoad{
    [super viewDidLoad];

    /* Create a map as big as our view */
    self.myMapView = [[MKMapView alloc]
                      initWithFrame:self.view.bounds];

    /* Set the map type to Satellite */
    self.myMapView.mapType = MKMapTypeSatellite;

    self.myMapView.delegate = self;

    self.myMapView.autoresizingMask =
    UIViewAutoresizingFlexibleWidth |
    UIViewAutoresizingFlexibleHeight;

    /* Add it to our view */
    [self.view addSubview:self.myMapView];

}

This code can easily run in the viewDidLoad method of a view controller object that has a property named MapView of type MKMapView:

#import "ViewController.h"
#import <MapKit/MapKit.h>

@interface ViewController () <MKMapViewDelegate>
@property (nonatomic, strong) MKMapView *myMapView;
@end

@implementation ViewController

Discussion

The delegate object of an instance of the MKMapView class must implement the methods defined in the MKMapViewDelegate protocol in order to receive various messages from the map view and, as we will see later, to provide information to the map view. Various methods are defined in the MKMapViewDelegate protocol, such as the mapViewWillStartLoadingMap: method that will get called in the delegate object whenever the map loading process starts. Bear in mind that a delegate for a ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required