Hi I'm trying to create an overlay around my annotations, like apples reminders app, I have already created an MKCircle object which I think I should use to show the overlay but how do I convert my MKCircle object into an MKOVerlay object? maybe there's a better way to add annotations? I'm new to swift and programming. Any suggestions?
MKCircle
is a MKOverlay
object. You just need to add it as an overlay:
let circle = MKCircle(center: coordinate, radius: 1000)
mapView.add(circle)
Of course, you have to tell the map how to render it by implementing mapView(_:rendererFor:)
in your delegate and instantiate a MKCircleRenderer
for the MKCircle
that’s passed as an overlay.
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKCircleRenderer(overlay: overlay)
renderer.fillColor = UIColor.cyan.withAlphaComponent(0.5)
renderer.strokeColor = UIColor.cyan.withAlphaComponent(0.8)
return renderer
}
}
Clearly, make sure you specified the delegate
for your MKMapView
, too. And if you have other types of renderers, you might implement specific logic for those, too, e.g.
extension ViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if let circle = overlay as? MKCircle {
let renderer = MKCircleRenderer(circle: circle)
renderer.fillColor = UIColor.cyan.withAlphaComponent(0.5)
renderer.strokeColor = UIColor.cyan.withAlphaComponent(0.8)
return renderer
}
if let polygon = overlay as? MKPolygon {
let renderer = MKPolygonRenderer(polygon: polygon)
renderer.fillColor = UIColor.blue.withAlphaComponent(0.5)
renderer.strokeColor = UIColor.blue.withAlphaComponent(0.8)
return renderer
}
if let polyline = overlay as? MKPolyline {
let renderer = MKPolylineRenderer(polyline: polyline)
renderer.fillColor = UIColor.red.withAlphaComponent(0.5)
renderer.strokeColor = UIColor.red.withAlphaComponent(0.8)
return renderer
}
fatalError("Unexpected overlay type")
}
}