ModelDelegate+ViewController.swift 6.19 KB
Newer Older
asahiocean's avatar
asahiocean committed
1
import UIKit
asahiocean's avatar
asahiocean committed
2
import MapKit
asahiocean's avatar
asahiocean committed
3
4
5
import CoreLocation

extension ViewController: ModelDelegate {
asahiocean's avatar
asahiocean committed
6
7
8
9
10
11
12
    
    func deselectPin(pin annotation: PinAnnotation) {
        mapView.deselectAnnotation(annotation, animated: true)
        guard let view = mapView.view(for: annotation) else { return }
        if let marker = view as? MKMarkerAnnotationView  {
            marker.markerTintColor = annotation.markerColor
        }
asahiocean's avatar
asahiocean committed
13
14
15
    }
    
    func modelButtonExecute(sender: UIButton) {
asahiocean's avatar
asahiocean committed
16
        let m = mapView.model
asahiocean's avatar
commit    
asahiocean committed
17
18
19
        let tag = Model.buttonTag(rawValue: sender.tag)
        switch tag {
        case .graphs:
asahiocean's avatar
asahiocean committed
20
21
            print("Trying to build graphs...")
            constructGraphs()
asahiocean's avatar
commit    
asahiocean committed
22
23
24
25
26
27
28
29
30
        case .start:
            if m.selected != nil {
                print("User has chosen a starting point!")
            } else { /* ... */ }
        case .finish:
            if m.selected != nil {
                print("User selected endpoint!")
            } else { /* ... */ }
        case .routecalc:
asahiocean's avatar
asahiocean committed
31
            print("Trying to make the shortest route!")
asahiocean's avatar
asahiocean committed
32
            let coords = m.route.compactMap({ $0.coordinate })
asahiocean's avatar
asahiocean committed
33
34
            
            for (i,coord) in coords.enumerated() {
asahiocean's avatar
asahiocean committed
35
                if (i+1) < coords.count {
asahiocean's avatar
asahiocean committed
36
37
38
39
                    createRouteTo(from: coord, to: coords[i+1])
                }
            }
            mainButton?.removeTarget(nil, action: nil, for: .allEvents)
asahiocean's avatar
commit    
asahiocean committed
40
        case .clear:
asahiocean's avatar
asahiocean committed
41
42
43
44
45
46
47
            clearingMap()
            print("❌ Clearing the map...")
        default: fatalError()
        }
    }
    
    func createRouteTo(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) {
48
49
        let CLL2DIsValid = CLLocationCoordinate2DIsValid
        if CLL2DIsValid(from) && CLL2DIsValid(to) {
asahiocean's avatar
asahiocean committed
50
51
52
53
54
            let dirRequest = MKDirections.Request()
            dirRequest.source = .init(placemark: .init(coordinate: from))
            dirRequest.destination = .init(placemark: .init(coordinate: to))
            dirRequest.requestsAlternateRoutes = false
            dirRequest.transportType = .any
asahiocean's avatar
asahiocean committed
55
            
asahiocean's avatar
asahiocean committed
56
            let directions = MKDirections(request: dirRequest)
asahiocean's avatar
asahiocean committed
57
            
asahiocean's avatar
asahiocean committed
58
59
            directions.calculate { [self] (resp, error) in
                guard let response = resp else {
asahiocean's avatar
asahiocean committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
                    if let error = error {
                        // MARK: Error message while building a route
                        let alert = UIAlertController(title: "FAILED TO CREATE A ROUTE",
                                                      message: error.localizedDescription, preferredStyle: .alert)
                        alert.addAction(.init(title: "Remove annotations", style: .destructive, handler: {_ in clearingMap() }))
                        present(alert, animated: true)
                    }
                    return
                }
                enum TransportType: UInt {
                    case automobile = 1, walking, transit
                    var value: String {
                        switch self {
                        case .automobile: return "car"
                        case .walking: return "walk"
                        case .transit: return "transit"
                        }
                    }
                }
                guard let route = response.routes.first else { return }
                mapView.addOverlay(route.polyline)
                let transport = (TransportType(rawValue: route.transportType.rawValue)?.value ?? "")
                mapView.model.mainButton?.setTitle("\(Int((route.expectedTravelTime)/60)) min / \(transport)", for: .normal)
            }
        }
    }
    
    // Clearing the entire map of annotations and overlays (including graphs)
    fileprivate func clearingMap() {
        DispatchQueue.main.async { [mapView] () -> Void in
            mapView?.model.pins.removeAll()
            mapView?.model.route.removeAll()
            mapView?.model.graphsBuilt = false
            mapView?.overlays.forEach({ mapView?.removeOverlay($0) })
            mapView?.annotations.forEach({ mapView?.removeAnnotation($0) })
        }
asahiocean's avatar
asahiocean committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
    }
    
    internal func constructGraphs() {
        mapView.removeOverlays(mapView.overlays)
        
        let pins = mapView.annotations.filter({ $0.isKind(of: PinAnnotation.self) })
        let coords = pins.compactMap({ $0.coordinate })
        
        coords.forEach({ (start: CLLocationCoordinate2D) in
            let vertices = coords.filter({ $0 != start }) // getting all vertices excluding the starting point
            
            vertices.forEach({ (end: CLLocationCoordinate2D) in // enumeration of all vertices
                let locations = [start, end] // start and end vertices
                
                // MARK: вершины соединены ребрами при условии, что расстояние между вершинами не более 5км
                // condition: vertices are connected by edges, provided that the distance between the vertices is no more than 5 km
                if locations.distance < 5000 {
                    let dashline = DashLine(locations: locations)
                    
                    // you can also delegate the storage of all vertices and graphs
                    // to into a separate class in which can their compare for find matches
                    let exists = mapView.overlays.contains(where: { $0.coordinate == dashline.coordinate })
                    
                    guard !exists else { return }
                    
                    // creating a graph between vertices
                    mapView?.addOverlay(dashline)
                    
                    if !mapView.model.graphsBuilt { mapView.model.graphsBuilt = true }
                    
                    #if DEBUG
                    print("graphs count:", mapView.overlays.count)
                    #endif
                } else {
                    let alert = UIAlertController(title: "Point is too far away!",
                                                  message: "The distance between the vertices should not be more than 5 km.",
                                                  preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "ОК", style: .cancel))
                    present(alert, animated: true)
                }
            })
        })
    }
}