There are similarly named questions, like this one, but that is not what I'm looking for.
Basically I'm drawing a bunch of MKPolygon
s on a standard map giving them a stroke, a random colour etc.. I'd like to be able to "name" them, adding a label or perhaps a UIView with a label so it looks nice. Is this possible?
Here's how my map looks like
And here's the implementation
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MacaronMKPolygon {
let macaronOverlay = overlay as! MacaronMKPolygon
let polygonView = MKPolygonRenderer(overlay: macaronOverlay)
polygonView.strokeColor = UIColor.gray
polygonView.lineWidth = 1
polygonView.alpha = shouldShowMacaron ? 1.0 : 0.0
polygonView.fillColor = macaronOverlay.color
return polygonView
}
return MKOverlayRenderer()
}
So one of the nice things with MKPolygon is that at its heart is really a type of MKMultiPoint, which inherits from MKShape, Which is a subclass of MKAnnotation. Just follow the docs all the way down from MKPolygon.
So the best part of all of this is that MKPolygon is required to conform to MKAnnotation and thus define the property for coordinate. Which is defined as the center of the annotation.
So this will give you the center of the polygon as defined by Apple. Now unfortunately with the odd shapes from your polygons it may not be the true center but should be close enough. Nice when we get some stuff for free from Apple.
Using this coordinate you can create an MKAnnotation and MKAnnotationView to lay onto of your overlays.