Topics

#70: Custom Map View Pins 🔰

Topics

MKMapView is a powerful class. One great feature is its ability to display custom annotation views for the annotations we use on our maps.

Let's test it out by creating a little treasure map. We'll start by creating a map view and adding an annotation to it:

let mapView = MKMapView(frame: mapFrame)
mapView.delegate = self

let location = CLLocationCoordinate2D(latitude: 37.3317115, longitude: -122.0301835)

let annotation = TreasureAnnotation(coordinate: location)
mapView.addAnnotation(annotation)

view.addSubview(mapView)

Instead of the standard red pin graphic 📍, we'd like to show a fun little treasure chest image at the spot of some secret treasure!

To do this, take advantage of MKAnnotationView's .image property. We can throw a regular UIImage at it to get exactly the behavior we're looking for. All we need to do is implement one delegate function and return an MKAnnotationView from it. MKAnnotationViews get reused just like UITableViewCells and UICollectionViewCells.

func mapView(mapView: MKMapView!, 
  viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
  if (annotation is MKUserLocation) { return nil }

  let reuseID = "chest"
  var v = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseID)

  if v != nil {
    v.annotation = annotation
  } else {
    v = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseID)

    v.image = UIImage(named:"chest")
  }

  return v
}

MKAnnotationView has tons of helpful properties out of the box, be sure to take a look before creating a full-blown subclass.