Sorry if the topic is not that accurate. I am trying to build a map route from point to point, and the key thing is that both points are defined by the user. So I want to pass a source mapItem and destination mapItem from the interface builder and make a route between them.
What I did: I have a suggestion table view controller which suggests places for search table view controller when something is typed in search bar; then search TVC passes map annotation with name and address to the result map View. On my result map view I have two buttons: Source and Destination. So when address is passed from search TVC, mapView suggests two buttons to press. If Destination button is pressed, then it means that source map item is nil and it builds the route from my current location to destination map item. No problem here, but when Source button is pressed, source map Item is not stored and when searching for destination map item and pressing Destination button, app builds route again from my current location, ignoring that before that I pressed the Source button and I need a route not from my current location, but from source mapItem.
So in code, I have defined variables:
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!
two functions: findMe(), which searches for my current location, and buildRoute(destinationMapItem: MKMapItem), which builds a route from my current location, if source map item is nil, to the destinationMapItem.
and two buttons:
@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 are defined and recorded in Search Table View Controller. Here we unpack them using compact map and start interacting with them.)
and other stuff as adding annotations, route line to mapView, two Swift files with Suggest TVC and Search TVC. Also added the printScreen of StoryBoard to show how it is organized. storyBoard printScreen Please type if some more details are required.
So: How can I make my app remember the sourceMapItem and when Destination button is pressed build a route from point to point defined by the user?