如何为一个目的地显示两个或多个不同引脚的折线?

时间:2016-12-28 16:45:38

标签: ios swift mapkit polyline direction

我正在尝试为两个或更多不同的引脚位置显示一个位置目的地,但问题是当我更改引脚的位置时,路由不会重置。例如,当我启动应用程序并设置位置时,它会显示一条路线,但是当我在地图上添加或更改位置时,之前的路线不会消失。

  

第一个方向视图   http://i.hizliresim.com/kGOvy9.png

     

第二个方向视图   http://i.hizliresim.com/pX6Ppn.png

//添加或更改目标引脚的位置

@IBAction func longpress(_ sender: UILongPressGestureRecognizer) {

    let location =  sender.location(in: self.map)
    let locCoordinate = self.map.convert(location, toCoordinateFrom: self.map)

    annotation.coordinate = locCoordinate
    annotation.title = "Store"
    annotation.subtitle = "Location of Store"

    self.map.addAnnotation(annotation)

    annotationLat = annotation.coordinate.latitude
    annotationLong = annotation.coordinate.longitude

    for item in arr {
        let dic = item as? [String: Any]
        pinDestinations(lat: dic?["lat"] as! CLLocationDegrees, long: dic?["long"] as! CLLocationDegrees)
    }

    let directions = MKDirections(request: request)

    directions.calculate { [unowned self] response, error in
        guard let unwrappedResponse = response else { return }

        for route in unwrappedResponse.routes {
            // I tried here remove previous polyline while i'm adding new one 
            self.map.removeOverlays([route.polyline])
        }
    }


func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)

    renderer.strokeColor = UIColor.blue
    renderer.lineWidth = 1
    return renderer
}  }

1 个答案:

答案 0 :(得分:0)

您可以定义属性以跟踪以前添加的折线:

var polylines: [MKPolyline]?

然后,当您更新路线时,从地图中删除旧折线(如果有),使用新值更新折线,然后将它们添加到地图中:

func updateDirections() {
    let request = ...

    let directions = MKDirections(request: request)
    directions.calculate { response, error in
        guard let response = response, error == nil else {
            print("\(error)")
            return
        }

        if let polylines = self.polylines {
            self.mapView.removeOverlays(polylines)
        }

        self.polylines = response.routes.map { $0.polyline }
        self.mapView.addOverlays(self.polylines!)
    }
}