Hoyeon Lee
Hoyeon Lee

Reputation: 113

How to avoid a segment connection between start point and end point on a map view to get printed image with MKMapSnapshotter?

I'm trying to draw a route on my Map View in Swift. The below is what I drew with MKMapSnapshotter. My problem is that the first and the last points of my route(coordinate) are always connected by segment so that they looks like a closed loop. Here, I don't want to draw the segment.

enter image description here

The following is my code, and please give me some solution for the problem.

func saveMapViewAsImage(region: MKCoordinateRegion, size: CGSize) {
    let options = MKMapSnapshotter.Options()
    options.region = region
    options.size = size
    options.mapType = .standard

    MKMapSnapshotter(options: options).start { snapshot, error in
        guard let snapshot = snapshot else { return }
        
        let mapImage = snapshot.image
        
        let finalImage = UIGraphicsImageRenderer(size: size).image { _ in
            mapImage.draw(at: .zero)
                
            // get [CLLocationCoordinate2D]
            let coordinates = self.getTrackPointForPolyline()
            guard coordinates.count > 1 else { return }
            
            // [CLLocationCoordinate2D] -> [CGPoint]
            let points = coordinates.map { coordinate in
                snapshot.point(for: coordinate)
            }

            // draw lines
            let path = UIBezierPath()
            path.lineWidth = K.Map.routeLineWidth * 0.5
            path.lineCapStyle = .round
            path.lineJoinStyle = .round

            path.move(to: points[0])
            for index in 1..<points.count {
                path.addLine(to: points[index])
            }

            K.Map.routeLineColor.withAlphaComponent(0.75).setStroke()
            path.stroke()
        }

        // save as image
        self.saveRenderedImageToDocumentDirectory(image: finalImage)
    }
}

Upvotes: 0

Views: 63

Answers (0)

Related Questions