6.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
MKAnnotationprotocol.Define a property for this class of type
CLLocationCoordinate2Dand name itcoordinate. Make sure you set it as areadonlyproperty since thecoordinateproperty is defined asreadonlyin theMKAnnotationprotocol.Optionally, define two properties of type
NSString, namelytitleandsubtitle, which will be able to carry the title and the subtitle information for your annotation view. Both of these properties arereadonlyas 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 thetitleandsubtitleproperties.Instantiate the
MyAnnotationclass and add it to your map using theaddAnnotation:method of theMKMapViewclass.
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 ...
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