How to make a regular MKPolyline in SWIFT with an additional argument - color

Can anyone help me with creating a custom one MKPolyline

with an optional Color argument?

CustomPolyline.swift

import Foundation
import MapKit
class CustomPolyline : MKPolyline {
    let coordinates: UnsafeMutablePointer<CLLocationCoordinate2D>
    let count : Int = 0
    let color : String = "ff0000"
    init(coordinates: UnsafeMutablePointer<CLLocationCoordinate2D>, count: Int, color: String) {

        self.coordinates = coordinates
        self.count = count
        self.color = color
    }
}

      

Init

Polyline = CustomPolyline(coordinates: &Path, count: Path.count, color: "ff0000")
self.mapView.addOverlay(Polyline)

func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {      
        if (overlay is CustomPolyline) {
            var pr = MKPolylineRenderer(overlay: overlay);
            pr.strokeColor = UIColor.colorWithRGBHex(0xff0000).colorWithAlphaComponent(0.5);
            pr.lineWidth = 10;
            return pr;
        }

        return nil
    }

      

My solution doesn't work and I can't figure out why. The polyline is not visible at all. I'm new to SWIFT, so I think the problem is with my class CustomPolyline

. Thanks for the help.

+3


source to share


2 answers


It can be done much easier than I throught:

Class

import Foundation
import MapKit

class CustomPolyline : MKPolyline {

    var color: String?
}

      



Init

cPolyline = CustomPolyline(coordinates: &Path, count: Path.count)
cPolyline.color = "#ff0000"
self.mapView.addOverlay(cPolyline)

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

            var pr = MKPolylineRenderer(overlay: overlay);
            pr.strokeColor = UIColor(rgba: overlay.color);
            pr.lineWidth = 10;
            return pr;

    }

      

+9


source


As pointed out by user 3470987, there may be a problem with changing the default delegate function "rendererForOverlay". This can also be difficult if you want to add overlays other than MKPolyline.

Class

import Foundation
import MapKit

class Polyline: MKPolyline {
    var color: UIColor?
}

      



Render function

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

    if let polyline = overlay as? Polyline {

        let polylineRenderer = MKPolylineRenderer(overlay: polyline)
        polylineRenderer.strokeColor = polyline.color
        polylineRenderer.lineWidth = 3
        return polylineRenderer
    }

    return MKOverlayRenderer(overlay: overlay)

}

      

+1


source







All Articles