我正在尝试在自定义表格单元中实现mapView,该表格单元显示两个位置之间的路线,但我正努力让路线显示出来。
这是我的代码:
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Get a cell to display the workout in
let cell:ChallengeTableCell = self.tableView.dequeueReusableCell(withIdentifier: "challengeTableCell") as! ChallengeTableCell
cell.mapView.delegate = self
let initialLocation = CLLocation(latitude: 51.5074, longitude: -0.1278)
let regionRadius: CLLocationDistance = 25000
let coordinateRegion = MKCoordinateRegion(center: initialLocation.coordinate,
latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
cell.mapView.setRegion(coordinateRegion, animated: false)
let startPoint = CLLocationCoordinate2D(latitude: 51.503794, longitude: -0.502074)
let endPoint = CLLocationCoordinate2D(latitude: 51.498665, longitude: 0.269378)
let sourcePlacemark = MKPlacemark(coordinate: startPoint, addressDictionary: nil)
let destinationPlacemark = MKPlacemark(coordinate: endPoint, addressDictionary: nil)
let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
let destinationMapItem = MKMapItem(placemark: destinationPlacemark)
let directionRequest = MKDirections.Request()
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("Error: \(error)")
}
return
}
let route = response.routes[0]
print(route)
cell.mapView.addOverlay((route.polyline), level: MKOverlayLevel.aboveRoads)
let rect = route.polyline.boundingMapRect
cell.mapView.setRegion(MKCoordinateRegion(rect), animated: false)
}
哪个应由委托方法调用:
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor.red
renderer.lineWidth = 4.0
return renderer
}
但是,当我测试代码时,没有绘制任何路线,我不确定下一步该怎么做。