Twitter khuong291
Twitter khuong291

Reputation: 11692

How to remove draw route on map

I have implemented draw route on the map with this function:

func drawRouteOnMap(sourceLocation sourceLocation: CLLocation, destinationLocation: CLLocation) {
        drawMapActivated = true
        let sourcePlacemark = MKPlacemark(coordinate: sourceLocation.coordinate, addressDictionary: nil)
        let destinationPlacemark = MKPlacemark(coordinate: destinationLocation.coordinate, addressDictionary: nil)

        let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
        let destinationMapItem = MKMapItem(placemark: destinationPlacemark)

        let destinationAnnotation = MKPointAnnotation()
        destinationAnnotation.title = "ATM"

        if let location = destinationPlacemark.location {
            destinationAnnotation.coordinate = location.coordinate
        }

        self.mapView.showAnnotations([destinationAnnotation], animated: true)

        let directionRequest = MKDirectionsRequest()
        directionRequest.source = sourceMapItem
        directionRequest.destination = destinationMapItem
        directionRequest.transportType = .Automobile

        let directions = MKDirections(request: directionRequest)

        directions.calculateDirectionsWithCompletionHandler {
            (response, error) -> Void in

            guard let response = response else {
                if let error = error {
                    print("Error: \(error)")
                }

                return
            }

            let route = response.routes[0]
            self.mapView.addOverlay((route.polyline), level: MKOverlayLevel.AboveRoads)

            let rect = route.polyline.boundingMapRect
            self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
        }

    }

But the problem here is when I want to draw another route, it override the previous route, so it look very ugly. I want to delete the old one, and draw a new one, how to do this.

Any helps would be appreciated, thanks.

Upvotes: 1

Views: 1810

Answers (1)

Twitter khuong291
Twitter khuong291

Reputation: 11692

I have tried like this:

mapView.removeOverlays(mapView.overlays)

And it works now.

Upvotes: 9

Related Questions