Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách vẽ đường đi giữa 2 vị trí dùng MapKit trong Swift

Để vẽ đường đi (route) giữa 2 vị trí trên bản đồ, dùng MapKit và MKDirections. Cần tọa độ (latitude, longitude) của 2 điểm.

Hàm vẽ đường đi


import MapKit

func getDirections(from sourceCoord: CLLocationCoordinate2D, to destCoord: CLLocationCoordinate2D) {
    let sourcePlacemark = MKPlacemark(coordinate: sourceCoord)
    let destPlacemark = MKPlacemark(coordinate: destCoord)
    
    let sourceItem = MKMapItem(placemark: sourcePlacemark)
    sourceItem.name = "Vị trí hiện tại"
    
    let destItem = MKMapItem(placemark: destPlacemark)
    destItem.name = "Đích đến"
    
    // Mở app Maps hệ thống với chỉ đường lái xe
    MKMapItem.openMaps(with: [sourceItem, destItem], 
                       launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])
}

Gọi trong ViewController


override func viewDidLoad() {
    super.viewDidLoad()
    
    // Ví dụ: Từ Washington DC đến Denver, CO
    let coord1 = CLLocationCoordinate2D(latitude: 38.9072, longitude: -77.0369)
    let coord2 = CLLocationCoordinate2D(latitude: 39.7392, longitude: -104.9903)
    
    getDirections(from: coord1, to: coord2)
}

Kết quả

Mở Apple Maps hệ thống hiển thị đường đi:

Cách vẽ đường đi giữa 2 vị trí dùng MapKit trong Swift

Nâng cao: Vẽ route trên MKMapView trong app (không mở Maps.app)


func drawRouteOnMap(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D) {
    let request = MKDirections.Request()
    request.source = MKMapItem(placemark: MKPlacemark(coordinate: source))
    request.destination = MKMapItem(placemark: MKPlacemark(coordinate: destination))
    request.transportType = .automobile
    
    let directions = MKDirections(request: request)
    directions.calculate { [weak self] response, error in
        guard let route = response?.routes.first else { return }
        
        // Vẽ polyline lên mapView
        self?.mapView.addOverlay(route.polyline, level: .aboveRoads)
        
        // Zoom fit route
        let rect = route.polyline.boundingMapRect
        self?.mapView.setVisibleMapRect(rect, edgePadding: UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50), animated: true)
    }
}

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

Lưu ý: Cần thêm NSLocationWhenInUseUsageDescription vào Info.plist nếu dùng vị trí user. MapKit directions yêu cầu internet.