Skip to content

mapkit polyline

tyler edited this page Oct 10, 2023 · 2 revisions

μ§€λ„μœ„μ— 경둜 ν‘œμ‹œ (Polyline)

λͺ©μ°¨

1. coordinates λ³€μˆ˜ 생성
2. Polyline Overlay μΆ”κ°€
3. μƒμ„±ν•œ Polyline μ»€μŠ€ν…€

coordinates λ³€μˆ˜ 생성

  • CLLocationCoordinate2D νƒ€μž…μœΌλ‘œ λͺ¨μΈ μ’Œν‘œμ˜ 배열을 μƒμ„±ν•©λ‹ˆλ‹€.
    @State private var coordinates = [
        CLLocationCoordinate2D(latitude: 37.53958, longitude: 127.07435),
        CLLocationCoordinate2D(latitude: 37.54132, longitude: 127.07575),
        CLLocationCoordinate2D(latitude: 37.54233, longitude:  127.07631),
        CLLocationCoordinate2D(latitude: 37.54215, longitude: 127.07750),
        CLLocationCoordinate2D(latitude: 37.53936, longitude: 127.07687),
        CLLocationCoordinate2D(latitude: 37.53958, longitude: 127.07435)
    ]

Polyline Overlay μΆ”κ°€

  • λ§Œλ“  coordinates λ³€μˆ˜λ₯Ό μ‚¬μš©ν•˜μ—¬ Polyline 을 λ§Œλ“­λ‹ˆλ‹€.
        let polyline = MKPolyline(coordinates: coordinates, count: coordinates.count)
        mapView.addOverlay(polyline)

μƒμ„±ν•œ Polyline μ»€μŠ€ν…€

        func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
            if let routePolyline = overlay as? MKPolyline {
                let renderer = MKPolylineRenderer(polyline: routePolyline)
                renderer.strokeColor = UIColor.orange
                renderer.lineWidth = 3
                renderer.alpha = 0.5
                return renderer
            }
            return MKOverlayRenderer()
        }

μΆ”κ°€ : Polyline Animation

  • μ•„λž˜μ™€ 같이 currentStep 을 κΈ°μ€€μœΌλ‘œ polyline 을 ν˜•μ„± ν•©λ‹ˆλ‹€.
  • currentStep 을 λΆ€λͺ¨λ·°μ—μ„œ 순차적으둜 μ˜¬λ €μ€λ‹ˆλ‹€.
    // ν•„μš”μ—†λŠ” 뢀뢄은 μƒλž΅ν–ˆμŠ΅λ‹ˆλ‹€.
    var currentStep: Int

    func makeUIView(context: Context) -> MKMapView {
        let polyline = MKPolyline(coordinates: coordinates, count: currentStep)
        mapView.addOverlay(polyline)
    }

    func updateUIView(_ view: MKMapView, context: Context) {        
        // ν˜„μž¬ μŠ€ν…μ— 따라 μƒˆλ‘œμš΄ 선뢄을 μΆ”κ°€ν•˜κΈ° 전에 이전 선뢄을 μ œκ±°ν•©λ‹ˆλ‹€.
        let overlays = view.overlays.filter { $0 is MKPolyline }
        view.removeOverlays(overlays)
        
        // ν˜„μž¬ μŠ€ν…μ— 따라 μƒˆλ‘œμš΄ 선뢄을 μΆ”κ°€ν•©λ‹ˆλ‹€.
        let subCoordinates = Array(coordinates.prefix(upTo: currentStep))
        let currentSegment = MKPolyline(coordinates: subCoordinates, count: subCoordinates.count)
        view.addOverlay(currentSegment)
    }

Clone this wiki locally