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

标签 ios swift mapkit polyline direction

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

First View of Directions http://i.hizliresim.com/kGOvy9.png

Second View of Directions 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
}  }

最佳答案

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

var polylines: [MKPolyline]?

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

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!)
    }
}

关于ios - 如何显示一个目的地的两个或多个不同引脚的折线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41366280/

相关文章:

iOS 9 和来自 iframe 的 Safari 上的通用链接

ios - 如何设置 AudioStreamBasicDescription 属性?

swift - swift编码后无法打印数据

ios - 如何在 swift 中从枚举成员原始值创建数组字符串

google-maps - 你可以在 react 原生 map 中自定义当前位置标记吗?

iphone - 计算路线长度

ios - 在 UITableView Swift 中滚动时重复图像

ios - 续订 Apple 开发者证书

swift - 在 mapView 中为 CLLocation 数组绘制路线(Swift)

ios - MK坐标跨度制作: why specify longitude AND latitude delta?