How to add pin annotation view to MKMapSnapShotter in Swiftui?

562 Views Asked by At

I have a snapshot image and want to add locationAnnotation of type CLLocationCoordinate2D as a pin annotation view to the snapshot. Is there any option from MKMapSnapshotter for doing that? If not, please how it can be added manually.

 func snapshotGenerator(width: CGFloat, height: CGFloat) {
      // The region the map should display.
      let region = MKCoordinateRegion(
        center: self.location,
        span: MKCoordinateSpan(
          latitudeDelta: self.span,
          longitudeDelta: self.span
        )
      )
       let locationAnnotation = CLLocationCoordinate2D(latitude: selectedItem.latitude, longitude: selectedItem.longitude)
      // Map options.
      let options = MKMapSnapshotter.Options()
      options.region = region
      options.size = CGSize(width: width, height: height)
      options.showsBuildings = true
      // Create the snapshotter and run it.
      let snapshotter = MKMapSnapshotter(options: options)
      snapshotter.start { (snapshotImage, Error) in
        if let error = Error {
          print(error)
          return
        }
        if let snapshot = snapshotImage {
            // How to add locationAnnotation to the snapshot image ?
            self.snapshotImage = snapshot.image
        }
      }
    }
1

There are 1 best solutions below

0
Sherko77 On

I have solved it with UIGraphicsImageRenderer as shown below:

    func snapshotGenerator(width: CGFloat, height: CGFloat) {
    let options = MKMapSnapshotter.Options()
    options.camera = MKMapCamera(lookingAtCenter: location,   fromDistance: 100, pitch: 0, heading: 0)
            options.mapType = .satellite
            options.size = CGSize(width: width, height: height)
            let snapshotter = MKMapSnapshotter(options: options)
            snapshotter.start() { snapshot, _ in
                let mapImage = snapshot?.image
                let finalImage = UIGraphicsImageRenderer(size: options.size).image { _ in
                    mapImage?.draw(at: .zero)
                    let pinView = MKPinAnnotationView(annotation: nil, reuseIdentifier: nil)
                    let pinImage = pinView.image
                    let point = snapshot?.point(for: location)
                    pinImage?.draw(at: point!)
                }
                self.snapshotImage = finalImage
            }
}