The code provided creates an MKMapView, adds it to the view controller's view hierarchy, and adds either a single annotation or a polyline to the map based on the number of markers it retrieves. However, there is one missing piece: The MKMapViewDelegate method used to render the polyline is not yet implemented.
To render the polyline, you will need to:
- Set the
delegate property of the map to self.
- Implement the
mapView(_:rendererFor:) delegate method to provide a renderer for the polyline.
Below is your modified MapViewController with these steps implemented:
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate {
@IBAction func onBack(_ sender: Any) {
dismiss(animated: true)
}
private let map: MKMapView = {
let mapView = MKMapView()
return mapView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.insertSubview(map, at: 0)
// Set the map's delegate to self
map.delegate = self
// Add pins for markers
let markers = Marker.getMarkers()
if markers.count == 1 {
let marker = markers[0]
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: marker.latitude, longitude: marker.longitude)
map.addAnnotation(annotation)
} else {
var lineCoords = [CLLocationCoordinate2D]()
for marker in markers {
lineCoords.append(CLLocationCoordinate2D(latitude: marker.latitude, longitude: marker.longitude))
}
let line = MKPolyline(coordinates: lineCoords, count: lineCoords.count)
map.addOverlay(line)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
map.frame = view.bounds
}
// MARK: MKMapViewDelegate
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if let polyline = overlay as? MKPolyline {
let renderer = MKPolylineRenderer(polyline: polyline)
renderer.strokeColor = .blue // Set line color
renderer.lineWidth = 3.0 // Set line width
return renderer
}
return MKOverlayRenderer(overlay: overlay)
}
}
Please note:
- The
MKMapViewDelegate must be conformed to by the MapViewController class.
- The
map.delegate = self line is added in viewDidLoad() to tell the map that the MapViewController class will handle its delegate callbacks.
- The
mapView(_:rendererFor:) delegate method is implemented, which checks if the overlay is an MKPolyline and then creates and returns an MKPolylineRenderer.
After these changes, the polyline should render correctly on the map with the specified color and line width. Remember to adjust any specifics for the MKPolylineRenderer as needed for your app, such as the strokeColor and lineWidth properties.