首页 > 解决方案 > MapKit:如何在注释之一移动时更新地图上的折线

问题描述

我正在开发像 Uber 这样的应用程序。我成功地在地图上绘制了用户和司机之间的线,但我还想跟踪司机的动作,如何根据司机的动作更新折线。

注意:我有一个 API,可以获取驱动程序的当前位置。

let sourcePlaceMark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)
    let destinationPlaceMark = MKPlacemark(coordinate: destinationLocation, addressDictionary: nil)
    let sourceMapItem = MKMapItem(placemark: sourcePlaceMark)
    let destinationItem = MKMapItem(placemark: destinationPlaceMark)
    let sourceAnotation = MKPointAnnotation()
    sourceAnotation.title = sourceAddress
    if let location = sourcePlaceMark.location {
        sourceAnotation.coordinate = location.coordinate
    }
    let destinationAnotation = MKPointAnnotation()
    destinationAnotation.title = destinationAddress
    if let location = destinationPlaceMark.location {
        destinationAnotation.coordinate = location.coordinate
    }
    mapView.showAnnotations([sourceAnotation, destinationAnotation], animated: true)
    
    let directionRequest = MKDirections.Request()
    directionRequest.source = sourceMapItem
    directionRequest.destination = destinationItem
    directionRequest.transportType = .automobile
    let direction = MKDirections(request: directionRequest)
    direction.calculate { (response, error) in
        guard let response = response else {
            if let error = error {
                print("ERROR FOUND : \(error.localizedDescription)")
            }
            return
        }
        let route = response.routes[0]
        mapView.addOverlay(route.polyline, level: MKOverlayLevel.aboveRoads)

标签: iosswiftmapkit

解决方案


您已经完成了最重要的部分工作,获取驾驶员的位置并绘制路线。

现在,您可以简单地运行一个计时器并定期执行以下步骤:

  • 获取司机位置
  • 检查新位置是否与以前的位置不同(超过某个阈值)
  • 使用更新的位置计算新路线
  • 删除旧路线折线覆盖
  • 添加新的路线折线叠加

推荐阅读