首页 > 解决方案 > Swift 如何从我在搜索栏中定义的地图项构建路线

问题描述

抱歉,如果主题不是那么准确。我正在尝试构建从点到点的地图路线,关键是两个点都是由用户定义的。所以我想从界面生成器传递一个源 mapItem 和目标 mapItem 并在它们之间建立一个路由。

我做了什么:我有一个建议表视图控制器,当在搜索栏中输入内容时,它会建议搜索表视图控制器的位置;然后搜索 TVC 将带有名称和地址的地图注释传递给结果地图视图。在我的结果图视图中,我有两个按钮:Source 和 Destination。因此,当从搜索 TVC 传递地址时,mapView 建议按下两个按钮。如果按下 Destination 按钮,则意味着源地图项为 nil,它构建了从我当前位置到目标地图项的路线。这里没问题,但是当按下 Source 按钮时,不会存储源地图项,当搜索目标地图项并按下 Destination 按钮时,应用程序会从我当前的位置再次构建路线,忽略在此之前我按下 Source 按钮,我需要不是从我当前位置出发的路线,

所以在代码中,我定义了变量:

var mapItems: [MKMapItem]?

private var sourceMapItem: MKMapItem!

@IBOutlet weak var selectPointBmessage: UILabel!

@IBOutlet weak var resultMapView: MKMapView!

@IBOutlet weak var resultName: UILabel!
@IBOutlet weak var resultAddress: UILabel!

两个函数:findMe(),搜索我的当前位置,以及 buildRoute(destinationMapItem: MKMapItem),如果源地图项为 nil,则构建从我当前位置到destinationMapItem 的路线。

和两个按钮:

@IBAction func sourceButton(_ sender: UIButton) {
        // add searched mapItems to Array of MapItems
        sourceMapItem = mapItems!.first

    // message saying the user to find destination is source button is pressed
        selectPointBmessage.isHidden = false
}

@IBAction func buildRouteButton(_ sender: UIButton) {
        // add searched mapItems to Array of MapItems
        let destinationMapItems = mapItems!.compactMap { (mapItem) -> MKMapItem in
            let destinationMapItem = mapItem

            return destinationMapItem
        }

        // for each if several or for one if one - build a route(s) to it
            for destinationMapItem in destinationMapItems {
           buildRoute(sourceMapItem: sourceMapItem, destinationMapItem: destinationMapItem)
            }  

}

(mapItems在Search Table View Controller中定义和记录。这里我们使用compact map解包并开始与它们交互。)

和其他的东西,如添加注释、到 mapView 的路线、两个带有 Suggest TVC 和 Search TVC 的 Swift 文件。还添加了 StoryBoard 的 printScreen 以显示它是如何组织的。 storyBoard printScreen 如果需要更多详细信息,请输入。

那么:如何让我的应用记住 sourceMapItem 以及按下 Destination 按钮时构建用户定义的从点到点的路线?

标签: swiftroutesmapkit

解决方案


So I created an Array of mapItems, stored mapItems in it when table row is selected. 然后,当调用我的按钮时,使用该数组,我已将值分配给我的源点和目标点。


推荐阅读