O'Reilly logo

iOS 5 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

6.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 sample .h file of a view controller that creates an instance of MKMapView and displays it full-screen on its view:

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface Creating_a_Map_ViewViewController : UIViewController

@property (nonatomic, strong) MKMapView *myMapView;

@end

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:

#import "Creating_a_Map_ViewViewController.h"

@implementation Creating_a_Map_ViewViewController

@synthesize myMapView;

- (void)didReceiveMemoryWarning{
  [super didReceiveMemoryWarning];
}

- (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];

}

- (void)viewDidUnload{
  [super viewDidUnload];
  self.myMapView = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation
        :(UIInterfaceOrientation)interfaceOrientation{
  return YES;
}

@end

Discussion

Creating an ...

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