[ios] 현재 위치와 목적지 간의 경로 그리기

iOS 애플리케이션이나 앱을 개발할 때, 사용자의 현재 위치와 목적지 사이의 경로를 지도에 그리는 기능은 매우 중요합니다. 사람들은 이를 통해 보다 효율적인 경로를 선택하고 목적지까지 도달할 수 있습니다. iOS 앱을 개발하면서 MapKit 프레임워크를 사용하여 이러한 기능을 구현할 수 있습니다.

현재 위치와 목적지 설정하기

먼저, 사용자의 현재 위치와 목적지를 설정해야 합니다. 이를 위해선 Core Location 프레임워크를 사용하여 사용자의 현재 위치를 가져올 수 있습니다. 사용자의 목적지를 가져오는 방법은 여러 가지가 있지만, 보통은 사용자의 입력이나 저장된 정보를 사용하여 목적지를 설정합니다.

import CoreLocation

// 현재 위치 가져오기
let locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()

if CLLocationManager.locationServicesEnabled() {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager.startUpdatingLocation()
}

// 목적지 설정하기
let destinationLocation = CLLocation(latitude: 37.7749, longitude: -122.4194) // 목적지 위도와 경도

지도에 경로 그리기

사용자의 현재 위치와 목적지를 설정했다면, MapKit을 사용하여 지도에 경로를 그릴 수 있습니다. MKMapViewDelegate 프로토콜을 이용하여 지도에 선을 추가하여 경로를 그리게 됩니다.

import MapKit

func drawRoute() {
    let sourcePlacemark = MKPlacemark(coordinate: locationManager.location.coordinate)
    let destinationPlacemark = MKPlacemark(coordinate: destinationLocation.coordinate)

    let directionRequest = MKDirections.Request()
    directionRequest.source = MKMapItem(placemark: sourcePlacemark)
    directionRequest.destination = MKMapItem(placemark: destinationPlacemark)
    directionRequest.transportType = .automobile

    let directions = MKDirections(request: directionRequest)
    directions.calculate { (response, error) in
        guard let response = response else {
            if let error = error {
                print("Error: \(error)")
            }
            return
        }
        
        let route = response.routes[0]
        self.mapView.addOverlay(route.polyline, level: .aboveRoads)
    }
}

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

위의 예제 코드는 사용자의 현재 위치와 목적지 간의 경로를 MapKit을 사용하여 그리는 방법을 보여줍니다. 사용자의 현재 위치를 가져오고, 목적지를 설정한 후에 MapKit을 사용하여 경로를 그립니다.

이제 이러한 코드를 사용하여 iOS 애플리케이션에 현재 위치와 목적지 간의 경로를 그릴 수 있습니다.

참고 자료