我做了一个视图控制器,一旦打开视图就跟踪我的位置。按下routeButton后,我想要显示蓝色折线。但事实并非如此。我设置了代理并编写了渲染函数,但它仍然没有显示。计算方向时我没有收到错误。它确实运行self.map.add(route.polyline, level: .aboveRoads)
线。但是没有折线添加到地图中。我已经在这里阅读了与此相关的多个问题,但没有任何问题可以解决我的问题。任何帮助将不胜感激。
继承我的代码:
class ThirdViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate{
var startLocCoord = CLLocation()
var endLocCoord = CLLocation()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.05,0.05)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
map.setRegion(region, animated: true)
self.map.showsUserLocation = true
}
@IBAction func routeButton (_ sender: Any) {
let destinationLoc = CLLocationCoordinate2D(latitude: endLocCoord.coordinate.latitude, longitude: endLocCoord.coordinate.longitude)
let sourceLoc = CLLocationCoordinate2D(latitude: startLocCoord.coordinate.latitude, longitude: startLocCoord.coordinate.longitude)
let sourcePlaceMark = MKPlacemark(coordinate: sourceLoc)
let destinationPlaceMark = MKPlacemark(coordinate: destinationLoc)
let directionRequest = MKDirectionsRequest()
directionRequest.source = MKMapItem(placemark: sourcePlaceMark)
directionRequest.destination = MKMapItem(placemark: destinationPlaceMark)
directionRequest.transportType = .automobile
let directions = MKDirections(request: directionRequest)
directions.calculate { (response, error) in
guard let directionResponse = response else {
if let error = error {
print("Error with directions==\(error.localizedDescription)")
}
return
}
let route = directionResponse.routes[0]
print("route ------->", route)
self.map.add(route.polyline, level: .aboveRoads)
let rect = route.polyline.boundingMapRect
self.map.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
print(self.srcLat, self.srcLon, self.lat, self.long)
}
override func viewDidLoad() {
manager.desiredAccuracy = kCLLocationAccuracyBest
UIApplication.shared.isIdleTimerDisabled = true
manager.delegate = self
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
manager.allowsBackgroundLocationUpdates = true
manager.pausesLocationUpdatesAutomatically = false
self.map.isZoomEnabled = false
self.map.isScrollEnabled = false
self.map.delegate = self
map.mapType = MKMapType.standard
}
func mapView(_mapView: MKMapView, rendererFor overlay: MKOverlay)-> MKOverlayRenderer{
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor.blue
renderer.lineWidth = 5.0
print("render called")
return renderer
}
}
谢谢
这可能只是一个错字。更换
func mapView(_mapView: MKMapView, rendererFor overlay: MKOverlay)-> MKOverlayRenderer{
同
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {