Swift 3 Add custom annotation pin to MKMapSnapShotter snapshot
To render a MKMapSnapshot
with annotation views, you have to manually draw the snapshot's image
and the annotation view's image
on a new graphic context, and get a new image from that context. In Swift 3:
let rect = imageView.bounds
let snapshot = MKMapSnapshotter(options: options)
snapshot.start { snapshot, error in
guard let snapshot = snapshot, error == nil else {
print(error ?? "Unknown error")
return
}
let image = UIGraphicsImageRenderer(size: options.size).image { _ in
snapshot.image.draw(at: .zero)
let pinView = MKPinAnnotationView(annotation: nil, reuseIdentifier: nil)
let pinImage = pinView.image
var point = snapshot.point(for: location.coordinate)
if rect.contains(point) {
point.x -= pinView.bounds.width / 2
point.y -= pinView.bounds.height / 2
point.x += pinView.centerOffset.x
point.y += pinView.centerOffset.y
pinImage?.draw(at: point)
}
}
// do whatever you want with this image, e.g.
DispatchQueue.main.async {
imageView.image = image
}
}
This was adapted from https://stackoverflow.com/a/18776723/1271826, which itself was adapted from WWDC 2013 video Putting MapKit in Perspective.
Here is an example of a snapshot with a .satelliteFlyover
: