ใช้ MapKit วาดเส้นทางระหว่าง 2 พิกัด (Coordinates) โดยใช้ MKDirections
โค้ดพื้นฐาน
import MapKit
func getDirections(from sourceCoord: CLLocationCoordinate2D,
to destCoord: CLLocationCoordinate2D) {
let source = MKMapItem(placemark: MKPlacemark(coordinate: sourceCoord))
source.name = "ต้นทาง"
let destination = MKMapItem(placemark: MKPlacemark(coordinate: destCoord))
destination.name = "ปลายทาง"
let request = MKDirections.Request()
request.source = source
request.destination = destination
request.transportType = .automobile // .walking, .transit
let directions = MKDirections(request: request)
directions.calculate { response, error in
guard let route = response?.routes.first else {
print("Error: \(error?.localizedDescription ?? "No route")")
return
}
// เพิ่ม Overlay บน Map
self.mapView.addOverlay(route.polyline)
// Zoom ให้เห็นทั้งเส้นทาง
self.mapView.setVisibleMapRect(route.polyline.boundingMapRect,
edgePadding: UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50),
animated: true)
}
}
Delegate สำหรับ Renderer
extension ViewController: 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)
}
}
การใช้งาน
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
let bangkok = CLLocationCoordinate2D(latitude: 13.7563, longitude: 100.5018)
let chiangMai = CLLocationCoordinate2D(latitude: 18.7883, longitude: 98.9853)
getDirections(from: bangkok, to: chiangMai)
}
Transport Types
.automobile - รถยนต์ (Default).walking - เดินเท้า.transit - ขนส่งสาธารณะ (รองรับบางประเทศ).any - ทุกประเภท
ข้อมูลเพิ่มเติมจาก Route
let route = response.routes.first!
print("Distance: \(route.distance) meters") // ระยะทาง (เมตร)
print("Time: \(route.expectedTravelTime) seconds") // เวลาเดินทาง (วินาที)
print("Steps: \(route.steps.count)") // จำนวนขั้นตอน
for step in route.steps {
print("\(step.instructions) - \(step.distance)m")
}
Info.plist
ต้องเพิ่ม NSLocationWhenInUseUsageDescription (ถ้าใช้ User Location)