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.1. Creating a Map View

Problem

You want to instantiate and display a map on a view.

Solution

Create an instance of the MKMapView class and add it to a view or assign it as a subview of your view controller. Here is the declaration part of the implementation of our view controller that creates an instance of MKMapView and displays it full-screen on its view:

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

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

@implementation ViewController

This is a simple root view controller with a variable of type MKMapView. Later in the implementation of this view controller (.m file), we will initialize the map and set its type to Satellite, like so:

- (void)viewDidLoad{
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    self.myMapView = [[MKMapView alloc]
                      initWithFrame:self.view.bounds];
    /* Set the map type to Satellite */
    self.myMapView.mapType = MKMapTypeSatellite;

    self.myMapView.autoresizingMask =
        UIViewAutoresizingFlexibleWidth |
        UIViewAutoresizingFlexibleHeight;

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

}

Discussion

Creating an instance of the MKMapView class is quite straightforward. We can simply assign a frame to it using its constructor, and after the map is created, add it as a subview of the view on the screen just so that we can see it.

Note

MKMapView is a subclass of UIView, so you can manipulate any map view the way you manipulate an instance of UIView. We use ...

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