I try to create Map view with annotations and overlays using only iOS 14 SwiftUI Map. I managed to create annotations but I am not able to create visible overlays because of lack of MKOverlayRenderer from MKMapView delegate. How can I attach to Map view delegate so it can run its method
Map(coordinateRegion: $region, showsUserLocation: true, userTrackingMode: $userTrackingMode, annotationItems: annotations)) { annotation in
MapAnnotation(coordinate: CLLocationCoordinate2DMake(annotation.latitude, annotation.longitude),
anchorPoint: CGPoint(x: 0.5, y: 0.7)) {
NavigationLink(destination: DetailsView()) {
VStack {
Image(systemName: "mappin")
.font(.title)
.foregroundColor(.red)
Text(annotation.name.split(separator: " ").joined(separator: "\n"))
.font(.caption)
.bold()
.multilineTextAlignment(.center)
.foregroundColor(.black)
.padding(2)
.background(RoundedRectangle(cornerRadius: 4).fill(Color.white.opacity(0.8)))
.layoutPriority(1)
}
}
}
}
.addOverlays(mapOverlays, delegate: mapDelegate)
and Map extension method:
extension Map {
func addOverlays(_ overlays: [MKOverlay], delegate: MKMapViewDelegate) -> some View {
// MKMapView.appearance().delegate = delegate // THIS DOES NOT WORK AT ALL
MKMapView.appearance().addOverlays(overlays)
return self
}
}
and delegate:
class MapDelegate: NSObject, MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKCircle {
let circle = MKCircleRenderer(overlay: overlay)
circle.strokeColor = .systemRed
circle.fillColor = .systemRed
circle.alpha = 0.2
circle.lineWidth = 1
return circle
}
return MKOverlayRenderer()
}
}