Search code examples
iosswiftmkmapviewmkpolyline

Polyline Overlay in Swift


I have my MKMapViewDelegate in place. Also, MapView.delegate = self

let c1 = myCLLocationCoodinate
let c2 = myCLLocationCoodinate2
var a = [c1, c2]
var polyline = MKPolyline(coordinates: &a, count: a.count)
self.MapView.addOverlay(polyline)

With this Delegate Method:

func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {

    if overlay is MKPolyline {
        var polylineRenderer = MKPolylineRenderer(overlay: overlay)
        polylineRenderer.strokeColor = UIColor.whiteColor()
        polylineRenderer.lineWidth = 2 
        return polylineRenderer
    }
    return nil
}

I get this: EXC BAD ACCESS Thread 8 on

self.MapView.addOverlay(polyline)

Solution

  • I think issue here is with the line:

    var a = [c1, c2]
    

    Here you directly created array without specifying its type.

    See below reference code to create Polyline overlay and related delegate method:

    let c1 = myCLLocationCoodinate
    let c2 = myCLLocationCoodinate2
    
    var points: [CLLocationCoordinate2D]
    points = [c1, c2]
    
    var geodesic = MKGeodesicPolyline(coordinates: &points[0], count: 2)
    mapView.add(geodesic)
    
    UIView.animate(withDuration: 1.5, animations: { () -> Void in
        let span = MKCoordinateSpanMake(20, 20)
        let region1 = MKCoordinateRegion(center: c1, span: span)
        mapView.setRegion(region1, animated: true)
    })
    

    A delegate method to render overlay:

    func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
    
       if overlay is MKPolyline {
           var polylineRenderer = MKPolylineRenderer(overlay: overlay)
           polylineRenderer.strokeColor = UIColor.whiteColor()
           polylineRenderer.lineWidth = 2 
           return polylineRenderer
       } 
       return nil
    }