swiftmapkitmkpolygonmkpolygonrenderer

Draw polygon on MapView using Swift


I have a MKMapView, and a set of coordinates I want to connect with a polygon to draw a rectangle. Below is my code that I have started with.

import UIKit
import MapKit

class mapViewViewController: UIViewController {
    @IBOutlet var map: MKMapView!


    override func viewDidLoad() {
        super.viewDidLoad()
        map?.delegate=self


        let startingPoint1 = ...

        let startingPoint2 = ...


        let endingPoint1 = ...

        let endingPoint2 = ...

        var coordinateInput:[CLLocationCoordinate2D]=[startingPoint1,startingPoint2,endingPoint1,endingPoint2]


        let line = MKPolygon(coordinates:&coordinateInput, count:4)

        map.addOverlay(line)


    }


extension mapViewViewController: MKMapViewDelegate{

    func map(_ map: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer{

        if overlay is MKPolygon{

            let renderer = MKPolygonRenderer(polygon: overlay as! MKPolygon)
            renderer.fillColor=UIColor.red.withAlphaComponent(0.5)
            renderer.strokeColor=UIColor.orange
            renderer.lineWidth=4
            return renderer
        }

        return MKOverlayRenderer()
    }

}

The issue I'm running into is that when I launch the map view nothing is displayed on top of the map as expected. I have confirmed all of my coordinates are valid and what I intended them to be, but my current setup is not drawing on the map as I expect. What is the correct way to accomplish this?


Solution

  • Your signature for rendererFor is incorrect. Add a breakpoint or log statement in your method and you will see it is not getting called.

    The correct signature is:

    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { ... }