You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MKMapView中添加途经点/停靠点?

在MKMapView路线中添加途经点的实现方案

你需要使用MKDirections.Request的waypoints属性来添加途经点,这个属性是iOS 11及以上版本提供的,用于存放路线的中间停靠点。

修改后的实现代码

以下是支持途经点的完整代码,新增了途经点参数,并补充了基础错误处理:

private func calculateRoute(on mapView: MKMapView, 
                            from source: CLLocationCoordinate2D,
                            waypoints: [CLLocationCoordinate2D],
                            to destination: CLLocationCoordinate2D) {
    let request = MKDirections.Request()
    request.source = MKMapItem(placemark: MKPlacemark(coordinate: source))
    request.destination = MKMapItem(placemark: MKPlacemark(coordinate: destination))
    
    // 将途经点坐标转换为MKMapItem数组,赋值给request的waypoints属性
    request.waypoints = waypoints.map { 
        MKMapItem(placemark: MKPlacemark(coordinate: $0))
    }
    
    // 可选设置:让系统自动优化途经点顺序,生成更高效的路线
    request.optimizeWaypoints = true

    let directions = MKDirections(request: request)
    directions.calculate { response, error in
        guard let response = response else {
            if let error = error {
                print("路线计算失败:\(error.localizedDescription)")
            }
            return
        }

        if let route = response.routes.first {
            mapView.addOverlay(route.polyline, level: .aboveRoads)
            mapView.setVisibleMapRect(
                route.polyline.boundingMapRect,
                edgePadding: UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50),
                animated: true)
        }
    }
}

关键注意事项

  • 版本兼容:waypoints属性仅在iOS 11及以上可用,如果需要兼容更低版本,需做版本判断。
  • 途经点数量限制:苹果Maps API对免费调用的途经点数量有上限(通常最多25个),超出限制会导致请求失败。
  • 路线优化:设置optimizeWaypoints = true后,系统会自动调整途经点顺序,生成总距离/时间更优的路线;如果需要严格按照传入顺序规划路线,将该属性设为false即可。

内容的提问来源于stack exchange,提问作者jamiii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 21:36:01