Search code examples
iosswiftmapkitmkpolyline

MapKit - Change the Color/Stroke of a MKPolyline


I have already added an Overlay to my Map with the follwing code:

func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
    if overlay.isKindOfClass(MKPolyline) {
        // draw the track

        let polyLine = overlay as! MKPolyline
        let polyLineRenderer = MKPolylineRenderer(overlay: polyLine)
        polyLineRenderer.strokeColor = UIColor.blueColor()
        polyLineRenderer.lineWidth = 2.0
        return polyLineRenderer
    }

    return nil
}

Now I want to change the color or line width of that Polyline.
The only way I found to do that is:

func randomMethod()
{
    ...// find aPolyline
    self.myOverlay = aPolyLine
    self.map.removeOverlay(self.myOverlay)
    self.map.addOverlay(self.myOverlay)
}

On the mapView renderForOverLay method added this:

if (polyLine == self.myOverlay)
{
   polyLineRenderer.strokeColor = UIColor.redColor()
   polyLineRenderer.lineWidth = 5.0
}else{
   polyLineRenderer.strokeColor = UIColor.blueColor()
   polyLineRenderer.lineWidth = 2.0
 }

There has to be a better way than removing the overlay and adding it back.
Do you know any other way?


Solution

  • I don't think this is the best solution but I found a way of doing this without removing/adding the overlay.

    I keep a reference to the let polyLineRenderer = MKPolylineRenderer(overlay: polyLine) this way on my randomMethod() I can change the properties I need (stroke, lineWidth) and then just execute setNeedsDisplay() on the renderer for that polyline.

    Is this worst than the other approach? It may be.. I have to add a structure to store the renderers, but is the only way I found...