Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a label in the center of a polygon in MapKit

There are similarly named questions, like this one, but that is not what I'm looking for.

Basically I'm drawing a bunch of MKPolygons 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

enter image description here

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()
}
like image 484
kernelpanic Avatar asked Oct 15 '25 18:10

kernelpanic


1 Answers

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.

polygonView.coordinate

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.

like image 155
Binary Platypus Avatar answered Oct 17 '25 07:10

Binary Platypus