如何删除地图路线的折线?

时间:2018-06-07 15:33:51

标签: ios swift

大家好,我正在尝试做的是创建一个触发findRandomPlace()函数的按钮。它假设在place数组中显示一个随机位置。当它给我一个随机的地方它应该从源到目的地绘制折线(它做)然后如果我不喜欢那个地方我可以再次点击按钮它应该显示另一个地方(它做) ,问题是从最后一个位置的折线。我不知道如何删除它。

let route = response.routes[0]
self.Map.add(route.polyline, level: .aboveRoads)

上面的代码是绘制折线但是我不知道我能做些什么来删除它。 如果你能提出任何想法,请提前感谢。

var previousIndex:Int = 999999
func findRandomPlace() {//need an if statement to check if its near u or in the area
    let randomIndex = Int(arc4random_uniform(UInt32(places.count)))

    if randomIndex != previousIndex {//Makes sure next place can't be current place
        previousIndex = randomIndex

        Name.text = (places[randomIndex][0])
        Description.text = (places[randomIndex][1])


        //Draw Direction Line
        let positionX:Double? = Double(places[randomIndex][2])
        let positionY:Double? = Double(places[randomIndex][3])

        let sourceCoordinates = manager.location?.coordinate
        let destinationCoordinates = CLLocationCoordinate2DMake(positionX!, positionY!)
        print(sourceCoordinates!)

        let sourcePlacemark = MKPlacemark(coordinate: sourceCoordinates!)
        let destinationPlacemark = MKPlacemark(coordinate: destinationCoordinates)

        let sourceItem = MKMapItem(placemark: sourcePlacemark)
        let destinationItem = MKMapItem(placemark: destinationPlacemark)

        let directionRequest = MKDirectionsRequest()
        directionRequest.source = sourceItem
        directionRequest.destination = destinationItem
        directionRequest.transportType = .walking

        let directions = MKDirections(request: directionRequest)
        directions.calculate(completionHandler: {
            response, error in
            //Draw Polyline and Zoom Into It
            guard let response = response else {
                if let error = error {
                    print("error")
                }
                return
            }
            let route = response.routes[0]
            self.Map.add(route.polyline, level: .aboveRoads)
            let rect = route.polyline.boundingMapRect
            self.Map.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
        })
        } else {

            findRandomPlace()
        }

}

1 个答案:

答案 0 :(得分:1)

我自己想通了。 我很惭愧,花了这么长时间,但我很高兴我最终发现了。

self.Map.removeOverlays(self.Map.overlays)