MKMapView Object is unexpectedly found nil while unwrapping an Optional value

151 Views Asked by At

I've written these two functions to draw overlay and working fine at viewDidLoad().

However, I have to display updated overlay by passing new coordinates on a click event.

First function is to get Latitudes and Longitudes of locations in CLLocationCoordinate2D type Array. Second function is to draw an overlay with those coordinates.

Problem I'm facing is MKMapView object in function drawpolyline(loclist: Array<CLLocationCoordinate2D>) nil every time I call this function on a click.

Here is the function:

func drawline(locs: Array<Location>){
    var loclist: Array<CLLocationCoordinate2D> = []

    if (locs.count > 3){

        for loc in locs{
            if (loc.gps == 1){
                let cord = CLLocationCoordinate2D(latitude: loc.lat!, longitude: loc.lon!)
                loclist.append(cord)
                }
            }
        }

   drawpolyline(loclist: loclist)

}

Function to draw overlay is:

func drawpolyline(loclist: Array<CLLocationCoordinate2D>){
    if(loclist != nil && loclist.count > 1){

         if let overlays = self.mainMapView?.overlays {
            self.mainMapView.removeOverlays(overlays)
            }
        if let annotations = self.mainMapView?.annotations {
            self.mainMapView.removeAnnotations(annotations)
            }

        let startmark = loclist.first
        let endmark = loclist.last
        let cord1 = CLLocationCoordinate2D(latitude: (startmark?.latitude)!, longitude: (startmark?.longitude)!)

        let polyline = MKPolyline(coordinates: loclist, count: loclist.count)
        print(polyline.pointCount)

        let mapAnnotation = MKPointAnnotation();
        mapAnnotation.title = Common.SelectedDevice?.dn;
        mapAnnotation.subtitle = Common.SelectedDevice?.dn;
        mapAnnotation.coordinate = cord1
        self.iconImage = Common.getIcon((Common.SelectedDevice?.icon)!, ign:(Common.SelectedDevice?.ign!)!)
        self.addDefaultMapPin("Start" , coordinates: startmark!)
        self.addDefaultMapPin("end" , coordinates: endmark!)

            self.mainMapView.add(polyline)
            self.mainMapView.addAnnotation(mapAnnotation);
            self.zoomPolyline(polyline)


    }
    else{
        configureMap()
    }

}
0

There are 0 best solutions below