-
Notifications
You must be signed in to change notification settings - Fork 313
/
RouteProgress.swift
463 lines (386 loc) · 16.1 KB
/
RouteProgress.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
import Foundation
import MapboxDirections
import Turf
/**
`RouteProgress` stores the user’s progress along a route.
*/
@objc(MBRouteProgress)
open class RouteProgress: NSObject {
/**
Returns the current `Route`.
*/
@objc public let route: Route
/**
Index representing current `RouteLeg`.
*/
@objc public var legIndex: Int {
didSet {
assert(legIndex >= 0 && legIndex < route.legs.endIndex)
// TODO: Set stepIndex to 0 or last index based on whether leg index was incremented or decremented.
currentLegProgress = RouteLegProgress(leg: currentLeg)
}
}
/**
If waypoints are provided in the `Route`, this will contain which leg the user is on.
*/
@objc public var currentLeg: RouteLeg {
return route.legs[legIndex]
}
/**
Returns true if `currentLeg` is the last leg.
*/
public var isFinalLeg: Bool {
guard let lastLeg = route.legs.last else { return false }
return currentLeg == lastLeg
}
/**
Total distance traveled by user along all legs.
*/
@objc public var distanceTraveled: CLLocationDistance {
return route.legs.prefix(upTo: legIndex).map { $0.distance }.reduce(0, +) + currentLegProgress.distanceTraveled
}
/**
Total seconds remaining on all legs.
*/
@objc public var durationRemaining: TimeInterval {
return route.legs.suffix(from: legIndex + 1).map { $0.expectedTravelTime }.reduce(0, +) + currentLegProgress.durationRemaining
}
/**
Number between 0 and 1 representing how far along the `Route` the user has traveled.
*/
@objc public var fractionTraveled: Double {
return distanceTraveled / route.distance
}
/**
Total distance remaining in meters along route.
*/
@objc public var distanceRemaining: CLLocationDistance {
return route.distance - distanceTraveled
}
/**
Number of waypoints remaining on the current route.
*/
@objc public var remainingWaypoints: [Waypoint] {
return route.legs.suffix(from: legIndex).map { $0.destination }
}
/**
Returns the progress along the current `RouteLeg`.
*/
@objc public var currentLegProgress: RouteLegProgress
/**
Tuple containing a `CongestionLevel` and a corresponding `TimeInterval` representing the expected travel time for this segment.
*/
public typealias TimedCongestionLevel = (CongestionLevel, TimeInterval)
/**
If the route contains both `segmentCongestionLevels` and `expectedSegmentTravelTimes`, this property is set to a deeply nested array of `TimeCongestionLevels` per segment per step per leg.
*/
public var congestionTravelTimesSegmentsByStep: [[[TimedCongestionLevel]]] = []
/**
An dictionary containing a `TimeInterval` total per `CongestionLevel`. Only `CongestionLevel` founnd on that step will present. Broken up by leg and then step.
*/
public var congestionTimesPerStep: [[[CongestionLevel: TimeInterval]]] = [[[:]]]
/**
Intializes a new `RouteProgress`.
- parameter route: The route to follow.
- parameter legIndex: Zero-based index indicating the current leg the user is on.
*/
@objc public init(route: Route, legIndex: Int = 0, spokenInstructionIndex: Int = 0) {
self.route = route
self.legIndex = legIndex
self.currentLegProgress = RouteLegProgress(leg: route.legs[legIndex], stepIndex: 0, spokenInstructionIndex: spokenInstructionIndex)
super.init()
for (legIndex, leg) in route.legs.enumerated() {
var maneuverCoordinateIndex = 0
congestionTimesPerStep.append([])
/// An index into the route’s coordinates and congestionTravelTimesSegmentsByStep that corresponds to a step’s maneuver location.
var congestionTravelTimesSegmentsByLeg: [[TimedCongestionLevel]] = []
if let segmentCongestionLevels = leg.segmentCongestionLevels, let expectedSegmentTravelTimes = leg.expectedSegmentTravelTimes {
for step in leg.steps {
guard let coordinates = step.coordinates else { continue }
let stepCoordinateCount = step.maneuverType == .arrive ? Int(step.coordinateCount) : coordinates.dropLast().count
let nextManeuverCoordinateIndex = maneuverCoordinateIndex + stepCoordinateCount - 1
guard nextManeuverCoordinateIndex < segmentCongestionLevels.count else { continue }
guard nextManeuverCoordinateIndex < expectedSegmentTravelTimes.count else { continue }
let stepSegmentCongestionLevels = Array(segmentCongestionLevels[maneuverCoordinateIndex..<nextManeuverCoordinateIndex])
let stepSegmentTravelTimes = Array(expectedSegmentTravelTimes[maneuverCoordinateIndex..<nextManeuverCoordinateIndex])
maneuverCoordinateIndex = nextManeuverCoordinateIndex
let stepTimedCongestionLevels = Array(zip(stepSegmentCongestionLevels, stepSegmentTravelTimes))
congestionTravelTimesSegmentsByLeg.append(stepTimedCongestionLevels)
var stepCongestionValues: [CongestionLevel: TimeInterval] = [:]
for (segmentCongestion, segmentTime) in stepTimedCongestionLevels {
stepCongestionValues[segmentCongestion] = (stepCongestionValues[segmentCongestion] ?? 0) + segmentTime
}
congestionTimesPerStep[legIndex].append(stepCongestionValues)
}
}
congestionTravelTimesSegmentsByStep.append(congestionTravelTimesSegmentsByLeg)
}
}
}
/**
`RouteLegProgress` stores the user’s progress along a route leg.
*/
@objc(MBRouteLegProgress)
open class RouteLegProgress: NSObject {
/**
Returns the current `RouteLeg`.
*/
@objc public let leg: RouteLeg
/**
Index representing the current step.
*/
@objc public var stepIndex: Int {
didSet {
assert(stepIndex >= 0 && stepIndex < leg.steps.endIndex)
currentStepProgress = RouteStepProgress(step: currentStep)
}
}
/**
The remaining steps for user to complete.
*/
@objc public var remainingSteps: [RouteStep] {
return Array(leg.steps.suffix(from: stepIndex + 1))
}
/**
Total distance traveled in meters along current leg.
*/
@objc public var distanceTraveled: CLLocationDistance {
return leg.steps.prefix(upTo: stepIndex).map { $0.distance }.reduce(0, +) + currentStepProgress.distanceTraveled
}
/**
Duration remaining in seconds on current leg.
*/
@objc public var durationRemaining: TimeInterval {
return remainingSteps.map { $0.expectedTravelTime }.reduce(0, +) + currentStepProgress.durationRemaining
}
/**
Number between 0 and 1 representing how far along the current leg the user has traveled.
*/
@objc public var fractionTraveled: Double {
return distanceTraveled / leg.distance
}
@objc public var userHasArrivedAtWaypoint = false
/**
Returns the `RouteStep` before a given step. Returns `nil` if there is no step prior.
*/
@objc public func stepBefore(_ step: RouteStep) -> RouteStep? {
guard let index = leg.steps.index(of: step) else {
return nil
}
if index > 0 {
return leg.steps[index-1]
}
return nil
}
/**
Returns the `RouteStep` after a given step. Returns `nil` if there is not a step after.
*/
@objc public func stepAfter(_ step: RouteStep) -> RouteStep? {
guard let index = leg.steps.index(of: step) else {
return nil
}
if index+1 < leg.steps.endIndex {
return leg.steps[index+1]
}
return nil
}
/**
Returns the `RouteStep` before the current step.
If there is no `priorStep`, nil is returned.
*/
@objc public var priorStep: RouteStep? {
guard stepIndex - 1 >= 0 else {
return nil
}
return leg.steps[stepIndex - 1]
}
/**
Returns the current `RouteStep` for the leg the user is on.
*/
@objc public var currentStep: RouteStep {
return leg.steps[stepIndex]
}
/**
Returns the upcoming `RouteStep`.
If there is no `upcomingStep`, nil is returned.
*/
@objc public var upComingStep: RouteStep? {
guard stepIndex + 1 < leg.steps.endIndex else {
return nil
}
return leg.steps[stepIndex + 1]
}
/**
Returns step 2 steps ahead.
If there is no `followOnStep`, nil is returned.
*/
@objc public var followOnStep: RouteStep? {
guard stepIndex + 2 < leg.steps.endIndex else {
return nil
}
return leg.steps[stepIndex + 2]
}
/**
Return bool whether step provided is the current `RouteStep` the user is on.
*/
@objc public func isCurrentStep(_ step: RouteStep) -> Bool {
return step == currentStep
}
/**
Returns the progress along the current `RouteStep`.
*/
@objc public var currentStepProgress: RouteStepProgress
/**
Intializes a new `RouteLegProgress`.
- parameter leg: Leg on a `Route`.
- parameter stepIndex: Current step the user is on.
*/
@objc public init(leg: RouteLeg, stepIndex: Int = 0, spokenInstructionIndex: Int = 0) {
self.leg = leg
self.stepIndex = stepIndex
currentStepProgress = RouteStepProgress(step: leg.steps[stepIndex], spokenInstructionIndex: spokenInstructionIndex)
}
/**
Returns an array of `CLLocationCoordinate2D` of the prior, current and upcoming step geometry.
*/
@objc public var nearbyCoordinates: [CLLocationCoordinate2D] {
let priorCoords = priorStep?.coordinates ?? []
let upcomingCoords = upComingStep?.coordinates ?? []
let currentCoords = currentStep.coordinates ?? []
let nearby = priorCoords + currentCoords + upcomingCoords
assert(!nearby.isEmpty, "Step must have coordinates")
return nearby
}
typealias StepIndexDistance = (index: Int, distance: CLLocationDistance)
func closestStep(to coordinate: CLLocationCoordinate2D) -> StepIndexDistance? {
var currentClosest: StepIndexDistance?
let remainingSteps = leg.steps.suffix(from: stepIndex)
for (currentStepIndex, step) in remainingSteps.enumerated() {
guard let coords = step.coordinates else { continue }
guard let closestCoordOnStep = Polyline(coords).closestCoordinate(to: coordinate) else { continue }
let foundIndex = currentStepIndex + stepIndex
// First time around, currentClosest will be `nil`.
guard let currentClosestDistance = currentClosest?.distance else {
currentClosest = (index: foundIndex, distance: closestCoordOnStep.distance)
continue
}
if closestCoordOnStep.distance < currentClosestDistance {
currentClosest = (index: foundIndex, distance: closestCoordOnStep.distance)
}
}
return currentClosest
}
}
/**
`RouteStepProgress` stores the user’s progress along a route step.
*/
@objc(MBRouteStepProgress)
open class RouteStepProgress: NSObject {
/**
Returns the current `RouteStep`.
*/
@objc public let step: RouteStep
/**
Returns distance user has traveled along current step.
*/
@objc public var distanceTraveled: CLLocationDistance = 0
/**
Returns distance from user to end of step.
*/
@objc public var userDistanceToManeuverLocation: CLLocationDistance = Double.infinity
/**
Total distance in meters remaining on current step.
*/
@objc public var distanceRemaining: CLLocationDistance {
return step.distance - distanceTraveled
}
/**
Number between 0 and 1 representing fraction of current step traveled.
*/
@objc public var fractionTraveled: Double {
guard step.distance > 0 else { return 1 }
return distanceTraveled / step.distance
}
/**
Number of seconds remaining on current step.
*/
@objc public var durationRemaining: TimeInterval {
return (1 - fractionTraveled) * step.expectedTravelTime
}
/**
Intializes a new `RouteStepProgress`.
- parameter step: Step on a `RouteLeg`.
*/
@objc public init(step: RouteStep, spokenInstructionIndex: Int = 0) {
self.step = step
self.intersectionIndex = 0
self.spokenInstructionIndex = spokenInstructionIndex
}
/**
All intersections on the current `RouteStep` and also the first intersection on the upcoming `RouteStep`.
The upcoming `RouteStep` first `Intersection` is added because it is omitted from the current step.
*/
@objc public var intersectionsIncludingUpcomingManeuverIntersection: [Intersection]?
/**
The next intersection the user will travel through.
The step must contain `intersectionsIncludingUpcomingManeuverIntersection` otherwise this property will be `nil`.
*/
@objc public var upcomingIntersection: Intersection? {
guard let intersections = intersectionsIncludingUpcomingManeuverIntersection, intersections.startIndex..<intersections.endIndex-1 ~= intersectionIndex else {
return nil
}
return intersections[intersections.index(after: intersectionIndex)]
}
/**
Index representing the current intersection.
*/
@objc public var intersectionIndex: Int = 0
/**
The current intersection the user will travel through.
The step must contain `intersectionsIncludingUpcomingManeuverIntersection` otherwise this property will be `nil`.
*/
@objc public var currentIntersection: Intersection? {
guard let intersections = intersectionsIncludingUpcomingManeuverIntersection, intersections.startIndex..<intersections.endIndex ~= intersectionIndex else {
return nil
}
return intersections[intersectionIndex]
}
/**
Returns an array of the calculated distances from the current intersection to the next intersection on the current step.
*/
@objc public var intersectionDistances: Array<CLLocationDistance>?
/**
The distance in meters the user is to the next intersection they will pass through.
*/
public var userDistanceToUpcomingIntersection: CLLocationDistance?
/**
Index into `step.instructionsDisplayedAlongStep` representing the current visual instruction for the step.
*/
@objc public var visualInstructionIndex: Int = 0
/**
An `Array` of remaining `VisualInstruction` for a step.
*/
@objc public var remainingVisualInstructions: [VisualInstructionBanner]? {
guard let visualInstructions = step.instructionsDisplayedAlongStep else { return nil }
return Array(visualInstructions.suffix(from: visualInstructionIndex))
}
/**
Index into `step.instructionsSpokenAlongStep` representing the current spoken instruction.
*/
@objc public var spokenInstructionIndex: Int = 0
/**
An `Array` of remaining `SpokenInstruction` for a step.
*/
@objc public var remainingSpokenInstructions: [SpokenInstruction]? {
guard let instructions = step.instructionsSpokenAlongStep else { return nil }
return Array(instructions.suffix(from: spokenInstructionIndex))
}
/**
Current Instruction for the user's progress along a step.
*/
@objc public var currentSpokenInstruction: SpokenInstruction? {
guard let instructionsSpokenAlongStep = step.instructionsSpokenAlongStep else { return nil }
guard spokenInstructionIndex < instructionsSpokenAlongStep.count else { return nil }
return instructionsSpokenAlongStep[spokenInstructionIndex]
}
}