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>@interfaceViewController()@property(nonatomic,strong)MKMapView*myMapView;@end@implementationViewController
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{[superviewDidLoad];self.view.backgroundColor=[UIColorwhiteColor];self.myMapView=[[MKMapViewalloc]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.viewaddSubview: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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access