9.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:
Create a new class and call it
MyAnnotation
.Make sure this class conforms to the
MKAnnotation
protocol.Define a property for this class of type
CLLocationCoordinate2D
and name itcoordinate
. Make sure you set it as areadonly
property since thecoordinate
property is defined asreadonly
in theMKAnnotation
protocol.Optionally, define two properties of type
NSString
, namelytitle
andsubtitle
, which will be able to carry the title and the subtitle information for your annotation view. Both of these properties arereadonly
as well.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 isreadonly
, 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 thetitle
andsubtitle
properties.Instantiate the
MyAnnotation
class and add it to your map using theadd
Annotation:
method of theMKMapView
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 declare ...
Get iOS 7 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.