-
Notifications
You must be signed in to change notification settings - Fork 313
/
NavigationMapView.swift
1090 lines (895 loc) · 50.7 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
let identifierNamespace = Bundle.mapboxNavigation.bundleIdentifier ?? ""
/**
`NavigationMapView` is a subclass of `MGLMapView` with convenience functions for adding `Route` lines to a map.
*/
open class NavigationMapView: MGLMapView, UIGestureRecognizerDelegate {
// MARK: Class Constants
struct FrameIntervalOptions {
static let durationUntilNextManeuver: TimeInterval = 7
static let durationSincePreviousManeuver: TimeInterval = 3
static let defaultFramesPerSecond = MGLMapViewPreferredFramesPerSecond.maximum
static let pluggedInFramesPerSecond = MGLMapViewPreferredFramesPerSecond.lowPower
}
/**
The minimum preferred frames per second at which to render map animations.
This property takes effect when the application has limited resources for animation, such as when the device is running on battery power. By default, this property is set to `MGLMapViewPreferredFramesPerSecond.lowPower`.
*/
public var minimumFramesPerSecond = MGLMapViewPreferredFramesPerSecond(20)
/**
Returns the altitude that the map camera initally defaults to.
*/
public var 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.
*/
public var 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.
*/
public var longManeuverDistance: CLLocationDistance = 1000.0
/**
Maximum distance the user can tap for a selection to be valid when selecting an alternate route.
*/
public var tapGestureDistanceThreshold: CGFloat = 50
/**
The object that acts as the navigation delegate of the map view.
*/
public weak var navigationMapViewDelegate: NavigationMapViewDelegate?
@available(swift, obsoleted: 0.1, renamed: "navigationMapViewDelegate")
public weak var navigationMapDelegate: NavigationMapViewDelegate? {
fatalError()
}
/**
The object that acts as the course tracking delegate of the map view.
*/
public weak var courseTrackingDelegate: NavigationMapViewCourseTrackingDelegate?
let sourceOptions: [MGLShapeSourceOption: Any] = [.maximumZoomLevel: 16]
struct SourceIdentifier {
static let route = "\(identifierNamespace).route"
static let routeCasing = "\(identifierNamespace).routeCasing"
static let waypoint = "\(identifierNamespace).waypoints"
static let waypointCircle = "\(identifierNamespace).waypointsCircle"
static let waypointSymbol = "\(identifierNamespace).waypointsSymbol"
static let arrow = "\(identifierNamespace).arrow"
static let arrowSymbol = "\(identifierNamespace).arrowSymbol"
static let arrowStroke = "\(identifierNamespace).arrowStroke"
static let instruction = "\(identifierNamespace).instruction"
}
struct StyleLayerIdentifier {
static let namespace = Bundle.mapboxNavigation.bundleIdentifier ?? ""
static let route = "\(identifierNamespace).route"
static let routeCasing = "\(identifierNamespace).routeCasing"
static let waypointCircle = "\(identifierNamespace).waypointsCircle"
static let waypointSymbol = "\(identifierNamespace).waypointsSymbol"
static let arrow = "\(identifierNamespace).arrow"
static let arrowSymbol = "\(identifierNamespace).arrowSymbol"
static let arrowStroke = "\(identifierNamespace).arrowStroke"
static let arrowCasingSymbol = "\(identifierNamespace).arrowCasingSymbol"
static let instructionLabel = "\(identifierNamespace).instructionLabel"
static let instructionCircle = "\(identifierNamespace).instructionCircle"
}
// MARK: - Instance Properties
@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
var routes: [Route]?
var isAnimatingToOverheadMode = false
var shouldPositionCourseViewFrameByFrame = false {
didSet {
if shouldPositionCourseViewFrameByFrame {
preferredFramesPerSecond = .maximum
}
}
}
var showsRoute: Bool {
get {
return style?.layer(withIdentifier: StyleLayerIdentifier.route) != nil
}
}
open override var showsUserLocation: Bool {
get {
if tracksUserCourse || userLocationForCourseTracking != nil {
return !(userCourseView.isHidden)
}
return super.showsUserLocation
}
set {
if tracksUserCourse || userLocationForCourseTracking != nil {
super.showsUserLocation = false
userCourseView.isHidden = !newValue
} else {
userCourseView.isHidden = true
super.showsUserLocation = newValue
}
}
}
/**
The minimum default insets from the content frame to the edges of the user course view.
*/
static let courseViewMinimumInsets = UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50)
/**
Center point of the user course view in screen coordinates relative to the map view.
- seealso: NavigationMapViewDelegate.navigationMapViewUserAnchorPoint(_:)
*/
var userAnchorPoint: CGPoint {
if let anchorPoint = navigationMapViewDelegate?.navigationMapViewUserAnchorPoint(self), anchorPoint != .zero {
return anchorPoint
}
let contentFrame = bounds.inset(by: contentInset)
return CGPoint(x: contentFrame.midX, y: contentFrame.midY)
}
/**
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: 3)
altitude = defaultAltitude
showsUserLocation = true
courseTrackingDelegate?.navigationMapViewDidStartTrackingCourse(self)
} else {
courseTrackingDelegate?.navigationMapViewDidStopTrackingCourse(self)
}
if let location = userLocationForCourseTracking {
updateCourseTracking(location: location, animated: true)
}
}
}
/**
A type that represents a `UIView` that is `CourseUpdatable`.
*/
public typealias UserCourseView = UIView & CourseUpdatable
/**
A `UserCourseView` used to indicate the user’s location and course on the map.
The `UserCourseView`'s `UserCourseView.update(location:pitch:direction:animated:)` method is frequently called to ensure that its visual appearance matches the map’s camera.
*/
public var userCourseView: UserCourseView = UserPuckCourseView(frame: CGRect(origin: .zero, size: 75.0)) {
didSet {
oldValue.removeFromSuperview()
installUserCourseView()
}
}
private lazy var mapTapGesture = UITapGestureRecognizer(target: self, action: #selector(didRecieveTap(sender:)))
//MARK: - Initalizers
public override init(frame: CGRect) {
altitude = defaultAltitude
super.init(frame: frame)
commonInit()
}
public required init?(coder decoder: NSCoder) {
altitude = defaultAltitude
super.init(coder: decoder)
commonInit()
}
public override init(frame: CGRect, styleURL: URL?) {
altitude = defaultAltitude
super.init(frame: frame, styleURL: styleURL)
commonInit()
}
fileprivate func commonInit() {
makeGestureRecognizersRespectCourseTracking()
makeGestureRecognizersUpdateCourseView()
let gestures = gestureRecognizers ?? []
let mapTapGesture = self.mapTapGesture
mapTapGesture.requireFailure(of: gestures)
addGestureRecognizer(mapTapGesture)
installUserCourseView()
}
open override func layoutMarginsDidChange() {
super.layoutMarginsDidChange()
enableFrameByFrameCourseViewTracking(for: 3)
}
//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, camera:self.camera, 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)
}
/**
Updates the map view’s preferred frames per second to the appropriate value for the current route progress.
This method accounts for the proximity to a maneuver and the current power source. It has no effect if `tracksUserCourse` is set to `true`.
*/
open func updatePreferredFrameRate(for routeProgress: RouteProgress) {
guard tracksUserCourse else { return }
let stepProgress = routeProgress.currentLegProgress.currentStepProgress
let expectedTravelTime = stepProgress.step.expectedTravelTime
let durationUntilNextManeuver = stepProgress.durationRemaining
let durationSincePreviousManeuver = expectedTravelTime - durationUntilNextManeuver
if UIDevice.current.isPluggedIn {
preferredFramesPerSecond = FrameIntervalOptions.pluggedInFramesPerSecond
} else if let upcomingStep = routeProgress.currentLegProgress.upcomingStep,
upcomingStep.maneuverDirection == .straightAhead || upcomingStep.maneuverDirection == .slightLeft || upcomingStep.maneuverDirection == .slightRight {
preferredFramesPerSecond = shouldPositionCourseViewFrameByFrame ? FrameIntervalOptions.defaultFramesPerSecond : minimumFramesPerSecond
} else if durationUntilNextManeuver > FrameIntervalOptions.durationUntilNextManeuver &&
durationSincePreviousManeuver > FrameIntervalOptions.durationSincePreviousManeuver {
preferredFramesPerSecond = shouldPositionCourseViewFrameByFrame ? FrameIntervalOptions.defaultFramesPerSecond : minimumFramesPerSecond
} else {
preferredFramesPerSecond = FrameIntervalOptions.pluggedInFramesPerSecond
}
}
/**
Track position on a frame by frame basis. Used for first location update and when resuming tracking mode
*/
public func enableFrameByFrameCourseViewTracking(for duration: TimeInterval) {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(disableFrameByFramePositioning), object: nil)
perform(#selector(disableFrameByFramePositioning), with: nil, afterDelay: duration)
shouldPositionCourseViewFrameByFrame = true
}
@objc fileprivate func disableFrameByFramePositioning() {
shouldPositionCourseViewFrameByFrame = false
}
//MARK: - User Tracking
func installUserCourseView() {
if let location = userLocationForCourseTracking {
updateCourseTracking(location: location, animated: false)
}
addSubview(userCourseView)
}
@objc private func disableUserCourseTracking() {
guard tracksUserCourse else { return }
tracksUserCourse = false
}
public func updateCourseTracking(location: CLLocation?, camera: MGLMapCamera? = nil, animated: Bool = false) {
// While animating to overhead mode, don't animate the puck.
let duration: TimeInterval = animated && !isAnimatingToOverheadMode ? 1 : 0
animatesUserLocation = animated
userLocationForCourseTracking = location
guard let location = location, CLLocationCoordinate2DIsValid(location.coordinate) else {
return
}
if tracksUserCourse {
let newCamera = camera ?? MGLMapCamera(lookingAtCenter: location.coordinate, altitude: altitude, pitch: 45, heading: location.course)
let function: CAMediaTimingFunction? = animated ? CAMediaTimingFunction(name: .linear) : nil
setCamera(newCamera, withDuration: duration, animationTimingFunction: function, completionHandler: nil)
} else {
// Animate course view updates in overview mode
UIView.animate(withDuration: duration, delay: 0, options: [.curveLinear], animations: { [weak self] in
guard let point = self?.convert(location.coordinate, toPointTo: self) else { return }
self?.userCourseView.center = point
})
}
userCourseView.update(location: location, pitch: self.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
navigationMapViewDelegate?.navigationMapView(self, didSelect: selected)
return
} else if let routes = self.routes(closeTo: tapPoint) {
guard let selectedRoute = routes.first else { return }
navigationMapViewDelegate?.navigationMapView(self, didSelect: selectedRoute)
}
}
@objc func updateCourseView(_ sender: UIGestureRecognizer) {
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.update(location: location,
pitch: camera.pitch,
direction: direction,
animated: false,
tracksUserCourse: tracksUserCourse)
userCourseView.center = convert(location.coordinate, toPointTo: self)
}
}
// MARK: Feature Addition/Removal
/**
Showcases route array. Adds routes and waypoints to map, and sets camera to point encompassing the route.
*/
public static let defaultPadding: UIEdgeInsets = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20)
public func showcase(_ routes: [Route], animated: Bool = false) {
guard let active = routes.first,
let coords = active.shape?.coordinates,
!coords.isEmpty else { return } //empty array
removeArrow()
removeRoutes()
removeWaypoints()
show(routes)
showWaypoints(on: active)
fit(to: active, facing: 0, animated: animated)
}
func fit(to route: Route, facing direction:CLLocationDirection = 0, animated: Bool = false) {
guard let shape = route.shape, !shape.coordinates.isEmpty else { return }
setUserTrackingMode(.none, animated: false, completionHandler: nil)
let line = MGLPolyline(shape)
// Workaround for https://github.com/mapbox/mapbox-gl-native/issues/15574
// Set content insets .zero, before cameraThatFitsShape + setCamera.
contentInset = .zero
let camera = cameraThatFitsShape(line, direction: direction, edgePadding: safeArea + NavigationMapView.defaultPadding)
setCamera(camera, animated: animated)
}
/**
Adds or updates both the route line and the route line casing
*/
public func show(_ routes: [Route], legIndex: Int = 0) {
guard let style = style else { return }
guard let mainRoute = routes.first else { return }
self.routes = routes
let polylines = navigationMapViewDelegate?.navigationMapView(self, shapeFor: routes) ?? shape(for: routes, legIndex: legIndex)
let mainPolylineSimplified = navigationMapViewDelegate?.navigationMapView(self, simplifiedShapeFor: mainRoute) ?? shape(forCasingOf: mainRoute, legIndex: legIndex)
if let source = style.source(withIdentifier: SourceIdentifier.route) as? MGLShapeSource,
let sourceSimplified = style.source(withIdentifier: SourceIdentifier.routeCasing) as? MGLShapeSource {
source.shape = polylines
sourceSimplified.shape = mainPolylineSimplified
} else {
let lineSource = MGLShapeSource(identifier: SourceIdentifier.route, shape: polylines, options: [.lineDistanceMetrics: true])
let lineCasingSource = MGLShapeSource(identifier: SourceIdentifier.routeCasing, shape: mainPolylineSimplified, options: [.lineDistanceMetrics: true])
style.addSource(lineSource)
style.addSource(lineCasingSource)
let line = navigationMapViewDelegate?.navigationMapView(self, routeStyleLayerWithIdentifier: StyleLayerIdentifier.route, source: lineSource) ?? routeStyleLayer(identifier: StyleLayerIdentifier.route, source: lineSource)
let lineCasing = navigationMapViewDelegate?.navigationMapView(self, routeCasingStyleLayerWithIdentifier: StyleLayerIdentifier.routeCasing, source: lineCasingSource) ?? routeCasingStyleLayer(identifier: StyleLayerIdentifier.routeCasing, source: lineSource)
for layer in style.layers.reversed() {
if !(layer is MGLSymbolStyleLayer) &&
layer.identifier != StyleLayerIdentifier.arrow && layer.identifier != StyleLayerIdentifier.arrowSymbol && layer.identifier != StyleLayerIdentifier.arrowCasingSymbol && layer.identifier != StyleLayerIdentifier.arrowStroke && layer.identifier != StyleLayerIdentifier.waypointCircle {
style.insertLayer(line, below: layer)
style.insertLayer(lineCasing, below: line)
break
}
}
}
}
/**
Removes route line and route line casing from map
*/
public func removeRoutes() {
guard let style = style else {
return
}
style.remove([
StyleLayerIdentifier.route,
StyleLayerIdentifier.routeCasing,
].compactMap { style.layer(withIdentifier: $0) })
style.remove(Set([
SourceIdentifier.route,
SourceIdentifier.routeCasing,
].compactMap { style.source(withIdentifier: $0) }))
}
/**
Adds the route waypoints to the map given the current leg index. Previous waypoints for completed legs will be omitted.
*/
public func showWaypoints(on route: Route, legIndex: Int = 0) {
guard let style = style else {
return
}
let waypoints: [Waypoint] = Array(route.legs.dropLast().compactMap { $0.destination })
let source = navigationMapViewDelegate?.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: SourceIdentifier.waypoint) as? MGLShapeSource {
waypointSource.shape = source
} else {
let sourceShape = MGLShapeSource(identifier: SourceIdentifier.waypoint, shape: source, options: sourceOptions)
style.addSource(sourceShape)
let circles = navigationMapViewDelegate?.navigationMapView(self, waypointStyleLayerWithIdentifier: StyleLayerIdentifier.waypointCircle, source: sourceShape) ?? routeWaypointCircleStyleLayer(identifier: StyleLayerIdentifier.waypointCircle, source: sourceShape)
let symbols = navigationMapViewDelegate?.navigationMapView(self, waypointSymbolStyleLayerWithIdentifier: StyleLayerIdentifier.waypointSymbol, source: sourceShape) ?? routeWaypointSymbolStyleLayer(identifier: StyleLayerIdentifier.waypointSymbol, source: sourceShape)
if let arrowLayer = style.layer(withIdentifier: StyleLayerIdentifier.arrowCasingSymbol) {
style.insertLayer(circles, above: arrowLayer)
} else {
style.addLayer(circles)
}
style.insertLayer(symbols, above: circles)
}
}
if let lastLeg = route.legs.last, let destinationCoordinate = lastLeg.destination?.coordinate {
removeAnnotations(annotationsToRemove() ?? [])
let destination = NavigationAnnotation()
destination.coordinate = destinationCoordinate
addAnnotation(destination)
}
}
func annotationsToRemove() -> [MGLAnnotation]? {
return annotations?.filter { $0 is NavigationAnnotation }
}
/**
Removes all waypoints from the map.
*/
public func removeWaypoints() {
guard let style = style else { return }
removeAnnotations(annotationsToRemove() ?? [])
style.remove([
StyleLayerIdentifier.waypointCircle,
StyleLayerIdentifier.waypointSymbol,
].compactMap { style.layer(withIdentifier: $0) })
style.remove(Set([
SourceIdentifier.waypoint,
SourceIdentifier.waypointCircle,
SourceIdentifier.waypointSymbol,
].compactMap { style.source(withIdentifier: $0) }))
}
/**
Shows the step arrow given the current `RouteProgress`.
*/
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 style = style else {
return
}
guard let triangleImage = Bundle.mapboxNavigation.image(named: "triangle")?.withRenderingMode(.alwaysTemplate) 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 shaftPolyline = route.polylineAroundManeuver(legIndex: legIndex, stepIndex: stepIndex, distance: shaftLength)
if shaftPolyline.coordinates.count > 1 {
var shaftStrokeCoordinates = shaftPolyline.coordinates
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: shaftPolyline.coordinates, count: UInt(shaftPolyline.coordinates.count))
let arrowShape = MGLShapeCollection(shapes: [shaftPolyline])
let arrowStrokeShape = MGLShapeCollection(shapes: maneuverArrowStrokePolylines)
let arrowSourceStroke = MGLShapeSource(identifier: SourceIdentifier.arrowStroke, shape: arrowStrokeShape, options: sourceOptions)
let arrowStroke = MGLLineStyleLayer(identifier: StyleLayerIdentifier.arrowStroke, source: arrowSourceStroke)
let arrowSource = MGLShapeSource(identifier: SourceIdentifier.arrow, shape: arrowShape, options: sourceOptions)
let arrow = MGLLineStyleLayer(identifier: StyleLayerIdentifier.arrow, source: arrowSource)
if let source = style.source(withIdentifier: SourceIdentifier.arrow) 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)
if let waypoints = style.layer(withIdentifier: StyleLayerIdentifier.waypointCircle) {
style.insertLayer(arrow, below: waypoints)
} else {
style.addLayer(arrow)
}
}
if let source = style.source(withIdentifier: SourceIdentifier.arrowStroke) 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: SourceIdentifier.arrowSymbol, features: [point], options: sourceOptions)
if let source = style.source(withIdentifier: SourceIdentifier.arrowSymbol) as? MGLShapeSource {
source.shape = arrowSymbolSource.shape
if let arrowSymbolLayer = style.layer(withIdentifier: StyleLayerIdentifier.arrowSymbol) as? MGLSymbolStyleLayer {
arrowSymbolLayer.iconRotation = NSExpression(forConstantValue: shaftDirection as NSNumber)
}
if let arrowSymbolLayerCasing = style.layer(withIdentifier: StyleLayerIdentifier.arrowCasingSymbol) as? MGLSymbolStyleLayer {
arrowSymbolLayerCasing.iconRotation = NSExpression(forConstantValue: shaftDirection as NSNumber)
}
} else {
let arrowSymbolLayer = MGLSymbolStyleLayer(identifier: StyleLayerIdentifier.arrowSymbol, 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: StyleLayerIdentifier.arrowCasingSymbol, 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.
*/
public func removeArrow() {
guard let style = style else {
return
}
style.remove([
StyleLayerIdentifier.arrow,
StyleLayerIdentifier.arrowStroke,
StyleLayerIdentifier.arrowSymbol,
StyleLayerIdentifier.arrowCasingSymbol,
].compactMap { style.layer(withIdentifier: $0) })
style.remove(Set([
SourceIdentifier.arrow,
SourceIdentifier.arrowStroke,
SourceIdentifier.arrowSymbol,
].compactMap { style.source(withIdentifier: $0) }))
}
// 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.shape?.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 = left.shape!
let rightLine = right.shape!
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 = $0.shape!.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(route.shape!)
polyline.attributes["isAlternateRoute"] = true
altRoutes.append(polyline)
}
return MGLShapeCollectionFeature(shapes: altRoutes + congestedRoute)
}
func addCongestion(to route: Route, legIndex: Int?) -> [MGLPolylineFeature]? {
guard let coordinates = route.shape?.coordinates else { return nil }
var linesPerLeg: [MGLPolylineFeature] = []
for (index, leg) in route.legs.enumerated() {
let lines: [MGLPolylineFeature]
// If there is no congestion, don't try and add it
if let legCongestion = leg.segmentCongestionLevels, legCongestion.count < coordinates.count {
// The last coord of the preceding step, is shared with the first coord of the next step, we don't need both.
let legCoordinates: [CLLocationCoordinate2D] = leg.steps.enumerated().reduce([]) { allCoordinates, current in
let index = current.offset
let step = current.element
let stepCoordinates = step.shape!.coordinates
return index == 0 ? stepCoordinates : allCoordinates + stepCoordinates.suffix(from: 1)
}
let mergedCongestionSegments = combine(legCoordinates, with: legCongestion)
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)
return polyline
}
} else {
lines = [MGLPolylineFeature(route.shape!)]
}
for line in lines {
line.attributes["isAlternateRoute"] = false
if let legIndex = legIndex {
line.attributes[MBCurrentLegAttribute] = index == legIndex
} else {
line.attributes[MBCurrentLegAttribute] = index == 0
}
}
linesPerLeg.append(contentsOf: lines)
}
return linesPerLeg
}
func combine(_ coordinates: [CLLocationCoordinate2D], with congestions: [CongestionLevel]) -> [CongestionSegment] {
var segments: [CongestionSegment] = []
segments.reserveCapacity(congestions.count)
for (index, congestion) in congestions.enumerated() {
let congestionSegment: ([CLLocationCoordinate2D], CongestionLevel) = ([coordinates[index], coordinates[index + 1]], congestion)
let coordinates = congestionSegment.0
let congestionLevel = congestionSegment.1
if segments.last?.1 == congestionLevel {
segments[segments.count - 1].0 += coordinates
} else {
segments.append(congestionSegment)
}
}
return segments
}
func shape(forCasingOf route: Route, legIndex: Int?) -> MGLShape? {
var linesPerLeg: [MGLPolylineFeature] = []
for (index, leg) in route.legs.enumerated() {
let polyline = MGLPolylineFeature(leg.shape)
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: identifier, 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://docs.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`.
*/
public func localizeLabels() {
guard MGLAccountManager.hasChinaBaseURL == false else{
return
}
guard let style = style else {
return
}
let streetsSourceIdentifiers: [String] = 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 isLabelLayer = MGLVectorTileSource.roadLabelLayerIdentifiersByTileSetIdentifier.values.contains(layer.sourceLayerIdentifier ?? "")
let locale = isLabelLayer ? Locale(identifier: "mul") : nil
let localizedText = text.mgl_expressionLocalized(into: locale)
if localizedText != text {
layer.text = localizedText
}
}
}
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].shape!.coordinates.reversed()).coordinateFromStart(distance: instruction.distanceAlongStep)!
feature.attributes = [ "instruction": instruction.text ]
features.append(feature)
}
}