Chapter 12. Maps and Location
In this chapter, we will have a look at some awesome updates to the MapKit
and CoreLocation
frameworks.
12.1 Displaying a Specific Location on the Map
Problem
You have a latitude and a longitude of a location on Earth that you would like to display as a pin on the map.
Solution
Follow these steps:
- Import
MapKit
as a framework into your project. - Create a class that conforms to both
NSObject
andMKAnnotation
. Conforming to theMKAnnotation
protocol requires defining its variables—particularlycoordinate
,title
, andsubtitle
—and methods. Instances of classes that conform toMKAnnotation
can be added to the map view via itsaddAnnotation(_:)
method. - For the map to know where to set the visible region that the user actually sees, instead of seeing the entire map of the earth, instantiate
MKCoordinateSpan
with a latitude delta and longitude delta of type double. The smaller the deltas, the closer the camera is to the earth. - Instantiate
MKCoordinateRegion
with the location you want to be the center of the map, and pass the coordinate span instance that you created in the previous step to the coordinate region. - Call the
addAnnotation(_:)
method of your map view to set the annotation at the right spot. - Call the
setRegion(_:animated:)
method of your map view to set the visible region of your map.
Discussion
Let’s have a look at an example. Create a single view application in Xcode and open the Main.storyboard file in Interface Builder. From the Object ...
Get iOS 10 Swift Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.