MKDirections: направления недоступны
Я создаю приложение, подобное UBER, и я использую MapKit, я хочу отобразить маршрут между двумя местоположениями, и для этого я использую следующий код
viewMap.delegate = self
let sourceLocation = CLLocationCoordinate2D(latitude: sourceLatitude, longitude: sourceLongitude)
let destinationLocation = CLLocationCoordinate2D(latitude: destinationLatitude, longitude: destinationLongitude)
let sourcePlacemark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)
let destinationPlacemark = MKPlacemark(coordinate: destinationLocation, addressDictionary: nil)
let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
let destinationMapItem = MKMapItem(placemark: destinationPlacemark)
let sourceAnnotation = MKPointAnnotation()
sourceAnnotation.title = strSource
if let location = sourcePlacemark.location {
sourceAnnotation.coordinate = location.coordinate
}
let destinationAnnotation = MKPointAnnotation()
destinationAnnotation.title = strDestination
if let location = destinationPlacemark.location {
destinationAnnotation.coordinate = location.coordinate
}
self.viewMap.showAnnotations([sourceAnnotation,destinationAnnotation], animated: true )
let directionRequest = MKDirectionsRequest()
directionRequest.source = sourceMapItem
directionRequest.destination = destinationMapItem
directionRequest.transportType = .automobile
let directions = MKDirections(request: directionRequest)
directions.calculate {
(response, error) -> Void in
guard let response = response else {
if let error = error {
print("Route Error: \(error)")
}
return
}
let route = response.routes[0]
self.viewMap.add((route.polyline), level: MKOverlayLevel.aboveRoads)
let rect = route.polyline.boundingMapRect
self.viewMap.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
}
расширение HomeVC: MKMapViewDelegate
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
renderer.lineWidth = 2.0
return renderer
}
Я проверил все возможные решения, и я также получаю широту и долготу исходных и конечных местоположений, но я все еще не работает, и я получаю следующую ошибку.
Пожалуйста, помогите мне с этим!
2 ответа
Направления карт Apple доступны только для определенных стран. Пожалуйста, проверьте полный список здесь. Список доступности карты Apple (проверьте в разделе " Карты": "Направления "). Вам следует изучить Google Map SDK, поскольку ваше приложение ориентировано на страны, не указанные в приведенной выше ссылке.
Это работает для меня и рисует пункт назначения на карте MK, а также фокусируется на пункт назначения
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
let request = MKDirectionsRequest()
request.source = MKMapItem.forCurrentLocation()
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: (view.annotation?.coordinate)!))
request.requestsAlternateRoutes = true
request.requestsAlternateRoutes = true
request.transportType = .walking
let directions = MKDirections(request: request)
directions.calculate { [unowned self] response, error in
guard let unwrappedResponse = response else { return }
for route in unwrappedResponse.routes {
self.myMapView.add(route.polyline) self.myMapView.setVisibleMapRect(route.polyline.boundingMapRect, animated: true)
return
}
}
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let polyLine = overlay
let polyLineRenderer = MKPolylineRenderer(overlay: polyLine)
polyLineRenderer.strokeColor = UIColor.blue
polyLineRenderer.lineWidth = 2.0
return polyLineRenderer
}
это работает, когда вы нажимаете на MKAnnotationView, если вы хотите рисовать из другого кода, вам просто нужно вырезать код для вашей функции и изменить линию
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: (view.annotation?.coordinate)!))
в
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: (CLLocationCoordinate2D(/*Your Location*/))!))