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:

  1. Import MapKit as a framework into your project.
  2. Create a class that conforms to both NSObject and MKAnnotation. Conforming to the MKAnnotation protocol requires defining its variables—particularly coordinate, title, and subtitle—and methods. Instances of classes that conform to MKAnnotation can be added to the map view via its addAnnotation(_:) method.
  3. 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.
  4. 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.
  5. Call the addAnnotation(_:) method of your map view to set the annotation at the right spot.
  6. 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.