-
Notifications
You must be signed in to change notification settings - Fork 312
/
NavigationMapView.swift
1185 lines (983 loc) · 57.4 KB
/
NavigationMapView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Foundation
import Mapbox
import MapboxDirections
import MapboxCoreNavigation
import Turf
/**
`NavigationMapView` is a subclass of `MGLMapView` with convenience functions for adding `Route` lines to a map.
*/
@objc(MBNavigationMapView)
open class NavigationMapView: MGLMapView, UIGestureRecognizerDelegate {
// MARK: Class Constants
struct FrameIntervalOptions {
fileprivate static let durationUntilNextManeuver: TimeInterval = 7
fileprivate static let durationSincePreviousManeuver: TimeInterval = 3
fileprivate static let defaultFramesPerSecond: Int = 60
fileprivate static let pluggedInFramesPerSecond: Int = 30
fileprivate static let decreasedFramesPerSecond: Int = 5
}
/**
Returns the altitude that the map camera initally defaults to.
*/
@objc public static let defaultAltitude: CLLocationDistance = 1000.0
/**
Returns the altitude the map conditionally zooms out to when user is on a motorway, and the maneuver length is sufficently long.
*/
@objc public static let zoomedOutMotorwayAltitude: CLLocationDistance = 2000.0
/**
Returns the threshold for what the map considers a "long-enough" maneuver distance to trigger a zoom-out when the user enters a motorway.
*/
@objc public static let longManeuverDistance: CLLocationDistance = 1000.0
/**
Maximum distance the user can tap for a selection to be valid when selecting an alternate route.
*/
@objc public var tapGestureDistanceThreshold: CGFloat = 50
/**
The object that acts as the navigation delegate of the map view.
*/
public weak var navigationMapDelegate: NavigationMapViewDelegate?
/**
The object that acts as the course tracking delegate of the map view.
*/
public weak var courseTrackingDelegate: NavigationMapViewCourseTrackingDelegate?
let sourceOptions: [MGLShapeSourceOption: Any] = [.maximumZoomLevel: 16]
// MARK: - Instance Properties
let sourceIdentifier = "routeSource"
let sourceCasingIdentifier = "routeCasingSource"
let routeLayerIdentifier = "routeLayer"
let routeLayerCasingIdentifier = "routeLayerCasing"
let waypointSourceIdentifier = "waypointsSource"
let waypointCircleIdentifier = "waypointsCircle"
let waypointSymbolIdentifier = "waypointsSymbol"
let arrowSourceIdentifier = "arrowSource"
let arrowSourceStrokeIdentifier = "arrowSourceStroke"
let arrowLayerIdentifier = "arrowLayer"
let arrowSymbolLayerIdentifier = "arrowSymbolLayer"
let arrowLayerStrokeIdentifier = "arrowStrokeLayer"
let arrowCasingSymbolLayerIdentifier = "arrowCasingSymbolLayer"
let arrowSymbolSourceIdentifier = "arrowSymbolSource"
let instructionSource = "instructionSource"
let instructionLabel = "instructionLabel"
let instructionCircle = "instructionCircle"
@objc dynamic public var trafficUnknownColor: UIColor = .trafficUnknown
@objc dynamic public var trafficLowColor: UIColor = .trafficLow
@objc dynamic public var trafficModerateColor: UIColor = .trafficModerate
@objc dynamic public var trafficHeavyColor: UIColor = .trafficHeavy
@objc dynamic public var trafficSevereColor: UIColor = .trafficSevere
@objc dynamic public var routeCasingColor: UIColor = .defaultRouteCasing
@objc dynamic public var routeAlternateColor: UIColor = .defaultAlternateLine
@objc dynamic public var routeAlternateCasingColor: UIColor = .defaultAlternateLineCasing
@objc dynamic public var maneuverArrowColor: UIColor = .defaultManeuverArrow
@objc dynamic public var maneuverArrowStrokeColor: UIColor = .defaultManeuverArrowStroke
var userLocationForCourseTracking: CLLocation?
var animatesUserLocation: Bool = false
var altitude: CLLocationDistance = defaultAltitude
var routes: [Route]?
fileprivate var preferredFramesPerSecond: Int = 60 {
didSet {
if #available(iOS 10.0, *) {
displayLink?.preferredFramesPerSecond = preferredFramesPerSecond
} else {
displayLink?.frameInterval = FrameIntervalOptions.defaultFramesPerSecond / preferredFramesPerSecond
}
}
}
var shouldPositionCourseViewFrameByFrame = false {
didSet {
if shouldPositionCourseViewFrameByFrame {
preferredFramesPerSecond = FrameIntervalOptions.defaultFramesPerSecond
}
}
}
var showsRoute: Bool {
get {
return style?.layer(withIdentifier: routeLayerIdentifier) != nil
}
}
open override var showsUserLocation: Bool {
get {
if tracksUserCourse || userLocationForCourseTracking != nil {
return !(userCourseView?.isHidden ?? true)
}
return super.showsUserLocation
}
set {
if tracksUserCourse || userLocationForCourseTracking != nil {
super.showsUserLocation = false
if userCourseView == nil {
userCourseView = UserPuckCourseView(frame: CGRect(origin: .zero, size: CGSize(width: 75, height: 75)))
}
userCourseView?.isHidden = !newValue
} else {
userCourseView?.isHidden = true
super.showsUserLocation = newValue
}
}
}
/**
Center point of the user course view in screen coordinates relative to the map view.
- seealso: NavigationMapViewDelegate.navigationMapViewUserAnchorPoint(_:)
*/
var userAnchorPoint: CGPoint {
if let anchorPoint = navigationMapDelegate?.navigationMapViewUserAnchorPoint?(self), anchorPoint != .zero {
return anchorPoint
}
let contentFrame = UIEdgeInsetsInsetRect(bounds, contentInset)
let courseViewWidth = userCourseView?.frame.width ?? 0
let courseViewHeight = userCourseView?.frame.height ?? 0
let edgePadding = UIEdgeInsets(top: 50 + courseViewHeight / 2,
left: 50 + courseViewWidth / 2,
bottom: 50 + courseViewHeight / 2,
right: 50 + courseViewWidth / 2)
return CGPoint(x: max(min(contentFrame.midX,
contentFrame.maxX - edgePadding.right),
contentFrame.minX + edgePadding.left),
y: max(max(min(contentFrame.minY + contentFrame.height * 0.8,
contentFrame.maxY - edgePadding.bottom),
contentFrame.minY + edgePadding.top),
contentFrame.minY + contentFrame.height * 0.5))
}
/**
Determines whether the map should follow the user location and rotate when the course changes.
- seealso: NavigationMapViewCourseTrackingDelegate
*/
open var tracksUserCourse: Bool = false {
didSet {
if tracksUserCourse {
enableFrameByFrameCourseViewTracking(for: 2)
altitude = NavigationMapView.defaultAltitude
showsUserLocation = true
courseTrackingDelegate?.navigationMapViewDidStartTrackingCourse?(self)
} else {
courseTrackingDelegate?.navigationMapViewDidStopTrackingCourse?(self)
}
if let location = userLocationForCourseTracking {
updateCourseTracking(location: location, animated: true)
}
}
}
/**
A `UIView` used to indicate the user’s location and course on the map.
If the view conforms to `UserCourseView`, its `UserCourseView.update(location:pitch:direction:animated:)` method is frequently called to ensure that its visual appearance matches the map’s camera.
*/
@objc public var userCourseView: UIView? {
didSet {
oldValue?.removeFromSuperview()
if let userCourseView = userCourseView {
if let location = userLocationForCourseTracking {
updateCourseTracking(location: location, animated: false)
} else {
userCourseView.center = userAnchorPoint
}
addSubview(userCourseView)
}
}
}
private lazy var mapTapGesture = UITapGestureRecognizer(target: self, action: #selector(didRecieveTap(sender:)))
//MARK: - Initalizers
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
commonInit()
}
public override init(frame: CGRect, styleURL: URL?) {
super.init(frame: frame, styleURL: styleURL)
commonInit()
}
fileprivate func commonInit() {
makeGestureRecognizersRespectCourseTracking()
makeGestureRecognizersUpdateCourseView()
resumeNotifications()
}
deinit {
suspendNotifications()
}
//MARK: - Overrides
open override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
let image = UIImage(named: "feedback-map-error", in: .mapboxNavigation, compatibleWith: nil)
let imageView = UIImageView(image: image)
imageView.contentMode = .center
imageView.backgroundColor = .gray
imageView.frame = bounds
addSubview(imageView)
}
open override func layoutSubviews() {
super.layoutSubviews()
//If the map is in tracking mode, make sure we update the camera after the layout pass.
if (tracksUserCourse) {
updateCourseTracking(location: userLocationForCourseTracking, animated: false)
}
}
open override func anchorPoint(forGesture gesture: UIGestureRecognizer) -> CGPoint {
if tracksUserCourse {
return userAnchorPoint
} else {
return super.anchorPoint(forGesture: gesture)
}
}
open override func mapViewDidFinishRenderingFrameFullyRendered(_ fullyRendered: Bool) {
super.mapViewDidFinishRenderingFrameFullyRendered(fullyRendered)
guard shouldPositionCourseViewFrameByFrame else { return }
guard let location = userLocationForCourseTracking else { return }
userCourseView?.center = convert(location.coordinate, toPointTo: self)
}
// MARK: - Notifications
func resumeNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(progressDidChange(_:)), name: .routeControllerProgressDidChange, object: nil)
let gestures = gestureRecognizers ?? []
let mapTapGesture = self.mapTapGesture
mapTapGesture.requireFailure(of: gestures)
addGestureRecognizer(mapTapGesture)
}
func suspendNotifications() {
NotificationCenter.default.removeObserver(self, name: .routeControllerProgressDidChange, object: nil)
}
@objc func progressDidChange(_ notification: Notification) {
guard tracksUserCourse else { return }
let routeProgress = notification.userInfo![RouteControllerNotificationUserInfoKey.routeProgressKey] as! RouteProgress
let stepProgress = routeProgress.currentLegProgress.currentStepProgress
let expectedTravelTime = stepProgress.step.expectedTravelTime
let durationUntilNextManeuver = stepProgress.durationRemaining
let durationSincePreviousManeuver = expectedTravelTime - durationUntilNextManeuver
guard !UIDevice.current.isPluggedIn else {
preferredFramesPerSecond = FrameIntervalOptions.pluggedInFramesPerSecond
return
}
if let upcomingStep = routeProgress.currentLegProgress.upComingStep,
upcomingStep.maneuverDirection == .straightAhead || upcomingStep.maneuverDirection == .slightLeft || upcomingStep.maneuverDirection == .slightRight {
preferredFramesPerSecond = shouldPositionCourseViewFrameByFrame ? FrameIntervalOptions.defaultFramesPerSecond : FrameIntervalOptions.decreasedFramesPerSecond
} else if durationUntilNextManeuver > FrameIntervalOptions.durationUntilNextManeuver &&
durationSincePreviousManeuver > FrameIntervalOptions.durationSincePreviousManeuver {
preferredFramesPerSecond = shouldPositionCourseViewFrameByFrame ? FrameIntervalOptions.defaultFramesPerSecond : FrameIntervalOptions.decreasedFramesPerSecond
} else {
preferredFramesPerSecond = FrameIntervalOptions.pluggedInFramesPerSecond
}
}
// Track position on a frame by frame basis. Used for first location update and when resuming tracking mode
func enableFrameByFrameCourseViewTracking(for duration: TimeInterval) {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(disableFrameByFramePositioning), object: nil)
perform(#selector(disableFrameByFramePositioning), with: nil, afterDelay: duration)
shouldPositionCourseViewFrameByFrame = true
}
//MARK: - User Tracking
@objc fileprivate func disableFrameByFramePositioning() {
shouldPositionCourseViewFrameByFrame = false
}
@objc private func disableUserCourseTracking() {
tracksUserCourse = false
}
@objc public func updateCourseTracking(location: CLLocation?, animated: Bool) {
let duration: TimeInterval = animated ? 1 : 0
animatesUserLocation = animated
userLocationForCourseTracking = location
guard let location = location, CLLocationCoordinate2DIsValid(location.coordinate) else {
return
}
if tracksUserCourse {
let point = userAnchorPoint
let padding = UIEdgeInsets(top: point.y, left: point.x, bottom: bounds.height - point.y, right: bounds.width - point.x)
let newCamera = MGLMapCamera(lookingAtCenter: location.coordinate, fromDistance: altitude, pitch: 45, heading: location.course)
let function: CAMediaTimingFunction? = animated ? CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) : nil
setCamera(newCamera, withDuration: duration, animationTimingFunction: function, edgePadding: padding, completionHandler: nil)
} else {
UIView.animate(withDuration: duration, delay: 0, options: [.curveLinear, .beginFromCurrentState], animations: {
self.userCourseView?.center = self.convert(location.coordinate, toPointTo: self)
}, completion: nil)
}
if let userCourseView = userCourseView as? UserCourseView {
if let customTransformation = userCourseView.update?(location: location, pitch: camera.pitch, direction: direction, animated: animated, tracksUserCourse: tracksUserCourse) {
customTransformation
} else {
self.userCourseView?.applyDefaultUserPuckTransformation(location: location, pitch: camera.pitch, direction: direction, animated: animated, tracksUserCourse: tracksUserCourse)
}
} else {
userCourseView?.applyDefaultUserPuckTransformation(location: location, pitch: camera.pitch, direction: direction, animated: animated, tracksUserCourse: tracksUserCourse)
}
}
//MARK: - Gesture Recognizers
/**
Fired when NavigationMapView detects a tap not handled elsewhere by other gesture recognizers.
*/
@objc func didRecieveTap(sender: UITapGestureRecognizer) {
guard let routes = routes, let tapPoint = sender.point else { return }
let waypointTest = waypoints(on: routes, closeTo: tapPoint) //are there waypoints near the tapped location?
if let selected = waypointTest?.first { //test passes
navigationMapDelegate?.navigationMapView?(self, didSelect: selected)
return
} else if let routes = self.routes(closeTo: tapPoint) {
guard let selectedRoute = routes.first else { return }
navigationMapDelegate?.navigationMapView?(self, didSelect: selectedRoute)
}
}
@objc func updateCourseView(_ sender: UIGestureRecognizer) {
preferredFramesPerSecond = FrameIntervalOptions.defaultFramesPerSecond
if sender.state == .ended {
altitude = self.camera.altitude
enableFrameByFrameCourseViewTracking(for: 2)
}
// Capture altitude for double tap and two finger tap after animation finishes
if sender is UITapGestureRecognizer, sender.state == .ended {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3, execute: {
self.altitude = self.camera.altitude
})
}
if let pan = sender as? UIPanGestureRecognizer {
if sender.state == .ended || sender.state == .cancelled {
let velocity = pan.velocity(in: self)
let didFling = sqrt(velocity.x * velocity.x + velocity.y * velocity.y) > 100
if didFling {
enableFrameByFrameCourseViewTracking(for: 1)
}
}
}
if sender.state == .changed {
guard let location = userLocationForCourseTracking else { return }
userCourseView?.layer.removeAllAnimations()
userCourseView?.center = convert(location.coordinate, toPointTo: self)
}
}
// MARK: Feature Addition/Removal
/**
Adds or updates both the route line and the route line casing
*/
@objc public func showRoutes(_ routes: [Route], legIndex: Int = 0) {
guard let style = style else { return }
guard let mainRoute = routes.first else { return }
self.routes = routes
let polylines = navigationMapDelegate?.navigationMapView?(self, shapeFor: routes) ?? shape(for: routes, legIndex: legIndex)
let mainPolylineSimplified = navigationMapDelegate?.navigationMapView?(self, simplifiedShapeFor: mainRoute) ?? shape(forCasingOf: mainRoute, legIndex: legIndex)
if let source = style.source(withIdentifier: sourceIdentifier) as? MGLShapeSource,
let sourceSimplified = style.source(withIdentifier: sourceCasingIdentifier) as? MGLShapeSource {
source.shape = polylines
sourceSimplified.shape = mainPolylineSimplified
} else {
let lineSource = MGLShapeSource(identifier: sourceIdentifier, shape: polylines, options: nil)
let lineCasingSource = MGLShapeSource(identifier: sourceCasingIdentifier, shape: mainPolylineSimplified, options: nil)
style.addSource(lineSource)
style.addSource(lineCasingSource)
let line = navigationMapDelegate?.navigationMapView?(self, routeStyleLayerWithIdentifier: routeLayerIdentifier, source: lineSource) ?? routeStyleLayer(identifier: routeLayerIdentifier, source: lineSource)
let lineCasing = navigationMapDelegate?.navigationMapView?(self, routeCasingStyleLayerWithIdentifier: routeLayerCasingIdentifier, source: lineCasingSource) ?? routeCasingStyleLayer(identifier: routeLayerCasingIdentifier, source: lineSource)
for layer in style.layers.reversed() {
if !(layer is MGLSymbolStyleLayer) &&
layer.identifier != arrowLayerIdentifier && layer.identifier != arrowSymbolLayerIdentifier && layer.identifier != arrowCasingSymbolLayerIdentifier && layer.identifier != arrowLayerStrokeIdentifier && layer.identifier != waypointCircleIdentifier {
style.insertLayer(line, below: layer)
style.insertLayer(lineCasing, below: line)
break
}
}
}
}
/**
Removes route line and route line casing from map
*/
@objc public func removeRoutes() {
guard let style = style else {
return
}
if let line = style.layer(withIdentifier: routeLayerIdentifier) {
style.removeLayer(line)
}
if let lineCasing = style.layer(withIdentifier: routeLayerCasingIdentifier) {
style.removeLayer(lineCasing)
}
if let lineSource = style.source(withIdentifier: sourceIdentifier) {
style.removeSource(lineSource)
}
if let lineCasingSource = style.source(withIdentifier: sourceCasingIdentifier) {
style.removeSource(lineCasingSource)
}
}
/**
Adds the route waypoints to the map given the current leg index. Previous waypoints for completed legs will be omitted.
*/
@objc public func showWaypoints(_ route: Route, legIndex: Int = 0) {
guard let style = style else {
return
}
let waypoints = Array(route.legs.map { $0.destination }.dropLast())
let source = navigationMapDelegate?.navigationMapView?(self, shapeFor: waypoints, legIndex: legIndex) ?? shape(for: waypoints, legIndex: legIndex)
if route.routeOptions.waypoints.count > 2 { //are we on a multipoint route?
routes = [route] //update the model
if let waypointSource = style.source(withIdentifier: waypointSourceIdentifier) as? MGLShapeSource {
waypointSource.shape = source
} else {
let sourceShape = MGLShapeSource(identifier: waypointSourceIdentifier, shape: source, options: sourceOptions)
style.addSource(sourceShape)
let circles = navigationMapDelegate?.navigationMapView?(self, waypointStyleLayerWithIdentifier: waypointCircleIdentifier, source: sourceShape) ?? routeWaypointCircleStyleLayer(identifier: waypointCircleIdentifier, source: sourceShape)
let symbols = navigationMapDelegate?.navigationMapView?(self, waypointSymbolStyleLayerWithIdentifier: waypointSymbolIdentifier, source: sourceShape) ?? routeWaypointSymbolStyleLayer(identifier: waypointSymbolIdentifier, source: sourceShape)
if let arrowLayer = style.layer(withIdentifier: arrowCasingSymbolLayerIdentifier) {
style.insertLayer(circles, below: arrowLayer)
} else {
style.addLayer(circles)
}
style.insertLayer(symbols, above: circles)
}
}
if let lastLeg = route.legs.last {
removeAnnotations(annotations ?? [])
let destination = MGLPointAnnotation()
destination.coordinate = lastLeg.destination.coordinate
addAnnotation(destination)
}
}
/**
Removes all waypoints from the map.
*/
@objc public func removeWaypoints() {
guard let style = style else { return }
removeAnnotations(annotations ?? [])
if let circleLayer = style.layer(withIdentifier: waypointCircleIdentifier) {
style.removeLayer(circleLayer)
}
if let symbolLayer = style.layer(withIdentifier: waypointSymbolIdentifier) {
style.removeLayer(symbolLayer)
}
if let waypointSource = style.source(withIdentifier: waypointSourceIdentifier) {
style.removeSource(waypointSource)
}
if let circleSource = style.source(withIdentifier: waypointCircleIdentifier) {
style.removeSource(circleSource)
}
if let symbolSource = style.source(withIdentifier: waypointSymbolIdentifier) {
style.removeSource(symbolSource)
}
}
/**
Shows the step arrow given the current `RouteProgress`.
*/
@objc public func addArrow(route: Route, legIndex: Int, stepIndex: Int) {
guard route.legs.indices.contains(legIndex),
route.legs[legIndex].steps.indices.contains(stepIndex) else { return }
let step = route.legs[legIndex].steps[stepIndex]
let maneuverCoordinate = step.maneuverLocation
guard let routeCoordinates = route.coordinates else { return }
guard let style = style else {
return
}
guard let triangleImage = Bundle.mapboxNavigation.image(named: "triangle")?.withRenderingMode(.alwaysTemplate).tinted(maneuverArrowColor) else { return }
style.setImage(triangleImage, forName: "triangle-tip-navigation")
guard step.maneuverType != .arrive else { return }
let minimumZoomLevel: Float = 14.5
let shaftLength = max(min(30 * metersPerPoint(atLatitude: maneuverCoordinate.latitude), 30), 10)
let polyline = Polyline(routeCoordinates)
let shaftCoordinates = Array(polyline.trimmed(from: maneuverCoordinate, distance: -shaftLength).coordinates.reversed()
+ polyline.trimmed(from: maneuverCoordinate, distance: shaftLength).coordinates.suffix(from: 1))
if shaftCoordinates.count > 1 {
var shaftStrokeCoordinates = shaftCoordinates
let shaftStrokePolyline = ArrowStrokePolyline(coordinates: &shaftStrokeCoordinates, count: UInt(shaftStrokeCoordinates.count))
let shaftDirection = shaftStrokeCoordinates[shaftStrokeCoordinates.count - 2].direction(to: shaftStrokeCoordinates.last!)
let maneuverArrowStrokePolylines = [shaftStrokePolyline]
let shaftPolyline = ArrowFillPolyline(coordinates: shaftCoordinates, count: UInt(shaftCoordinates.count))
let arrowShape = MGLShapeCollection(shapes: [shaftPolyline])
let arrowStrokeShape = MGLShapeCollection(shapes: maneuverArrowStrokePolylines)
let arrowSourceStroke = MGLShapeSource(identifier: arrowSourceStrokeIdentifier, shape: arrowStrokeShape, options: sourceOptions)
let arrowStroke = MGLLineStyleLayer(identifier: arrowLayerStrokeIdentifier, source: arrowSourceStroke)
let arrowSource = MGLShapeSource(identifier: arrowSourceIdentifier, shape: arrowShape, options: sourceOptions)
let arrow = MGLLineStyleLayer(identifier: arrowLayerIdentifier, source: arrowSource)
if let source = style.source(withIdentifier: arrowSourceIdentifier) as? MGLShapeSource {
source.shape = arrowShape
} else {
arrow.minimumZoomLevel = minimumZoomLevel
arrow.lineCap = NSExpression(forConstantValue: "butt")
arrow.lineJoin = NSExpression(forConstantValue: "round")
arrow.lineWidth = NSExpression(format: "mgl_interpolate:withCurveType:parameters:stops:($zoomLevel, 'linear', nil, %@)", MBRouteLineWidthByZoomLevel.multiplied(by: 0.70))
arrow.lineColor = NSExpression(forConstantValue: maneuverArrowColor)
style.addSource(arrowSource)
style.addLayer(arrow)
}
if let source = style.source(withIdentifier: arrowSourceStrokeIdentifier) as? MGLShapeSource {
source.shape = arrowStrokeShape
} else {
arrowStroke.minimumZoomLevel = arrow.minimumZoomLevel
arrowStroke.lineCap = arrow.lineCap
arrowStroke.lineJoin = arrow.lineJoin
arrowStroke.lineWidth = NSExpression(format: "mgl_interpolate:withCurveType:parameters:stops:($zoomLevel, 'linear', nil, %@)", MBRouteLineWidthByZoomLevel.multiplied(by: 0.80))
arrowStroke.lineColor = NSExpression(forConstantValue: maneuverArrowStrokeColor)
style.addSource(arrowSourceStroke)
style.insertLayer(arrowStroke, below: arrow)
}
// Arrow symbol
let point = MGLPointFeature()
point.coordinate = shaftStrokeCoordinates.last!
let arrowSymbolSource = MGLShapeSource(identifier: arrowSymbolSourceIdentifier, features: [point], options: sourceOptions)
if let source = style.source(withIdentifier: arrowSymbolSourceIdentifier) as? MGLShapeSource {
source.shape = arrowSymbolSource.shape
if let arrowSymbolLayer = style.layer(withIdentifier: arrowSymbolLayerIdentifier) as? MGLSymbolStyleLayer {
arrowSymbolLayer.iconRotation = NSExpression(forConstantValue: shaftDirection as NSNumber)
}
if let arrowSymbolLayerCasing = style.layer(withIdentifier: arrowCasingSymbolLayerIdentifier) as? MGLSymbolStyleLayer {
arrowSymbolLayerCasing.iconRotation = NSExpression(forConstantValue: shaftDirection as NSNumber)
}
} else {
let arrowSymbolLayer = MGLSymbolStyleLayer(identifier: arrowSymbolLayerIdentifier, source: arrowSymbolSource)
arrowSymbolLayer.minimumZoomLevel = minimumZoomLevel
arrowSymbolLayer.iconImageName = NSExpression(forConstantValue: "triangle-tip-navigation")
arrowSymbolLayer.iconColor = NSExpression(forConstantValue: maneuverArrowColor)
arrowSymbolLayer.iconRotationAlignment = NSExpression(forConstantValue: "map")
arrowSymbolLayer.iconRotation = NSExpression(forConstantValue: shaftDirection as NSNumber)
arrowSymbolLayer.iconScale = NSExpression(format: "mgl_interpolate:withCurveType:parameters:stops:($zoomLevel, 'linear', nil, %@)", MBRouteLineWidthByZoomLevel.multiplied(by: 0.12))
arrowSymbolLayer.iconAllowsOverlap = NSExpression(forConstantValue: true)
let arrowSymbolLayerCasing = MGLSymbolStyleLayer(identifier: arrowCasingSymbolLayerIdentifier, source: arrowSymbolSource)
arrowSymbolLayerCasing.minimumZoomLevel = arrowSymbolLayer.minimumZoomLevel
arrowSymbolLayerCasing.iconImageName = arrowSymbolLayer.iconImageName
arrowSymbolLayerCasing.iconColor = NSExpression(forConstantValue: maneuverArrowStrokeColor)
arrowSymbolLayerCasing.iconRotationAlignment = arrowSymbolLayer.iconRotationAlignment
arrowSymbolLayerCasing.iconRotation = arrowSymbolLayer.iconRotation
arrowSymbolLayerCasing.iconScale = NSExpression(format: "mgl_interpolate:withCurveType:parameters:stops:($zoomLevel, 'linear', nil, %@)", MBRouteLineWidthByZoomLevel.multiplied(by: 0.14))
arrowSymbolLayerCasing.iconAllowsOverlap = arrowSymbolLayer.iconAllowsOverlap
style.addSource(arrowSymbolSource)
style.insertLayer(arrowSymbolLayer, above: arrow)
style.insertLayer(arrowSymbolLayerCasing, below: arrow)
}
}
}
/**
Removes the step arrow from the map.
*/
@objc public func removeArrow() {
guard let style = style else {
return
}
if let arrowLayer = style.layer(withIdentifier: arrowLayerIdentifier) {
style.removeLayer(arrowLayer)
}
if let arrowLayerStroke = style.layer(withIdentifier: arrowLayerStrokeIdentifier) {
style.removeLayer(arrowLayerStroke)
}
if let arrowSymbolLayer = style.layer(withIdentifier: arrowSymbolLayerIdentifier) {
style.removeLayer(arrowSymbolLayer)
}
if let arrowCasingSymbolLayer = style.layer(withIdentifier: arrowCasingSymbolLayerIdentifier) {
style.removeLayer(arrowCasingSymbolLayer)
}
if let arrowSource = style.source(withIdentifier: arrowSourceIdentifier) {
style.removeSource(arrowSource)
}
if let arrowStrokeSource = style.source(withIdentifier: arrowSourceStrokeIdentifier) {
style.removeSource(arrowStrokeSource)
}
if let arrowSymboleSource = style.source(withIdentifier: arrowSymbolSourceIdentifier) {
style.removeSource(arrowSymboleSource)
}
}
// MARK: Utility Methods
/** Modifies the gesture recognizers to also disable course tracking. */
func makeGestureRecognizersRespectCourseTracking() {
for gestureRecognizer in gestureRecognizers ?? []
where gestureRecognizer is UIPanGestureRecognizer || gestureRecognizer is UIRotationGestureRecognizer {
gestureRecognizer.addTarget(self, action: #selector(disableUserCourseTracking))
}
}
func makeGestureRecognizersUpdateCourseView() {
for gestureRecognizer in gestureRecognizers ?? [] {
gestureRecognizer.addTarget(self, action: #selector(updateCourseView(_:)))
}
}
//TODO: Change to point-based distance calculation
private func waypoints(on routes: [Route], closeTo point: CGPoint) -> [Waypoint]? {
let tapCoordinate = convert(point, toCoordinateFrom: self)
let multipointRoutes = routes.filter { $0.routeOptions.waypoints.count >= 3}
guard multipointRoutes.count > 0 else { return nil }
let waypoints = multipointRoutes.flatMap({$0.routeOptions.waypoints})
//lets sort the array in order of closest to tap
let closest = waypoints.sorted { (left, right) -> Bool in
let leftDistance = left.coordinate.distance(to: tapCoordinate)
let rightDistance = right.coordinate.distance(to: tapCoordinate)
return leftDistance < rightDistance
}
//lets filter to see which ones are under threshold
let candidates = closest.filter({
let coordinatePoint = self.convert($0.coordinate, toPointTo: self)
return coordinatePoint.distance(to: point) < tapGestureDistanceThreshold
})
return candidates
}
private func routes(closeTo point: CGPoint) -> [Route]? {
let tapCoordinate = convert(point, toCoordinateFrom: self)
//do we have routes? If so, filter routes with at least 2 coordinates.
guard let routes = routes?.filter({ $0.coordinates?.count ?? 0 > 1 }) else { return nil }
//Sort routes by closest distance to tap gesture.
let closest = routes.sorted { (left, right) -> Bool in
//existance has been assured through use of filter.
let leftLine = Polyline(left.coordinates!)
let rightLine = Polyline(right.coordinates!)
let leftDistance = leftLine.closestCoordinate(to: tapCoordinate)!.distance
let rightDistance = rightLine.closestCoordinate(to: tapCoordinate)!.distance
return leftDistance < rightDistance
}
//filter closest coordinates by which ones are under threshold.
let candidates = closest.filter {
let closestCoordinate = Polyline($0.coordinates!).closestCoordinate(to: tapCoordinate)!.coordinate
let closestPoint = self.convert(closestCoordinate, toPointTo: self)
return closestPoint.distance(to: point) < tapGestureDistanceThreshold
}
return candidates
}
func shape(for routes: [Route], legIndex: Int?) -> MGLShape? {
guard let firstRoute = routes.first else { return nil }
guard let congestedRoute = addCongestion(to: firstRoute, legIndex: legIndex) else { return nil }
var altRoutes: [MGLPolylineFeature] = []
for route in routes.suffix(from: 1) {
let polyline = MGLPolylineFeature(coordinates: route.coordinates!, count: UInt(route.coordinates!.count))
polyline.attributes["isAlternateRoute"] = true
altRoutes.append(polyline)
}
return MGLShapeCollectionFeature(shapes: altRoutes + congestedRoute)
}
func addCongestion(to route: Route, legIndex: Int?) -> [MGLPolylineFeature]? {
guard let coordinates = route.coordinates else { return nil }
var linesPerLeg: [[MGLPolylineFeature]] = []
for (index, leg) in route.legs.enumerated() {
// If there is no congestion, don't try and add it
guard let legCongestion = leg.segmentCongestionLevels else {
return [MGLPolylineFeature(coordinates: route.coordinates!, count: UInt(route.coordinates!.count))]
}
guard legCongestion.count + 1 <= coordinates.count else {
return [MGLPolylineFeature(coordinates: route.coordinates!, count: UInt(route.coordinates!.count))]
}
// The last coord of the preceding step, is shared with the first coord of the next step.
// We don't need both.
var legCoordinates = Array(leg.steps.compactMap {
$0.coordinates?.suffix(from: 1)
}.joined())
// We need to add the first coord of the route in.
if let firstCoord = leg.steps.first?.coordinates?.first {
legCoordinates.insert(firstCoord, at: 0)
}
// We're trying to create a sequence that conforms to `((segmentStartCoordinate, segmentEndCoordinate), segmentCongestionLevel)`.
// This is represents a segment on the route and it's associated congestion level.
let segments = zip(legCoordinates, legCoordinates.suffix(from: 1)).map { [$0.0, $0.1] }
let congestionSegments = Array(zip(segments, legCongestion))
// Merge adjacent segments with the same congestion level
var mergedCongestionSegments = [CongestionSegment]()
for seg in congestionSegments {
let coordinates = seg.0
let congestionLevel = seg.1
if let last = mergedCongestionSegments.last, last.1 == congestionLevel {
mergedCongestionSegments[mergedCongestionSegments.count - 1].0 += coordinates
} else {
mergedCongestionSegments.append(seg)
}
}
let lines = mergedCongestionSegments.map { (congestionSegment: CongestionSegment) -> MGLPolylineFeature in
let polyline = MGLPolylineFeature(coordinates: congestionSegment.0, count: UInt(congestionSegment.0.count))
polyline.attributes[MBCongestionAttribute] = String(describing: congestionSegment.1)
if let legIndex = legIndex {
polyline.attributes[MBCurrentLegAttribute] = index == legIndex
} else {
polyline.attributes[MBCurrentLegAttribute] = index == 0
}
polyline.attributes["isAlternateRoute"] = false
return polyline
}
linesPerLeg.append(lines)
}
return Array(linesPerLeg.joined())
}
func shape(forCasingOf route: Route, legIndex: Int?) -> MGLShape? {
var linesPerLeg: [MGLPolylineFeature] = []
for (index, leg) in route.legs.enumerated() {
let legCoordinates = Array(leg.steps.compactMap {
$0.coordinates
}.joined())
let polyline = MGLPolylineFeature(coordinates: legCoordinates, count: UInt(legCoordinates.count))
if let legIndex = legIndex {
polyline.attributes[MBCurrentLegAttribute] = index == legIndex
} else {
polyline.attributes[MBCurrentLegAttribute] = index == 0
}
linesPerLeg.append(polyline)
}
return MGLShapeCollectionFeature(shapes: linesPerLeg)
}
func shape(for waypoints: [Waypoint], legIndex: Int) -> MGLShape? {
var features = [MGLPointFeature]()
for (waypointIndex, waypoint) in waypoints.enumerated() {
let feature = MGLPointFeature()
feature.coordinate = waypoint.coordinate
feature.attributes = [
"waypointCompleted": waypointIndex < legIndex,
"name": waypointIndex + 1
]
features.append(feature)
}
return MGLShapeCollectionFeature(shapes: features)
}
func routeWaypointCircleStyleLayer(identifier: String, source: MGLSource) -> MGLStyleLayer {
let circles = MGLCircleStyleLayer(identifier: waypointCircleIdentifier, source: source)
let opacity = NSExpression(forConditional: NSPredicate(format: "waypointCompleted == true"), trueExpression: NSExpression(forConstantValue: 0.5), falseExpression: NSExpression(forConstantValue: 1))
circles.circleColor = NSExpression(forConstantValue: UIColor(red:0.9, green:0.9, blue:0.9, alpha:1.0))
circles.circleOpacity = opacity
circles.circleRadius = NSExpression(forConstantValue: 10)
circles.circleStrokeColor = NSExpression(forConstantValue: UIColor.black)
circles.circleStrokeWidth = NSExpression(forConstantValue: 1)
circles.circleStrokeOpacity = opacity
return circles
}
func routeWaypointSymbolStyleLayer(identifier: String, source: MGLSource) -> MGLStyleLayer {
let symbol = MGLSymbolStyleLayer(identifier: identifier, source: source)
symbol.text = NSExpression(format: "CAST(name, 'NSString')")
symbol.textOpacity = NSExpression(forConditional: NSPredicate(format: "waypointCompleted == true"), trueExpression: NSExpression(forConstantValue: 0.5), falseExpression: NSExpression(forConstantValue: 1))
symbol.textFontSize = NSExpression(forConstantValue: 10)
symbol.textHaloWidth = NSExpression(forConstantValue: 0.25)
symbol.textHaloColor = NSExpression(forConstantValue: UIColor.black)
return symbol
}
func routeStyleLayer(identifier: String, source: MGLSource) -> MGLStyleLayer {
let line = MGLLineStyleLayer(identifier: identifier, source: source)
line.lineWidth = NSExpression(format: "mgl_interpolate:withCurveType:parameters:stops:($zoomLevel, 'linear', nil, %@)", MBRouteLineWidthByZoomLevel)
line.lineOpacity = NSExpression(forConditional:
NSPredicate(format: "isAlternateRoute == true"),
trueExpression: NSExpression(forConstantValue: 1),
falseExpression: NSExpression(forConditional: NSPredicate(format: "isCurrentLeg == true"),
trueExpression: NSExpression(forConstantValue: 1),
falseExpression: NSExpression(forConstantValue: 0)))
line.lineColor = NSExpression(format: "TERNARY(isAlternateRoute == true, %@, MGL_MATCH(congestion, 'low' , %@, 'moderate', %@, 'heavy', %@, 'severe', %@, %@))", routeAlternateColor, trafficLowColor, trafficModerateColor, trafficHeavyColor, trafficSevereColor, trafficUnknownColor)
line.lineJoin = NSExpression(forConstantValue: "round")
return line
}
func routeCasingStyleLayer(identifier: String, source: MGLSource) -> MGLStyleLayer {
let lineCasing = MGLLineStyleLayer(identifier: identifier, source: source)
// Take the default line width and make it wider for the casing
lineCasing.lineWidth = NSExpression(format: "mgl_interpolate:withCurveType:parameters:stops:($zoomLevel, 'linear', nil, %@)", MBRouteLineWidthByZoomLevel.multiplied(by: 1.5))
lineCasing.lineColor = NSExpression(forConditional: NSPredicate(format: "isAlternateRoute == true"),
trueExpression: NSExpression(forConstantValue: routeAlternateCasingColor),
falseExpression: NSExpression(forConstantValue: routeCasingColor))
lineCasing.lineCap = NSExpression(forConstantValue: "round")
lineCasing.lineJoin = NSExpression(forConstantValue: "round")
lineCasing.lineOpacity = NSExpression(forConditional: NSPredicate(format: "isAlternateRoute == true"),
trueExpression: NSExpression(forConstantValue: 1),
falseExpression: NSExpression(forConditional: NSPredicate(format: "isCurrentLeg == true"), trueExpression: NSExpression(forConstantValue: 1), falseExpression: NSExpression(forConstantValue: 0.85)))
return lineCasing
}
/**
Attempts to localize road labels into the local language and other labels
into the system’s preferred language.
When this property is enabled, the style automatically modifies the `text`
property of any symbol style layer whose source is the
<a href="https://www.mapbox.com/vector-tiles/mapbox-streets-v7/#overview">Mapbox
Streets source</a>. On iOS, the user can set the system’s preferred
language in Settings, General Settings, Language & Region.
Unlike the `MGLStyle.localizeLabels(into:)` method, this method localizes
road labels into the local language, regardless of the system’s preferred
language, in an effort to match road signage. The turn banner always
displays road names and exit destinations in the local language, so you
should call this method in the
`MGLMapViewDelegate.mapView(_:didFinishLoading:)` method of any delegate of
a standalone `NavigationMapView`. The map view embedded in
`NavigationViewController` is localized automatically, so you do not need
to call this method on the value of `NavigationViewController.mapView`.
*/
@objc public func localizeLabels() {
guard let style = style else {
return
}
let streetsSourceIdentifiers = style.sources.compactMap {
$0 as? MGLVectorTileSource
}.filter {
$0.isMapboxStreets
}.map {
$0.identifier
}
for layer in style.layers where layer is MGLSymbolStyleLayer {
let layer = layer as! MGLSymbolStyleLayer
guard let sourceIdentifier = layer.sourceIdentifier,
streetsSourceIdentifiers.contains(sourceIdentifier) else {
continue
}
guard let text = layer.text else {
continue
}
// Road labels should match road signage.
let locale = layer.sourceLayerIdentifier == "road_label" ? Locale(identifier: "mul") : nil
let localizedText = text.mgl_expressionLocalized(into: locale)
if localizedText != text {
layer.text = localizedText
}
}
}
@objc public func showVoiceInstructionsOnMap(route: Route) {
guard let style = style else {
return
}
var features = [MGLPointFeature]()
for (legIndex, leg) in route.legs.enumerated() {
for (stepIndex, step) in leg.steps.enumerated() {
for instruction in step.instructionsSpokenAlongStep! {
let feature = MGLPointFeature()
feature.coordinate = Polyline(route.legs[legIndex].steps[stepIndex].coordinates!.reversed()).coordinateFromStart(distance: instruction.distanceAlongStep)!
feature.attributes = [ "instruction": instruction.text ]
features.append(feature)
}
}
}
let instructionPointSource = MGLShapeCollectionFeature(shapes: features)
if let instructionSource = style.source(withIdentifier: instructionSource) as? MGLShapeSource {