How to draw a polygon overlay using MapKit and swift

Sicong Liu picture Sicong Liu · Jul 16, 2015 · Viewed 9.2k times · Source

I am trying to get the following code to draw a polygon on the map but for some reason it doesn't work. What did i go wrong here?

import UIKit
import MapKit

class ViewController: UIViewController {

    @IBOutlet weak var mapView: MKMapView!
    override func viewDidLoad() {
        super.viewDidLoad()
        let initialLocation = CLLocation(latitude: 49.140838, longitude: -123.127886)
        centerMapOnLocation(initialLocation)
        addBoundry()
    }


    func addBoundry()
    {
        var points=[CLLocationCoordinate2DMake(49.142677,  -123.135139),CLLocationCoordinate2DMake(49.142730, -123.125794),CLLocationCoordinate2DMake(49.140874, -123.125805),CLLocationCoordinate2DMake(49.140885, -123.135214)]

        let polygon = MKPolygon(coordinates: &points, count: points.count)

        mapView.addOverlay(polygon)
    }


    let regionRadius: CLLocationDistance = 1000
    func centerMapOnLocation(location: CLLocation) {
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
            regionRadius * 2.0, regionRadius * 2.0)
        mapView.setRegion(coordinateRegion, animated: true)
    }


}


func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
        if overlay is MKPolygon {
        let polygonView = MKPolygonRenderer(overlay: overlay)
        polygonView.strokeColor = UIColor.magentaColor()

        return polygonView
    }

    return nil
}

Answer

Rob picture Rob · Jul 16, 2015

It would appear that you've implemented mapView(_:renderFor:) (previously known as rendererForOverlay) as a global function. The method must be within the ViewController class definition or, even better, to keep our code nicely organized, within a MKMapViewDelegate extension:

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

Also, make sure that you've defined the view controller to be the delegate of the map view. It's probably easiest to do that in IB, but you can also do it in viewDidLoad:

mapView.delegate = self