[ios] 지도에 여행 코스 및 여행 경로 표시하기

여행 앱을 개발할 때 사용자가 여행 경로를 확인하고 관리할 수 있도록 하는 것은 매우 중요합니다. iOS 앱에서 Apple MapKit Framework를 사용하여 지도에 여행 코스 및 여행 경로를 표시하는 방법에 대해 배워보겠습니다.

1. 지도에 여행 코스 표시하기

여행 코스를 지도에 표시하려면 다음과 같은 단계를 따릅니다.

1.1. MapKit Framework Import

먼저, 프로젝트에 MapKit Framework를 Import 해야 합니다.

import MapKit

1.2. 지도에 Polyline 표시하기

여행 경로를 Polyline으로 표시합니다. Polyline은 지도상에 선을 그리는 데 사용됩니다.

func drawTravelRoute() {
    let locations = // 여행 경로를 포함하는 위치 배열
    
    var coordinates = locations.map({ $0.coordinate })
    let polyline = MKPolyline(coordinates: &coordinates, count: coordinates.count)
    mapView.addOverlay(polyline)
}

1.3. Polyline 커스터마이징

Polyline을 커스터마이징하여 경로를 강조하거나 시각적으로 구분할 수 있습니다.

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

2. 지도에 여행 경로 표시하기

여행 경로를 표시하려면 다음과 같은 단계를 따릅니다.

2.1. 지도에 Annotations 추가하기

여행하는 동안 방문하는 장소를 Annotations으로 표시합니다.

func addAnnotations() {
    let locations = // 여행 경로에 있는 장소들
    
    for location in locations {
        let annotation = MKPointAnnotation()
        annotation.coordinate = location.coordinate
        annotation.title = location.name
        mapView.addAnnotation(annotation)
    }
}

2.2. Annotations 커스터마이징

Annotations을 커스터마이징하여 여행하는 동안 방문하는 장소를 시각적으로 구분할 수 있습니다.

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation { return nil }
    
    let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "customAnnotation")
    annotationView.pinTintColor = .green
    return annotationView
}

위의 단계를 따라하면 지도에 여행 코스 및 여행 경로를 표시할 수 있습니다.

참고로, 이 코드는 iOS 13 이상에서 작동합니다.

참고 자료