I am trying to have different colors for each Polyline in MapKit in Swift. Here is a simplified example.
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if let overlay_ = overlay as? MKPolyline {
let renderer = MKPolylineRenderer(overlay: overlay)
if overlay_.title == "2" {
renderer.strokeColor = UIColor.red
} else {
renderer.strokeColor = UIColor.blue
}
renderer.lineWidth = 5
return renderer
} else {
return MKOverlayRenderer()
}
}
I have multiple polylines in a map where I set different overlay.title to differentiate between the colors.
Unfortunately it always take the last set color and applies it to all polylines.
In my example below I have 3 polylines with title: "0", "1" and "2". The result is red stroke color for all polylines.
Does anyone has an idea how to fix this? Do you need more code?
Code to add title:
func showAllRoutes(map: MKMapView, route: Routes) {
var coordinates: [CLLocationCoordinate2D] = []
if dm.show_all_routes {
for x in route.routes.indices {
for y in route.routes[x].route_numbers {
coordinates.append(CLLocationCoordinate2D(latitude: dm.alle_staende.locations[y].latitude, longitude:dm.alle_staende.locations[y].longitude))
}
let overlay = MKPolyline(coordinates: coordinates, count: coordinates.count)
overlay.subtitle = "Route"
overlay.title = "\(x)"
map.addOverlay(overlay)
}
}
}
Got it. The problem is:
var coordinates: [CLLocationCoordinate2D] = []
It was placed wrong, it adds all lines and then they are basically the same. That's why they have the same color
func showAllRoutes(map: MKMapView, route: Routes) {
if dm.show_all_routes {
for x in route.routes.indices {
var coordinates: [CLLocationCoordinate2D] = []
for y in route.routes[x].route_numbers {
coordinates.append(CLLocationCoordinate2D(latitude: dm.alle_staende.locations[y].latitude, longitude:dm.alle_staende.locations[y].longitude))
}
let overlay = MKPolyline(coordinates: coordinates, count: coordinates.count)
overlay.subtitle = "Route"
overlay.title = "\(x)"
map.addOverlay(overlay)
}
}
}