以下代码允许用户点击路段控制器以选择首选的运输方式,并返回从起点到终点的方向。我能够成功获得步行和驾车的路线。
@objc func handleDirectionSegmentControl(_ sender: UISegmentedControl){
//transport = MKDirectionsTransportType.automobile
switch sender.selectedSegmentIndex {
case 0:
transport = MKDirectionsTransportType.walking
case 1:
transport = MKDirectionsTransportType.automobile
case 2:
transport = MKDirectionsTransportType.transit
default:
print("Invalid index selected in Segment Controller")
}
func getDirections(){
let request = createDirectionsRequest(from: location)
let directions = MKDirections(request: request)
resetMapView(withNew: directions)
directions.calculate { [unowned self](response, error) in
for route in response.routes {
let steps = route.steps
self._steps = steps
self.mapView.addOverlay
self.mapView.setVisibleMapRect(route.polyline.boundingMapRect, animated: true)
}
}
}
func createDirectionsRequest(from coordinate: CLLocationCoordinate2D)-> MKDirections.Request {
let destinationCoordinate = getCenterLocation(for: mapView).coordinate
let startingLocation = MKPlacemark(coordinate: coordinate)
let destination = MKPlacemark(coordinate: destinationCoordinate)
let request = MKDirections.Request()
request.source = MKMapItem(placemark: startingLocation)
request.destination = MKMapItem(placemark: destination)
request.transportType = transport //From Segment Controller
request.requestsAlternateRoutes = true
return request
}
我正在使用纽约市的起点和终点,那里在起点/终点之间肯定有公共交通选项。在我的iPhone(带有Apple Maps)上,Apple Maps功能能够显示我的应用失败所在的相同开始/结束位置之间的大众运输选项。
由于成功获得了行车路线/步行路线,我想知道是否需要实现.transit的其他功能。