7.4. Displaying Pins on a Map View

Problem

You want to point out a specific location on a map to the user.

Solution

Use built-in map view annotations. Follow these steps:

  1. Create a new class and call it MyAnnotation.

  2. Make sure this class conforms to the MKAnnotation protocol.

  3. Define a property for this class of type CLLocationCoordinate2D and name it coordinate. Make sure you set it as a readonly property since the coordinate property is defined as readonly in the MKAnnotation protocol.

  4. Optionally, define two properties of type NSString, namely title and subtitle, which will be able to carry the title and the subtitle information for your annotation view. Both of these properties are readonly as well.

  5. Create an initializer method for your class that will accept a parameter of type CLLocationCoordinate2D. In this method, assign the passed location parameter to the property that we defined in step 3. Since this property is readonly, it cannot be assigned by code outside the scope of this class. Therefore, the initializer of this class acts as a bridge here and allows us to indirectly assign a value to this property. We will do the same thing for the title and subtitle properties.

  6. Instantiate the MyAnnotation class and add it to your map using the addAnnotation: method of the MKMapView class.

Discussion

As explained in this recipe’s Solution, we must create an object that conforms to the MKAnnotation protocol, and later instantiate this object and pass it to the map to be displayed. We will write ...

Get iOS 6 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.