mobility-toolbox-js 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (271) hide show
  1. package/api/RealtimeAPI.d.ts +279 -0
  2. package/api/RealtimeAPI.d.ts.map +1 -0
  3. package/api/RealtimeAPI.js +466 -0
  4. package/api/RoutingAPI.d.ts +37 -0
  5. package/api/RoutingAPI.d.ts.map +1 -0
  6. package/api/RoutingAPI.js +35 -0
  7. package/api/StopsAPI.d.ts +38 -0
  8. package/api/StopsAPI.d.ts.map +1 -0
  9. package/api/StopsAPI.js +36 -0
  10. package/api/index.d.ts +4 -0
  11. package/api/index.d.ts.map +1 -0
  12. package/api/index.js +3 -3
  13. package/api/typedefs.d.ts +179 -0
  14. package/api/typedefs.d.ts.map +1 -0
  15. package/api/{tralis/typedefs.js → typedefs.js} +4 -10
  16. package/common/api/HttpAPI.d.ts +31 -0
  17. package/common/api/HttpAPI.d.ts.map +1 -0
  18. package/common/api/HttpAPI.js +57 -0
  19. package/common/api/WebSocketAPI.d.ts +153 -0
  20. package/common/api/WebSocketAPI.d.ts.map +1 -0
  21. package/common/api/WebSocketAPI.js +341 -0
  22. package/common/controls/ControlCommon.d.ts +76 -0
  23. package/common/controls/ControlCommon.d.ts.map +1 -0
  24. package/common/controls/ControlCommon.js +150 -0
  25. package/common/controls/CopyrightControlCommon.d.ts +13 -0
  26. package/common/controls/CopyrightControlCommon.d.ts.map +1 -0
  27. package/common/controls/CopyrightControlCommon.js +34 -0
  28. package/common/controls/StopFinderControlCommon.d.ts +55 -0
  29. package/common/controls/StopFinderControlCommon.d.ts.map +1 -0
  30. package/common/controls/StopFinderControlCommon.js +144 -0
  31. package/common/index.d.ts +3 -0
  32. package/common/index.d.ts.map +1 -0
  33. package/common/index.js +2 -0
  34. package/common/layers/LayerCommon.d.ts +94 -0
  35. package/common/layers/LayerCommon.d.ts.map +1 -0
  36. package/common/layers/LayerCommon.js +244 -0
  37. package/common/mixins/RealtimeLayerMixin.d.ts +286 -0
  38. package/common/mixins/RealtimeLayerMixin.d.ts.map +1 -0
  39. package/common/mixins/RealtimeLayerMixin.js +776 -0
  40. package/common/mixins/UserInteractionsLayerMixin.d.ts +60 -0
  41. package/common/mixins/UserInteractionsLayerMixin.d.ts.map +1 -0
  42. package/common/mixins/UserInteractionsLayerMixin.js +241 -0
  43. package/common/styles/index.d.ts +5 -0
  44. package/common/styles/index.d.ts.map +1 -0
  45. package/common/styles/index.js +4 -4
  46. package/common/styles/realtimeDefaultStyle.d.ts +36 -0
  47. package/common/styles/realtimeDefaultStyle.d.ts.map +1 -0
  48. package/common/styles/realtimeDefaultStyle.js +275 -0
  49. package/common/styles/{trackerDelayStyle.js → realtimeDelayStyle.d.ts} +4 -9
  50. package/common/styles/realtimeDelayStyle.d.ts.map +1 -0
  51. package/common/styles/realtimeDelayStyle.js +13 -0
  52. package/common/styles/realtimeHeadingStyle.d.ts +12 -0
  53. package/common/styles/realtimeHeadingStyle.d.ts.map +1 -0
  54. package/common/styles/realtimeHeadingStyle.js +85 -0
  55. package/common/styles/realtimeSimpleStyle.d.ts +4 -0
  56. package/common/styles/realtimeSimpleStyle.d.ts.map +1 -0
  57. package/common/styles/realtimeSimpleStyle.js +23 -0
  58. package/common/typedefs.d.ts +111 -0
  59. package/common/typedefs.d.ts.map +1 -0
  60. package/common/typedefs.js +35 -6
  61. package/common/utils/compareDepartures.d.ts +11 -0
  62. package/common/utils/compareDepartures.d.ts.map +1 -0
  63. package/common/utils/compareDepartures.js +35 -0
  64. package/common/utils/createCanvas.d.ts +10 -0
  65. package/common/utils/createCanvas.d.ts.map +1 -0
  66. package/common/utils/createCanvas.js +27 -0
  67. package/common/utils/createRealtimeFilters.d.ts +13 -0
  68. package/common/utils/createRealtimeFilters.d.ts.map +1 -0
  69. package/common/utils/createRealtimeFilters.js +74 -0
  70. package/common/utils/debounceDeparturesMessages.d.ts +12 -0
  71. package/common/utils/debounceDeparturesMessages.d.ts.map +1 -0
  72. package/common/utils/debounceDeparturesMessages.js +24 -0
  73. package/common/utils/debounceWebsocketMessages.d.ts +11 -0
  74. package/common/utils/debounceWebsocketMessages.d.ts.map +1 -0
  75. package/common/utils/debounceWebsocketMessages.js +29 -0
  76. package/common/utils/getLayersAsFlatArray.d.ts +3 -0
  77. package/common/utils/getLayersAsFlatArray.d.ts.map +1 -0
  78. package/common/utils/getLayersAsFlatArray.js +15 -0
  79. package/common/utils/getMapboxMapCopyrights.d.ts +18 -0
  80. package/common/utils/getMapboxMapCopyrights.d.ts.map +1 -0
  81. package/common/utils/getMapboxMapCopyrights.js +21 -23
  82. package/common/utils/getMapboxRender.d.ts +7 -0
  83. package/common/utils/getMapboxRender.d.ts.map +1 -0
  84. package/common/utils/getMapboxRender.js +87 -0
  85. package/common/utils/getMaplibreRender.d.ts +7 -0
  86. package/common/utils/getMaplibreRender.d.ts.map +1 -0
  87. package/common/utils/getMaplibreRender.js +38 -0
  88. package/common/utils/getRealtimeModeSuffix.d.ts +10 -0
  89. package/common/utils/getRealtimeModeSuffix.d.ts.map +1 -0
  90. package/common/utils/getRealtimeModeSuffix.js +7 -0
  91. package/common/utils/getUrlWithParams.d.ts +9 -0
  92. package/common/utils/getUrlWithParams.d.ts.map +1 -0
  93. package/common/utils/getUrlWithParams.js +18 -0
  94. package/common/utils/getVehiclePosition.d.ts +16 -0
  95. package/common/utils/getVehiclePosition.d.ts.map +1 -0
  96. package/common/utils/getVehiclePosition.js +60 -60
  97. package/common/utils/index.d.ts +17 -0
  98. package/common/utils/index.d.ts.map +1 -0
  99. package/common/utils/index.js +13 -2
  100. package/common/utils/realtimeConfig.d.ts +49 -0
  101. package/common/utils/realtimeConfig.d.ts.map +1 -0
  102. package/common/utils/realtimeConfig.js +173 -0
  103. package/common/utils/removeDuplicate.d.ts +10 -0
  104. package/common/utils/removeDuplicate.d.ts.map +1 -0
  105. package/common/utils/removeDuplicate.js +5 -12
  106. package/common/utils/renderTrajectories.d.ts +17 -0
  107. package/common/utils/renderTrajectories.d.ts.map +1 -0
  108. package/common/utils/renderTrajectories.js +110 -0
  109. package/common/utils/sortAndFilterDepartures.d.ts +16 -0
  110. package/common/utils/sortAndFilterDepartures.d.ts.map +1 -0
  111. package/common/utils/sortAndFilterDepartures.js +58 -0
  112. package/common/utils/sortByDelay.d.ts +3 -0
  113. package/common/utils/sortByDelay.d.ts.map +1 -0
  114. package/common/utils/sortByDelay.js +17 -20
  115. package/common/utils/timeUtils.d.ts +24 -0
  116. package/common/utils/timeUtils.d.ts.map +1 -0
  117. package/common/utils/timeUtils.js +13 -18
  118. package/iife.d.ts +3 -0
  119. package/iife.d.ts.map +1 -0
  120. package/iife.js +5 -0
  121. package/index.d.ts +10 -0
  122. package/index.d.ts.map +1 -0
  123. package/index.js +10 -2
  124. package/mapbox/controls/CopyrightControl.d.ts +29 -0
  125. package/mapbox/controls/CopyrightControl.d.ts.map +1 -0
  126. package/mapbox/controls/CopyrightControl.js +25 -35
  127. package/mapbox/controls/index.d.ts +2 -0
  128. package/mapbox/controls/index.d.ts.map +1 -0
  129. package/mapbox/controls/index.js +2 -0
  130. package/mapbox/index.d.ts +6 -0
  131. package/mapbox/index.d.ts.map +1 -0
  132. package/mapbox/index.js +5 -3
  133. package/mapbox/layers/Layer.d.ts +59 -0
  134. package/mapbox/layers/Layer.d.ts.map +1 -0
  135. package/mapbox/layers/Layer.js +78 -95
  136. package/mapbox/layers/RealtimeLayer.d.ts +181 -0
  137. package/mapbox/layers/RealtimeLayer.d.ts.map +1 -0
  138. package/mapbox/layers/RealtimeLayer.js +276 -0
  139. package/mapbox/layers/index.d.ts +3 -0
  140. package/mapbox/layers/index.d.ts.map +1 -0
  141. package/mapbox/layers/index.js +2 -0
  142. package/mapbox/utils/getMercatorResolution.d.ts +9 -0
  143. package/mapbox/utils/getMercatorResolution.d.ts.map +1 -0
  144. package/mapbox/utils/getMercatorResolution.js +18 -0
  145. package/mapbox/utils/getSourceCoordinates.d.ts +9 -0
  146. package/mapbox/utils/getSourceCoordinates.d.ts.map +1 -0
  147. package/mapbox/utils/getSourceCoordinates.js +27 -0
  148. package/mapbox/utils/index.d.ts +3 -0
  149. package/mapbox/utils/index.d.ts.map +1 -0
  150. package/mapbox/utils/index.js +2 -0
  151. package/mbt.js +60005 -0
  152. package/mbt.js.map +7 -0
  153. package/mbt.min.js +1084 -0
  154. package/mbt.min.js.map +7 -0
  155. package/ol/controls/CopyrightControl.d.ts +31 -0
  156. package/ol/controls/CopyrightControl.d.ts.map +1 -0
  157. package/ol/controls/CopyrightControl.js +44 -56
  158. package/ol/controls/RoutingControl.d.ts +193 -0
  159. package/ol/controls/RoutingControl.d.ts.map +1 -0
  160. package/ol/controls/RoutingControl.js +546 -667
  161. package/ol/controls/StopFinderControl.d.ts +30 -0
  162. package/ol/controls/StopFinderControl.d.ts.map +1 -0
  163. package/ol/controls/StopFinderControl.js +10 -16
  164. package/ol/controls/index.d.ts +4 -0
  165. package/ol/controls/index.d.ts.map +1 -0
  166. package/ol/controls/index.js +3 -0
  167. package/ol/index.d.ts +6 -0
  168. package/ol/index.d.ts.map +1 -0
  169. package/ol/index.js +4 -12
  170. package/ol/layers/Layer.d.ts +86 -0
  171. package/ol/layers/Layer.d.ts.map +1 -0
  172. package/ol/layers/Layer.js +147 -166
  173. package/ol/layers/MapGlLayer.d.ts +67 -0
  174. package/ol/layers/MapGlLayer.d.ts.map +1 -0
  175. package/ol/layers/MapGlLayer.js +218 -0
  176. package/ol/layers/MapboxLayer.d.ts +50 -0
  177. package/ol/layers/MapboxLayer.d.ts.map +1 -0
  178. package/ol/layers/MapboxLayer.js +79 -348
  179. package/ol/layers/MapboxStyleLayer.d.ts +129 -0
  180. package/ol/layers/MapboxStyleLayer.d.ts.map +1 -0
  181. package/ol/layers/MapboxStyleLayer.js +329 -368
  182. package/ol/layers/MaplibreLayer.d.ts +28 -0
  183. package/ol/layers/MaplibreLayer.d.ts.map +1 -0
  184. package/ol/layers/MaplibreLayer.js +13 -259
  185. package/ol/layers/RealtimeLayer.d.ts +202 -0
  186. package/ol/layers/RealtimeLayer.d.ts.map +1 -0
  187. package/ol/layers/RealtimeLayer.js +340 -0
  188. package/ol/layers/RoutingLayer.d.ts +34 -0
  189. package/ol/layers/RoutingLayer.d.ts.map +1 -0
  190. package/ol/layers/RoutingLayer.js +62 -68
  191. package/ol/layers/VectorLayer.d.ts +25 -0
  192. package/ol/layers/VectorLayer.d.ts.map +1 -0
  193. package/ol/layers/VectorLayer.js +27 -32
  194. package/ol/layers/WMSLayer.d.ts +42 -0
  195. package/ol/layers/WMSLayer.d.ts.map +1 -0
  196. package/ol/layers/WMSLayer.js +74 -66
  197. package/ol/layers/index.d.ts +9 -0
  198. package/ol/layers/index.d.ts.map +1 -0
  199. package/ol/layers/index.js +8 -0
  200. package/ol/styles/fullTrajectoryDelayStyle.d.ts +4 -0
  201. package/ol/styles/fullTrajectoryDelayStyle.d.ts.map +1 -0
  202. package/ol/styles/fullTrajectoryDelayStyle.js +23 -25
  203. package/ol/styles/fullTrajectoryStyle.d.ts +5 -0
  204. package/ol/styles/fullTrajectoryStyle.d.ts.map +1 -0
  205. package/ol/styles/fullTrajectoryStyle.js +37 -44
  206. package/ol/styles/index.d.ts +3 -0
  207. package/ol/styles/index.d.ts.map +1 -0
  208. package/package.json +98 -177
  209. package/setupTests.d.ts +2 -0
  210. package/setupTests.d.ts.map +1 -0
  211. package/setupTests.js +26 -0
  212. package/types/common.d.ts +122 -0
  213. package/types/index.d.ts +11 -0
  214. package/types/realtime.d.ts +320 -0
  215. package/types/routing.d.ts +206 -0
  216. package/types/stops.d.ts +143 -0
  217. package/README.md +0 -23
  218. package/api/routing/RoutingAPI.js +0 -44
  219. package/api/routing/RoutingAPI.test.js +0 -41
  220. package/api/stops/StopsAPI.js +0 -41
  221. package/api/stops/StopsAPI.test.js +0 -34
  222. package/api/tralis/TralisAPI.js +0 -731
  223. package/api/tralis/TralisAPI.test.js +0 -75
  224. package/api/tralis/TralisAPIUtils.js +0 -73
  225. package/api/tralis/WebSocketConnector.js +0 -338
  226. package/api/tralis/WebSocketConnector.test.js +0 -356
  227. package/common/Tracker.js +0 -197
  228. package/common/api/api.js +0 -64
  229. package/common/api/api.test.js +0 -68
  230. package/common/controls/Control.js +0 -146
  231. package/common/controls/Control.test.js +0 -98
  232. package/common/layers/Layer.js +0 -404
  233. package/common/layers/Layer.test.js +0 -585
  234. package/common/mixins/CopyrightMixin.js +0 -48
  235. package/common/mixins/SearchMixin.js +0 -176
  236. package/common/mixins/TralisLayerMixin.js +0 -930
  237. package/common/styles/trackerDefaultStyle.js +0 -333
  238. package/common/styles/trackerSimpleStyle.js +0 -22
  239. package/common/trackerConfig.js +0 -190
  240. package/common/trackerConfig.test.js +0 -25
  241. package/common/utils/createTrackerFilters.js +0 -87
  242. package/common/utils/createTrackerFilters.test.js +0 -95
  243. package/common/utils/getMapboxMapCopyrights.test.js +0 -47
  244. package/common/utils/getMapboxStyleUrl.js +0 -32
  245. package/common/utils/removeDuplicate.test.js +0 -22
  246. package/common/utils/timeUtils.test.js +0 -16
  247. package/index.js.map +0 -1
  248. package/mapbox/layers/Layer.test.js +0 -202
  249. package/mapbox/layers/TralisLayer.js +0 -329
  250. package/mapbox/layers/TralisLayer.test.js +0 -40
  251. package/mapbox/utils.js +0 -46
  252. package/module.js +0 -23
  253. package/ol/README.md +0 -0
  254. package/ol/controls/CopyrightControl.test.js +0 -211
  255. package/ol/controls/RoutingControl.test.js +0 -216
  256. package/ol/controls/StopFinderControl.test.js +0 -59
  257. package/ol/controls/snapshots/RoutingControlRouteGen10.json +0 -58
  258. package/ol/controls/snapshots/RoutingControlRouteGen100.json +0 -292
  259. package/ol/controls/snapshots/RoutingControlRouteGen30.json +0 -69
  260. package/ol/controls/snapshots/RoutingControlRouteGen5.json +0 -58
  261. package/ol/controls/snapshots/RoutingControlRouteOSM.json +0 -759
  262. package/ol/controls/snapshots/RoutingControlStation1.json +0 -60
  263. package/ol/controls/snapshots/RoutingControlStation2.json +0 -49
  264. package/ol/layers/Layer.test.js +0 -197
  265. package/ol/layers/MapboxLayer.test.js +0 -186
  266. package/ol/layers/MapboxStyleLayer.test.js +0 -262
  267. package/ol/layers/RoutingLayer.test.js +0 -49
  268. package/ol/layers/TralisLayer.js +0 -359
  269. package/ol/layers/TralisLayer.test.js +0 -97
  270. package/ol/layers/VectorLayer.test.js +0 -98
  271. package/ol/layers/WMSLayer.test.js +0 -84
@@ -6,10 +6,10 @@ import { click } from 'ol/events/condition';
6
6
  import { GeoJSON } from 'ol/format';
7
7
  import { buffer } from 'ol/extent';
8
8
  import { fromLonLat, toLonLat } from 'ol/proj';
9
- import RoutingAPI from '../../api/routing/RoutingAPI';
10
- import Control from '../../common/controls/Control';
9
+ import BaseEvent from 'ol/events/Event';
10
+ import { RoutingAPI } from '../../api';
11
+ import ControlCommon from '../../common/controls/ControlCommon';
11
12
  import RoutingLayer from '../layers/RoutingLayer';
12
-
13
13
  // Examples for a single hop:
14
14
  // basel sbb a station named "basel sbb"
15
15
  // ZUE, station "Zürich HB" by its common abbreviation
@@ -17,30 +17,34 @@ import RoutingLayer from '../layers/RoutingLayer';
17
17
  // @47.37811,8.53935 a station at position 47.37811, 8.53935
18
18
  // @47.37811,8.53935$4 track 4 in a station at position 47.37811, 8.53935
19
19
  // zürich hb@47.37811,8.53935$8 track 8 in station "Zürich HB" at position 47.37811, 8.53935
20
- const REGEX_VIA_POINT =
21
- /^([^@$!\n]*)(@?([\d.]+),([\d.]+))?(\$?([a-zA-Z0-9]{0,2}))$/;
22
-
20
+ /** @private */
21
+ const REGEX_VIA_POINT = /^([^@$!\n]*)(@?([\d.]+),([\d.]+))?(\$?([a-zA-Z0-9]{0,2}))$/;
23
22
  // Examples for a single hop:
24
23
  //
25
24
  // 47.37811,8.53935 a position 47.37811, 8.53935
25
+ /** @private */
26
26
  const REGEX_VIA_POINT_COORD = /^([\d.]+),([\d.]+)$/;
27
-
28
27
  // Examples for a single hop:
29
28
  //
30
29
  // !8596126 a station with id 8596126
31
30
  // !8596126$4 a station with id 8596126
31
+ /** @private */
32
32
  const REGEX_VIA_POINT_STATION_ID = /^!([^$]*)(\$?([a-zA-Z0-9]{0,2}))$/;
33
-
33
+ /** @private */
34
34
  const STOP_FETCH_ABORT_CONTROLLER_KEY = 'stop-fetch';
35
-
35
+ /** @private */
36
36
  const getFlatCoordinatesFromSegments = (segmentArray) => {
37
- const coords = [];
38
- segmentArray.forEach((seg) => {
39
- coords.push(...seg.getGeometry().getCoordinates());
40
- });
41
- return coords;
37
+ const coords = [];
38
+ segmentArray.forEach((seg) => {
39
+ var _a;
40
+ // @ts-ignore
41
+ const coordArr = (_a = seg.getGeometry()) === null || _a === void 0 ? void 0 : _a.getCoordinates();
42
+ if (coordArr === null || coordArr === void 0 ? void 0 : coordArr.length) {
43
+ coords.push(...coordArr);
44
+ }
45
+ });
46
+ return coords;
42
47
  };
43
-
44
48
  /**
45
49
  * Display a route of a specified mean of transport.
46
50
  *
@@ -54,7 +58,7 @@ const getFlatCoordinatesFromSegments = (segmentArray) => {
54
58
  *
55
59
  * const control = new RoutingControl();
56
60
  *
57
- * control.map = map
61
+ * control.attachToMap(map)
58
62
  *
59
63
  * @classproperty {string} apiKey - Key used for RoutingApi requests.
60
64
  * @classproperty {string} stopsApiKey - Key used for Stop lookup requests (defaults to apiKey).
@@ -72,681 +76,556 @@ const getFlatCoordinatesFromSegments = (segmentArray) => {
72
76
  * @extends {Control}
73
77
  * @implements {RoutingInterface}
74
78
  */
75
- class RoutingControl extends Control {
76
- constructor(options = {}) {
77
- super(options);
78
-
79
- Object.defineProperties(this, {
80
- mot: {
81
- get: () => this.get('mot'),
82
- set: (newMot) => {
83
- if (newMot) {
84
- this.set('mot', newMot);
85
- if (this.viaPoints) {
86
- this.drawRoute();
87
- }
88
- }
89
- },
90
- },
91
- loading: {
92
- get: () => this.get('loading'),
93
- set: (newLoading) => {
94
- this.set('loading', newLoading);
95
- },
96
- },
97
- modify: {
98
- get: () => this.get('modify'),
99
- set: (modify) => {
100
- this.set('modify', modify);
101
- },
102
- },
103
- });
104
-
105
- /** True if the control is requesting the backend. */
106
- this.loading = false;
107
-
108
- /** @ignore */
109
- this.graphs = options.graphs || [['osm', 0, 99]];
110
-
111
- /** @ignore */
112
- this.mot = options.mot || 'bus';
113
-
114
- /** @ignore */
115
- this.modify = options.modify !== false;
116
-
117
- /** @ignore */
118
- this.routingApiParams = options.routingApiParams || {};
119
-
120
- /** @ignore */
121
- this.useRawViaPoints = options.useRawViaPoints || false;
122
-
123
- /** @ignore */
124
- this.snapToClosestStation = options.snapToClosestStation || false;
125
-
126
- /** @ignore */
127
- this.cacheStationData = {};
128
-
129
- /** @ignore */
130
- this.abortControllers = [];
131
-
132
- /** @ignore */
133
- this.apiKey = options.apiKey;
134
-
135
- /** @ignore */
136
- this.stopsApiKey = options.stopsApiKey || this.apiKey;
137
-
138
- /** @ignore */
139
- this.segments = [];
140
-
141
- /** @ignore */
142
- this.stopsApiUrl = options.stopsApiUrl || 'https://api.geops.io/stops/v1/';
143
-
144
- /** @ignore */
145
- this.api = new RoutingAPI({
146
- url: options.url,
147
- apiKey: this.apiKey,
148
- mot: options.mot,
149
- });
150
-
151
- /** @ignore */
152
- this.routingLayer =
153
- options.routingLayer ||
154
- new RoutingLayer({
155
- name: 'routing-layer',
156
- style: options.style,
157
- });
158
-
159
- /** @ignore */
160
- this.onRouteError =
161
- options.onRouteError ||
162
- ((error) => {
163
- this.dispatchEvent({
164
- type: 'change:route',
165
- target: this,
79
+ class RoutingControl extends ControlCommon {
80
+ constructor(options = {}) {
81
+ super(options);
82
+ this.viaPoints = [];
83
+ this.loading = false;
84
+ this.graphs = [];
85
+ this.modify = true;
86
+ this.useRawViaPoints = false;
87
+ this.snapToClosestStation = false;
88
+ this.cacheStationData = {};
89
+ this.abortControllers = {};
90
+ this.segments = [];
91
+ this.format = new GeoJSON({ featureProjection: 'EPSG:3857' });
92
+ this.initialRouteDrag = {};
93
+ Object.defineProperties(this, {
94
+ mot: {
95
+ get: () => this.get('mot'),
96
+ set: (newMot) => {
97
+ if (newMot) {
98
+ this.set('mot', newMot);
99
+ if (this.viaPoints) {
100
+ this.drawRoute();
101
+ }
102
+ }
103
+ },
104
+ },
105
+ loading: {
106
+ get: () => this.get('loading'),
107
+ set: (newLoading) => {
108
+ this.set('loading', newLoading);
109
+ },
110
+ },
111
+ modify: {
112
+ get: () => this.get('modify'),
113
+ set: (modify) => {
114
+ this.set('modify', modify);
115
+ },
116
+ },
166
117
  });
167
- this.reset();
168
- // eslint-disable-next-line no-console
169
- console.error(error);
170
- });
171
-
172
- /** @ignore */
173
- this.viaPoints = [];
174
-
175
- /** @ignore */
176
- this.onMapClick = this.onMapClick.bind(this);
177
-
178
- /** @ignore */
179
- this.onModifyEnd = this.onModifyEnd.bind(this);
180
-
181
- /** @ignore */
182
- this.onModifyStart = this.onModifyStart.bind(this);
183
-
184
- /** @ignore */
185
- this.apiChangeListener = () => this.drawRoute();
186
-
187
- /** @ignore */
188
- this.createModifyInteraction();
189
- }
190
-
191
- /**
192
- * Calculate at which resolutions corresponds each generalizations.
193
- *
194
- * @private
195
- */
196
- static getGraphsResolutions(graphs, map) {
197
- const view = map.getView();
198
- return graphs.map(([, minZoom, maxZoom]) => [
199
- view.getResolutionForZoom(minZoom),
200
- view.getResolutionForZoom(maxZoom || minZoom + 1),
201
- ]);
202
- }
203
-
204
- /**
205
- * Adds/Replaces a viaPoint to the viaPoints array and redraws route:
206
- * Adds a viaPoint at end of array by default.
207
- * If an index is passed a viaPoint is added at the specified index.
208
- * If an index is passed and overwrite x is > 0, x viaPoints at the specified
209
- * index are replaced with a single new viaPoint.
210
- * @param {Array<number>} coordinates Array of coordinates
211
- * @param {number} index Integer representing the index of the added viaPoint.
212
- * @param {number} [overwrite=0] Marks the number of viaPoints that are removed at the specified index on add.
213
- */
214
- addViaPoint(
215
- coordinatesOrString,
216
- index = this.viaPoints.length,
217
- overwrite = 0,
218
- ) {
219
- /* Add/Insert/Overwrite viapoint and redraw route */
220
- this.viaPoints.splice(index, overwrite, coordinatesOrString);
221
- this.drawRoute();
222
- this.dispatchEvent({
223
- type: 'change:route',
224
- target: this,
225
- });
226
- }
227
-
228
- /**
229
- * Removes a viaPoint at the passed array index and redraws route
230
- * By default the last viaPoint is removed.
231
- * @param {number} index Integer representing the index of the viaPoint to delete.
232
- */
233
- removeViaPoint(index = this.viaPoints.length - 1) {
234
- /* Remove viapoint and redraw route */
235
- if (this.viaPoints.length && this.viaPoints[index]) {
236
- this.viaPoints.splice(index, 1);
118
+ /** True if the control is requesting the backend. */
119
+ this.loading = false;
120
+ /** @ignore */
121
+ this.graphs = options.graphs || [['osm', 0, 99]];
122
+ /** @ignore */
123
+ this.mot = options.mot || 'bus';
124
+ /** @ignore */
125
+ this.modify = options.modify !== false;
126
+ /** @ignore */
127
+ this.routingApiParams = options.routingApiParams;
128
+ /** @ignore */
129
+ this.useRawViaPoints = options.useRawViaPoints || false;
130
+ /** @ignore */
131
+ this.snapToClosestStation = options.snapToClosestStation || false;
132
+ /** @ignore */
133
+ this.apiKey = options.apiKey;
134
+ /** @ignore */
135
+ this.stopsApiKey = options.stopsApiKey || this.apiKey;
136
+ /** @ignore */
137
+ this.stopsApiUrl = options.stopsApiUrl || 'https://api.geops.io/stops/v1/';
138
+ /** @ignore */
139
+ this.api = new RoutingAPI(Object.assign({}, options));
140
+ /** @ignore */
141
+ this.routingLayer =
142
+ options.routingLayer ||
143
+ new RoutingLayer({
144
+ name: 'routing-layer',
145
+ style: options.style,
146
+ });
147
+ /** @ignore */
148
+ this.onRouteError =
149
+ options.onRouteError ||
150
+ ((error) => {
151
+ this.dispatchEvent(new BaseEvent('change:route'));
152
+ this.reset();
153
+ // eslint-disable-next-line no-console
154
+ console.error(error);
155
+ });
156
+ /** @ignore */
157
+ this.onMapClick = this.onMapClick.bind(this);
158
+ /** @ignore */
159
+ this.onModifyEnd = this.onModifyEnd.bind(this);
160
+ /** @ignore */
161
+ this.onModifyStart = this.onModifyStart.bind(this);
162
+ /** @ignore */
163
+ this.createModifyInteraction();
237
164
  }
238
- this.drawRoute();
239
- this.dispatchEvent({
240
- type: 'change:route',
241
- target: this,
242
- });
243
- }
244
-
245
- /**
246
- * Replaces the current viaPoints with a new coordinate array.
247
- * @param {Array<Array<number>>} coordinateArray Array of nested coordinates
248
- */
249
- setViaPoints(coordinateArray) {
250
- this.viaPoints = [...coordinateArray];
251
- this.drawRoute();
252
- this.dispatchEvent({
253
- type: 'change:route',
254
- target: this,
255
- });
256
- }
257
-
258
- /**
259
- * Removes all viaPoints, clears the source and triggers a change event
260
- */
261
- reset() {
262
- // Clear viaPoints and source
263
- this.abortRequests();
264
- this.viaPoints = [];
265
- this.routingLayer.olLayer.getSource().clear();
266
- this.dispatchEvent({
267
- type: 'change:route',
268
- target: this,
269
- });
270
- }
271
-
272
- /**
273
- * Aborts viapoint and route requests
274
- * @private
275
- */
276
- abortRequests() {
277
- // Abort Routing API requests
278
- this.graphs.forEach(([graph]) => {
279
- if (this.abortControllers[graph]) {
280
- this.abortControllers[graph].abort();
281
- }
282
- this.abortControllers[graph] = new AbortController();
283
- });
284
-
285
- // Abort Stops API requests
286
- this.abortControllers[STOP_FETCH_ABORT_CONTROLLER_KEY]?.abort();
287
- this.abortControllers[STOP_FETCH_ABORT_CONTROLLER_KEY] =
288
- new AbortController();
289
-
290
- this.loading = false;
291
- }
292
-
293
- /**
294
- * Draws route on map using an array of coordinates:
295
- * If a single coordinate is passed a single point feature is added to map.
296
- * If two or more coordinates are passed a request to the RoutingAPI fetches
297
- * the route using the passed coordinates and the current mot.
298
- * @private
299
- */
300
- drawRoute() {
301
- /* Calls RoutingAPI to draw a route using the viaPoints array */
302
- this.abortRequests();
303
- this.routingLayer.olLayer.getSource().clear();
304
-
305
- if (!this.viaPoints.length) {
306
- return null;
165
+ /**
166
+ * Calculate at which resolutions corresponds each generalizations.
167
+ *
168
+ * @private
169
+ */
170
+ static getGraphsResolutions(graphs, map) {
171
+ const view = map.getView();
172
+ return graphs.map(([, minZoom, maxZoom]) => [
173
+ view.getResolutionForZoom(minZoom),
174
+ view.getResolutionForZoom(maxZoom || minZoom + 1),
175
+ ]);
307
176
  }
308
-
309
- if (this.viaPoints.length === 1) {
310
- // Add point for first node
311
- return this.drawViaPoint(
312
- this.viaPoints[0],
313
- 0,
314
- this.abortControllers[STOP_FETCH_ABORT_CONTROLLER_KEY],
315
- );
177
+ /**
178
+ * Adds/Replaces a viaPoint to the viaPoints array and redraws route:
179
+ * Adds a viaPoint at end of array by default.
180
+ * If an index is passed a viaPoint is added at the specified index.
181
+ * If an index is passed and overwrite x is > 0, x viaPoints at the specified
182
+ * index are replaced with a single new viaPoint.
183
+ * @param {number[]|string} coordinates Array of coordinates
184
+ * @param {number} [index=-1] Integer representing the index of the added viaPoint. If not specified, the viaPoint is added at the end of the array.
185
+ * @param {number} [overwrite=0] Marks the number of viaPoints that are removed at the specified index on add.
186
+ */
187
+ addViaPoint(coordinatesOrString, index = -1, overwrite = 0) {
188
+ /* Add/Insert/Overwrite viapoint and redraw route */
189
+ this.viaPoints.splice(index === -1 ? this.viaPoints.length : index, overwrite, coordinatesOrString);
190
+ this.drawRoute();
191
+ this.dispatchEvent(new BaseEvent('change:route'));
316
192
  }
317
-
318
- const formattedViaPoints = this.viaPoints.map((viaPoint) => {
319
- if (Array.isArray(viaPoint)) {
320
- const projection = this.map.getView().getProjection();
321
- // viaPoint is a coordinate
322
- // Coordinates need to be reversed as required by the backend RoutingAPI
323
- const [lon, lat] = toLonLat(viaPoint, projection);
324
- return this.snapToClosestStation ? [`@${lat}`, lon] : [lat, lon];
325
- }
326
-
327
- // viaPoint is a string to use as it is
328
- return this.useRawViaPoints ? viaPoint : `!${viaPoint}`;
329
- });
330
-
331
- this.loading = true;
332
-
333
- // Clear source
334
- this.routingLayer.olLayer.getSource().clear();
335
-
336
- // Create point features for the viaPoints
337
- this.viaPoints.forEach((viaPoint, idx) =>
338
- this.drawViaPoint(
339
- viaPoint,
340
- idx,
341
- this.abortControllers[STOP_FETCH_ABORT_CONTROLLER_KEY],
342
- ),
343
- );
344
-
345
- return Promise.all(
346
- this.graphs.map(([graph], index) => {
347
- return this.api
348
- .route(
349
- {
350
- graph,
351
- via: `${formattedViaPoints.join('|')}`,
352
- mot: `${this.mot}`,
353
- 'resolve-hops': false,
354
- elevation: false,
355
- 'coord-radius': 100.0,
356
- 'coord-punish': 1000.0,
357
- ...this.routingApiParams,
358
- },
359
- this.abortControllers[graph],
360
- )
361
- .then((featureCollection) => {
362
- this.segments = this.format.readFeatures(featureCollection);
363
-
364
- if (this.mot === 'foot') {
365
- // Extract unique values from viaPoint target value
366
- const uniqueVias = this.segments.reduce(
367
- (resultVias, currentFeat) => {
368
- const segTrg = currentFeat.get('trg');
369
- return resultVias.find(
370
- (via) => via[0] === segTrg[0] && via[1] === segTrg[1],
371
- )
372
- ? resultVias
373
- : [...resultVias, segTrg];
374
- },
375
- [],
376
- );
377
-
378
- // Create LineString features from segments with same unique value
379
- this.segments = uniqueVias.map((via) => {
380
- const viaSegments = this.segments.filter((seg) => {
381
- const segTrg = seg.get('trg');
382
- return segTrg[0] === via[0] && segTrg[1] === via[1];
383
- });
384
-
385
- const coords = getFlatCoordinatesFromSegments(viaSegments);
386
- return new Feature({
387
- geometry: new LineString(coords),
193
+ /**
194
+ * Removes a viaPoint at the passed array index and redraws route
195
+ * By default the last viaPoint is removed.
196
+ * @param {number} index Integer representing the index of the viaPoint to delete.
197
+ */
198
+ removeViaPoint(index = (this.viaPoints || []).length - 1) {
199
+ /* Remove viapoint and redraw route */
200
+ if (this.viaPoints.length && this.viaPoints[index]) {
201
+ this.viaPoints.splice(index, 1);
202
+ }
203
+ this.drawRoute();
204
+ this.dispatchEvent(new BaseEvent('change:route'));
205
+ }
206
+ /**
207
+ * Replaces the current viaPoints with a new coordinate array.
208
+ * @param {Array<Array<number>>} coordinateArray Array of nested coordinates
209
+ */
210
+ setViaPoints(coordinateArray) {
211
+ this.viaPoints = [...coordinateArray];
212
+ this.drawRoute();
213
+ this.dispatchEvent(new BaseEvent('change:route'));
214
+ }
215
+ /**
216
+ * Removes all viaPoints, clears the source and triggers a change event
217
+ */
218
+ reset() {
219
+ var _a, _b, _c;
220
+ // Clear viaPoints and source
221
+ this.abortRequests();
222
+ this.viaPoints = [];
223
+ (_c = (_b = (_a = this.routingLayer) === null || _a === void 0 ? void 0 : _a.olLayer) === null || _b === void 0 ? void 0 : _b.getSource()) === null || _c === void 0 ? void 0 : _c.clear();
224
+ this.dispatchEvent(new BaseEvent('change:route'));
225
+ }
226
+ /**
227
+ * Aborts viapoint and route requests
228
+ * @private
229
+ */
230
+ abortRequests() {
231
+ var _a;
232
+ // Abort Routing API requests
233
+ this.graphs.forEach((graph) => {
234
+ const graphName = graph[0];
235
+ if (this.abortControllers[graphName]) {
236
+ this.abortControllers[graphName].abort();
237
+ }
238
+ this.abortControllers[graphName] = new AbortController();
239
+ });
240
+ // Abort Stops API requests
241
+ (_a = this.abortControllers[STOP_FETCH_ABORT_CONTROLLER_KEY]) === null || _a === void 0 ? void 0 : _a.abort();
242
+ this.abortControllers[STOP_FETCH_ABORT_CONTROLLER_KEY] =
243
+ new AbortController();
244
+ this.loading = false;
245
+ }
246
+ /**
247
+ * Draws route on map using an array of coordinates:
248
+ * If a single coordinate is passed a single point feature is added to map.
249
+ * If two or more coordinates are passed a request to the RoutingAPI fetches
250
+ * the route using the passed coordinates and the current mot.
251
+ * @private
252
+ */
253
+ drawRoute() {
254
+ var _a, _b, _c, _d, _e, _f;
255
+ /* Calls RoutingAPI to draw a route using the viaPoints array */
256
+ this.abortRequests();
257
+ (_c = (_b = (_a = this.routingLayer) === null || _a === void 0 ? void 0 : _a.olLayer) === null || _b === void 0 ? void 0 : _b.getSource()) === null || _c === void 0 ? void 0 : _c.clear();
258
+ if (!this.viaPoints.length) {
259
+ return null;
260
+ }
261
+ if (this.viaPoints.length === 1) {
262
+ // Add point for first node
263
+ return this.drawViaPoint(this.viaPoints[0], 0, this.abortControllers[STOP_FETCH_ABORT_CONTROLLER_KEY]);
264
+ }
265
+ const formattedViaPoints = this.viaPoints.map((viaPoint) => {
266
+ var _a;
267
+ if (Array.isArray(viaPoint)) {
268
+ const projection = (_a = this.map) === null || _a === void 0 ? void 0 : _a.getView().getProjection();
269
+ // viaPoint is a coordinate
270
+ // Coordinates need to be reversed as required by the backend RoutingAPI
271
+ const [lon, lat] = toLonLat(viaPoint, projection);
272
+ return this.snapToClosestStation ? [`@${lat}`, lon] : [lat, lon];
273
+ }
274
+ // viaPoint is a string to use as it is
275
+ return this.useRawViaPoints ? viaPoint : `!${viaPoint}`;
276
+ });
277
+ this.loading = true;
278
+ // Clear source
279
+ (_f = (_e = (_d = this.routingLayer) === null || _d === void 0 ? void 0 : _d.olLayer) === null || _e === void 0 ? void 0 : _e.getSource()) === null || _f === void 0 ? void 0 : _f.clear();
280
+ // Create point features for the viaPoints
281
+ this.viaPoints.forEach((viaPoint, idx) => this.drawViaPoint(viaPoint, idx, this.abortControllers[STOP_FETCH_ABORT_CONTROLLER_KEY]));
282
+ return Promise.all(this.graphs.map(([graph], index) => {
283
+ const { signal } = this.abortControllers[graph];
284
+ if (!this.api) {
285
+ return Promise.resolve([]);
286
+ }
287
+ return this.api
288
+ .route(Object.assign({ graph, via: `${formattedViaPoints.join('|')}`, mot: this.mot,
289
+ // @ts-ignore missing property in swagger
290
+ 'resolve-hops': false, elevation: false, 'coord-radius': 100.0, 'coord-punish': 1000.0 }, (this.routingApiParams || {})), { signal })
291
+ .then((featureCollection) => {
292
+ var _a, _b, _c, _d;
293
+ this.segments = this.format.readFeatures(featureCollection);
294
+ if (this.mot === 'foot') {
295
+ // Extract unique values from viaPoint target value
296
+ const uniqueVias = this.segments.reduce((resultVias, currentFeat) => {
297
+ const segTrg = currentFeat.get('trg');
298
+ return resultVias.find((via) => via[0] === segTrg[0] && via[1] === segTrg[1])
299
+ ? resultVias
300
+ : [...resultVias, segTrg];
301
+ }, []);
302
+ // Create LineString features from segments with same unique value
303
+ this.segments = uniqueVias.map((via) => {
304
+ const viaSegments = this.segments.filter((seg) => {
305
+ const segTrg = seg.get('trg');
306
+ return segTrg[0] === via[0] && segTrg[1] === via[1];
307
+ });
308
+ const coords = getFlatCoordinatesFromSegments(viaSegments);
309
+ return new Feature({
310
+ geometry: new LineString(coords),
311
+ });
312
+ });
313
+ }
314
+ // Create the new route. This route will be modifiable by the Modifiy interaction.
315
+ const coords = getFlatCoordinatesFromSegments(this.segments);
316
+ const routeFeature = new Feature({
317
+ geometry: new LineString(coords),
388
318
  });
389
- });
319
+ routeFeature.set('graph', graph);
320
+ routeFeature.set('mot', this.mot);
321
+ if (this.graphsResolutions &&
322
+ ((_a = this.graphsResolutions[index]) === null || _a === void 0 ? void 0 : _a.length) >= 2) {
323
+ routeFeature.set('minResolution', this.graphsResolutions[index][0]);
324
+ routeFeature.set('maxResolution', this.graphsResolutions[index][1]);
325
+ }
326
+ (_d = (_c = (_b = this.routingLayer) === null || _b === void 0 ? void 0 : _b.olLayer) === null || _c === void 0 ? void 0 : _c.getSource()) === null || _d === void 0 ? void 0 : _d.addFeature(routeFeature);
327
+ this.loading = false;
328
+ })
329
+ .catch((error) => {
330
+ if (error.name === 'AbortError') {
331
+ // Ignore abort error
332
+ return;
333
+ }
334
+ this.segments = [];
335
+ // Dispatch error event and execute error function
336
+ this.dispatchEvent(new BaseEvent('error'));
337
+ this.onRouteError(error, this);
338
+ this.loading = false;
339
+ });
340
+ }));
341
+ }
342
+ /**
343
+ * Draw a via point. This function can parse all the possibilitiies
344
+ *
345
+ * @private
346
+ */
347
+ drawViaPoint(viaPoint, idx, abortController) {
348
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
349
+ const pointFeature = new Feature();
350
+ pointFeature.set('viaPointIdx', idx);
351
+ // The via point is a coordinate using the current map's projection
352
+ if (Array.isArray(viaPoint)) {
353
+ pointFeature.setGeometry(new Point(viaPoint));
354
+ (_c = (_b = (_a = this.routingLayer) === null || _a === void 0 ? void 0 : _a.olLayer) === null || _b === void 0 ? void 0 : _b.getSource()) === null || _c === void 0 ? void 0 : _c.addFeature(pointFeature);
355
+ return Promise.resolve(pointFeature);
356
+ }
357
+ // Possibility to parse:
358
+ //
359
+ // !8596126 a station with id 8596126
360
+ // !8596126$4 a station with id 8596126
361
+ if (!this.useRawViaPoints || REGEX_VIA_POINT_STATION_ID.test(viaPoint)) {
362
+ let stationId;
363
+ let track;
364
+ if (this.useRawViaPoints) {
365
+ [, stationId, , track] =
366
+ REGEX_VIA_POINT_STATION_ID.exec(viaPoint) || [];
367
+ }
368
+ else {
369
+ [stationId, track] = viaPoint.split('$');
390
370
  }
391
-
392
- // Create the new route. This route will be modifiable by the Modifiy interaction.
393
- const coords = getFlatCoordinatesFromSegments(this.segments);
394
-
395
- const routeFeature = new Feature({
396
- geometry: new LineString(coords),
371
+ return fetch(`${this.stopsApiUrl}lookup/${stationId}?key=${this.stopsApiKey}`, { signal: abortController.signal })
372
+ .then((res) => res.json())
373
+ .then((stationData) => {
374
+ var _a, _b, _c;
375
+ const { coordinates } = stationData.features[0].geometry;
376
+ this.cacheStationData[viaPoint] = fromLonLat(coordinates);
377
+ pointFeature.set('viaPointTrack', track);
378
+ pointFeature.setGeometry(new Point(fromLonLat(coordinates)));
379
+ (_c = (_b = (_a = this.routingLayer) === null || _a === void 0 ? void 0 : _a.olLayer) === null || _b === void 0 ? void 0 : _b.getSource()) === null || _c === void 0 ? void 0 : _c.addFeature(pointFeature);
380
+ return pointFeature;
381
+ })
382
+ .catch((error) => {
383
+ if (error.name === 'AbortError') {
384
+ // Ignore abort error
385
+ return;
386
+ }
387
+ // Dispatch error event and execute error function
388
+ this.dispatchEvent(new BaseEvent('error'));
389
+ this.onRouteError(error, this);
390
+ this.loading = false;
397
391
  });
398
- routeFeature.set('graph', graph);
399
- routeFeature.set('mot', this.mot);
400
- routeFeature.set('minResolution', this.graphsResolutions[index][0]);
401
- routeFeature.set('maxResolution', this.graphsResolutions[index][1]);
402
- this.routingLayer.olLayer.getSource().addFeature(routeFeature);
403
- this.loading = false;
404
- })
405
- .catch((error) => {
406
- if (error.name === 'AbortError') {
407
- // Ignore abort error
408
- return;
392
+ }
393
+ // Only when this.useRawViaPoints is true.
394
+ // Possibility to parse:
395
+ //
396
+ // 47.37811,8.53935 a position 47.37811, 8.53935
397
+ if (this.useRawViaPoints && REGEX_VIA_POINT_COORD.test(viaPoint)) {
398
+ const [lat, lon] = REGEX_VIA_POINT_COORD.exec(viaPoint) || [];
399
+ if (lon && lat) {
400
+ const floatLon = parseFloat(lon);
401
+ const floatLat = parseFloat(lat);
402
+ const coordinates = fromLonLat([floatLon, floatLat], (_d = this.map) === null || _d === void 0 ? void 0 : _d.getView().getProjection());
403
+ pointFeature.setGeometry(new Point(coordinates));
404
+ (_g = (_f = (_e = this.routingLayer) === null || _e === void 0 ? void 0 : _e.olLayer) === null || _f === void 0 ? void 0 : _f.getSource()) === null || _g === void 0 ? void 0 : _g.addFeature(pointFeature);
405
+ return Promise.resolve(pointFeature);
409
406
  }
410
- this.segments = [];
411
- // Dispatch error event and execute error function
412
- this.dispatchEvent({
413
- type: 'error',
414
- target: this,
407
+ }
408
+ // Only when this.useRawViaPoints is true.
409
+ // It will parse the via point to find some name, id, track coordinates.
410
+ //
411
+ // Possibility to parse:
412
+ //
413
+ // @47.37811,8.53935 a station at position 47.37811, 8.53935
414
+ // @47.37811,8.53935$4 track 4 in a station at position 47.37811, 8.53935
415
+ // zürich hb@47.37811,8.53935$8 track 8 in station "Zürich HB" at position 47.37811, 8.53935
416
+ const [, stationName, , lat, lon, , track] = REGEX_VIA_POINT.exec(viaPoint) || [];
417
+ if (lon && lat) {
418
+ const coordinates = fromLonLat([parseFloat(lon), parseFloat(lat)], (_h = this.map) === null || _h === void 0 ? void 0 : _h.getView().getProjection());
419
+ pointFeature.set('viaPointTrack', track);
420
+ pointFeature.setGeometry(new Point(coordinates));
421
+ (_l = (_k = (_j = this.routingLayer) === null || _j === void 0 ? void 0 : _j.olLayer) === null || _k === void 0 ? void 0 : _k.getSource()) === null || _l === void 0 ? void 0 : _l.addFeature(pointFeature);
422
+ return Promise.resolve(pointFeature);
423
+ }
424
+ if (stationName) {
425
+ return fetch(`${this.stopsApiUrl}?key=${this.stopsApiKey}&q=${stationName}&limit=1`, { signal: abortController.signal })
426
+ .then((res) => res.json())
427
+ .then((stationData) => {
428
+ var _a, _b, _c;
429
+ const { coordinates } = stationData.features[0].geometry;
430
+ this.cacheStationData[viaPoint] = fromLonLat(coordinates);
431
+ pointFeature.set('viaPointTrack', track);
432
+ pointFeature.setGeometry(new Point(fromLonLat(coordinates)));
433
+ (_c = (_b = (_a = this.routingLayer) === null || _a === void 0 ? void 0 : _a.olLayer) === null || _b === void 0 ? void 0 : _b.getSource()) === null || _c === void 0 ? void 0 : _c.addFeature(pointFeature);
434
+ return pointFeature;
435
+ })
436
+ .catch((error) => {
437
+ // Dispatch error event and execute error function
438
+ this.dispatchEvent(new BaseEvent('error'));
439
+ this.onRouteError(error, this);
440
+ this.loading = false;
441
+ return null;
415
442
  });
416
- this.onRouteError(error, this);
417
- this.loading = false;
418
- });
419
- }),
420
- );
421
- }
422
-
423
- /**
424
- * Draw a via point. This function can parse all the possibilitiies
425
- *
426
- * @private
427
- */
428
- drawViaPoint(viaPoint, idx, abortController) {
429
- const pointFeature = new Feature();
430
- pointFeature.set('viaPointIdx', idx);
431
-
432
- // The via point is a coordinate using the current map's projection
433
- if (Array.isArray(viaPoint)) {
434
- pointFeature.setGeometry(new Point(viaPoint));
435
- this.routingLayer.olLayer.getSource().addFeature(pointFeature);
436
- return Promise.resolve(pointFeature);
443
+ }
444
+ return Promise.resolve(null);
437
445
  }
438
-
439
- // Possibility to parse:
440
- //
441
- // !8596126 a station with id 8596126
442
- // !8596126$4 a station with id 8596126
443
- if (!this.useRawViaPoints || REGEX_VIA_POINT_STATION_ID.test(viaPoint)) {
444
- let stationId;
445
- let track;
446
- if (this.useRawViaPoints) {
447
- [, stationId, , track] = REGEX_VIA_POINT_STATION_ID.exec(viaPoint);
448
- } else {
449
- [stationId, track] = viaPoint.split('$');
450
- }
451
-
452
- return fetch(
453
- `${this.stopsApiUrl}lookup/${stationId}?key=${this.stopsApiKey}`,
454
- { signal: abortController.signal },
455
- )
456
- .then((res) => res.json())
457
- .then((stationData) => {
458
- const { coordinates } = stationData.features[0].geometry;
459
- this.cacheStationData[viaPoint] = fromLonLat(coordinates);
460
- pointFeature.set('viaPointTrack', track);
461
- pointFeature.setGeometry(new Point(fromLonLat(coordinates)));
462
- this.routingLayer.olLayer.getSource().addFeature(pointFeature);
463
- return pointFeature;
464
- })
465
- .catch((error) => {
466
- if (error.name === 'AbortError') {
467
- // Ignore abort error
468
- return;
469
- }
470
- // Dispatch error event and execute error function
471
- this.dispatchEvent({
472
- type: 'error',
473
- target: this,
474
- });
475
- this.onRouteError(error, this);
476
- this.loading = false;
446
+ /**
447
+ * Used on click on map while control is active:
448
+ * By default adds a viaPoint to the end of array.
449
+ * If an existing viaPoint is clicked removes the clicked viaPoint.
450
+ * @private
451
+ */
452
+ onMapClick(evt) {
453
+ const feats = evt.target.getFeaturesAtPixel(evt.pixel);
454
+ const viaPoint = feats.find((feat) => {
455
+ var _a;
456
+ return ((_a = feat.getGeometry()) === null || _a === void 0 ? void 0 : _a.getType()) === 'Point' &&
457
+ feat.get('viaPointIdx') !== undefined;
477
458
  });
459
+ if (viaPoint) {
460
+ // Remove existing viaPoint on click and abort viaPoint add
461
+ this.removeViaPoint(viaPoint.get('viaPointIdx'));
462
+ return;
463
+ }
464
+ this.addViaPoint(evt.coordinate);
478
465
  }
479
-
480
- // Only when this.useRawViaPoints is true.
481
- // Possibility to parse:
482
- //
483
- // 47.37811,8.53935 a position 47.37811, 8.53935
484
- if (this.useRawViaPoints && REGEX_VIA_POINT_COORD.test(viaPoint)) {
485
- const [lat, lon] = REGEX_VIA_POINT_COORD.exec(viaPoint);
486
- const coordinates = fromLonLat(
487
- [parseFloat(lon), parseFloat(lat)],
488
- this.map.getView().getProjection(),
489
- );
490
- pointFeature.setGeometry(new Point(coordinates));
491
- this.routingLayer.olLayer.getSource().addFeature(pointFeature);
492
- return Promise.resolve(pointFeature);
466
+ /**
467
+ * Used on start of the modify interaction. Stores relevant data
468
+ * in this.initialRouteDrag object
469
+ * @private
470
+ */
471
+ onModifyStart(evt) {
472
+ var _a;
473
+ // When modify start, we search the index of the segment that is modifying.
474
+ let segmentIndex = -1;
475
+ const route = evt.features
476
+ .getArray()
477
+ .find((feat) => { var _a; return ((_a = feat.getGeometry()) === null || _a === void 0 ? void 0 : _a.getType()) === 'LineString'; });
478
+ // Find the segment index that is being modified
479
+ if (route && route.getGeometry() && evt.mapBrowserEvent.coordinate) {
480
+ // We use a buff extent to fix floating issues , see https://github.com/openlayers/openlayers/issues/7130#issuecomment-535856422
481
+ const closestExtent = buffer(new Point(
482
+ // @ts-ignore
483
+ (_a = route.getGeometry()) === null || _a === void 0 ? void 0 : _a.getClosestPoint(evt.mapBrowserEvent.coordinate)).getExtent(), 0.001);
484
+ segmentIndex = this.segments.findIndex((segment) => { var _a; return (_a = segment.getGeometry()) === null || _a === void 0 ? void 0 : _a.intersectsExtent(closestExtent); });
485
+ }
486
+ // Find the viaPoint that is being modified
487
+ const viaPoint = (evt.features
488
+ .getArray()
489
+ .filter((feat) => { var _a; return ((_a = feat.getGeometry()) === null || _a === void 0 ? void 0 : _a.getType()) === 'Point'; }) ||
490
+ [])[0];
491
+ // Write object with modify info
492
+ /** @ignore */
493
+ this.initialRouteDrag = {
494
+ viaPoint,
495
+ oldRoute: route && route.clone(),
496
+ segmentIndex,
497
+ };
493
498
  }
494
-
495
- // Only when this.useRawViaPoints is true.
496
- // It will parse the via point to find some name, id, track coordinates.
497
- //
498
- // Possibility to parse:
499
- //
500
- // @47.37811,8.53935 a station at position 47.37811, 8.53935
501
- // @47.37811,8.53935$4 track 4 in a station at position 47.37811, 8.53935
502
- // zürich hb@47.37811,8.53935$8 track 8 in station "Zürich HB" at position 47.37811, 8.53935
503
- const [, stationName, , lat, lon, , track] = REGEX_VIA_POINT.exec(viaPoint);
504
-
505
- if (lon && lat) {
506
- const coordinates = fromLonLat(
507
- [parseFloat(lon), parseFloat(lat)],
508
- this.map.getView().getProjection(),
509
- );
510
- pointFeature.set('viaPointTrack', track);
511
- pointFeature.setGeometry(new Point(coordinates));
512
- this.routingLayer.olLayer.getSource().addFeature(pointFeature);
513
- return Promise.resolve(pointFeature);
499
+ /**
500
+ * Used on end of the modify interaction. Resolves feature modification:
501
+ * Line drag creates new viaPoint at the final coordinate of drag.
502
+ * Point drag replaces old viaPoint.
503
+ * @private
504
+ */
505
+ onModifyEnd(evt) {
506
+ const coord = evt.mapBrowserEvent.coordinate;
507
+ const { oldRoute, viaPoint, segmentIndex } = this.initialRouteDrag || {};
508
+ // If viaPoint is being relocated overwrite the old viaPoint
509
+ if (viaPoint) {
510
+ return this.addViaPoint(coord, viaPoint.get('viaPointIdx'), 1);
511
+ }
512
+ // In case there is no route overwrite first coordinate
513
+ if (!oldRoute) {
514
+ return this.addViaPoint(coord, 0, 1);
515
+ }
516
+ // We can't add a via point because we haven't found which segment has been modified.
517
+ if (segmentIndex === -1) {
518
+ return Promise.reject(new Error('No segment found'));
519
+ }
520
+ // Insert new viaPoint at the modified segment index + 1
521
+ return this.addViaPoint(coord, (segmentIndex || 0) + 1);
514
522
  }
515
-
516
- if (stationName) {
517
- return fetch(
518
- `${this.stopsApiUrl}?key=${this.stopsApiKey}&q=${stationName}&limit=1`,
519
- { signal: abortController.signal },
520
- )
521
- .then((res) => res.json())
522
- .then((stationData) => {
523
- const { coordinates } = stationData.features[0].geometry;
524
- this.cacheStationData[viaPoint] = fromLonLat(coordinates);
525
- pointFeature.set('viaPointTrack', track);
526
- pointFeature.setGeometry(new Point(fromLonLat(coordinates)));
527
- this.routingLayer.olLayer.getSource().addFeature(pointFeature);
528
- return pointFeature;
529
- })
530
- .catch((error) => {
531
- // Dispatch error event and execute error function
532
- this.dispatchEvent({
533
- type: 'error',
534
- target: this,
535
- });
536
- this.onRouteError(error, this);
537
- this.loading = false;
538
- return null;
523
+ /**
524
+ * Define a default element.
525
+ *
526
+ * @private
527
+ */
528
+ createDefaultElement() {
529
+ /** @ignore */
530
+ this.element = document.createElement('button');
531
+ this.element.id = 'ol-toggle-routing';
532
+ this.element.innerHTML = 'Toggle Route Control';
533
+ this.element.onclick = () => this.active ? this.deactivate() : this.activate();
534
+ Object.assign(this.element.style, {
535
+ position: 'absolute',
536
+ right: '10px',
537
+ top: '10px',
539
538
  });
540
539
  }
541
- return Promise.resolve(null);
542
- }
543
-
544
- /**
545
- * Used on click on map while control is active:
546
- * By default adds a viaPoint to the end of array.
547
- * If an existing viaPoint is clicked removes the clicked viaPoint.
548
- * @private
549
- */
550
- onMapClick(e) {
551
- const feats = e.target.getFeaturesAtPixel(e.pixel);
552
- const viaPoint = feats.find(
553
- (feat) =>
554
- feat.getGeometry() instanceof Point &&
555
- feat.get('viaPointIdx') !== undefined,
556
- );
557
-
558
- if (viaPoint) {
559
- // Remove existing viaPoint on click and abort viaPoint add
560
- this.removeViaPoint(viaPoint.get('viaPointIdx'));
561
- return;
562
- }
563
-
564
- this.addViaPoint(e.coordinate);
565
- }
566
-
567
- /**
568
- * Used on start of the modify interaction. Stores relevant data
569
- * in this.initialRouteDrag object
570
- * @private
571
- */
572
- onModifyStart(evt) {
573
- // When modify start, we search the index of the segment that is modifying.
574
- let segmentIndex = -1;
575
- const route = evt.features
576
- .getArray()
577
- .find((feat) => feat.getGeometry() instanceof LineString);
578
-
579
- // Find the segment index that is being modified
580
- if (route) {
581
- // We use a buff extent to fix floating issues , see https://github.com/openlayers/openlayers/issues/7130#issuecomment-535856422
582
- const closestExtent = buffer(
583
- new Point(
584
- route.getGeometry().getClosestPoint(evt.mapBrowserEvent.coordinate),
585
- ).getExtent(),
586
- 0.001,
587
- );
588
-
589
- segmentIndex = this.segments.findIndex((segment) =>
590
- segment.getGeometry().intersectsExtent(closestExtent),
591
- );
592
- }
593
-
594
- // Find the viaPoint that is being modified
595
- const viaPoint = (evt.features
596
- .getArray()
597
- .filter((feat) => feat.getGeometry() instanceof Point) || [])[0];
598
-
599
- // Write object with modify info
600
- /** @ignore */
601
- this.initialRouteDrag = {
602
- viaPoint,
603
- oldRoute: route && route.clone(),
604
- segmentIndex,
605
- };
606
- }
607
-
608
- /**
609
- * Used on end of the modify interaction. Resolves feature modification:
610
- * Line drag creates new viaPoint at the final coordinate of drag.
611
- * Point drag replaces old viaPoint.
612
- * @private
613
- */
614
- onModifyEnd(evt) {
615
- const coord = evt.mapBrowserEvent.coordinate;
616
- const { oldRoute, viaPoint, segmentIndex } = this.initialRouteDrag;
617
-
618
- // If viaPoint is being relocated overwrite the old viaPoint
619
- if (viaPoint) {
620
- return this.addViaPoint(coord, viaPoint.get('viaPointIdx'), 1);
621
- }
622
-
623
- // In case there is no route overwrite first coordinate
624
- if (!oldRoute) {
625
- return this.addViaPoint(coord, 0, 1);
540
+ /**
541
+ * Create the interaction used to modify vertexes of features.
542
+ * @private
543
+ */
544
+ createModifyInteraction() {
545
+ var _a, _b, _c;
546
+ /**
547
+ * @type {ol.interaction.Modify}
548
+ * @private
549
+ */
550
+ // Define and add modify interaction
551
+ this.modifyInteraction = new Modify({
552
+ source: ((_b = (_a = this.routingLayer) === null || _a === void 0 ? void 0 : _a.olLayer) === null || _b === void 0 ? void 0 : _b.getSource()) || undefined,
553
+ pixelTolerance: 4,
554
+ hitDetection: (_c = this.routingLayer) === null || _c === void 0 ? void 0 : _c.olLayer,
555
+ deleteCondition: (e) => {
556
+ const feats = e.target.getFeaturesAtPixel(e.pixel, {
557
+ hitTolerance: 5,
558
+ });
559
+ const viaPoint = feats.find((feat) => { var _a; return ((_a = feat.getGeometry()) === null || _a === void 0 ? void 0 : _a.getType()) === 'Point' && feat.get('index'); });
560
+ if (click(e) && viaPoint) {
561
+ // Remove node & viaPoint if an existing viaPoint was clicked
562
+ this.removeViaPoint(viaPoint.get('index'));
563
+ return true;
564
+ }
565
+ return false;
566
+ },
567
+ });
568
+ this.modifyInteraction.on('modifystart', this.onModifyStart);
569
+ this.modifyInteraction.on('modifyend', this.onModifyEnd);
570
+ this.modifyInteraction.setActive(false);
626
571
  }
627
-
628
- // We can't add a via point because we haven't found which segment has been modified.
629
- if (segmentIndex === -1) {
630
- return Promise.reject(new Error('No segment found'));
572
+ /**
573
+ * Add click listener to map.
574
+ * @private
575
+ */
576
+ addListeners() {
577
+ var _a;
578
+ if (!this.modify) {
579
+ return;
580
+ }
581
+ this.removeListeners();
582
+ /** @ignore */
583
+ this.onMapClickKey = (_a = this.map) === null || _a === void 0 ? void 0 : _a.on('singleclick', this.onMapClick);
631
584
  }
632
-
633
- // Insert new viaPoint at the modified segment index + 1
634
- return this.addViaPoint(coord, segmentIndex + 1);
635
- }
636
-
637
- /**
638
- * Define a default element.
639
- *
640
- * @private
641
- */
642
- createDefaultElement() {
643
- /** @ignore */
644
- this.element = document.createElement('button');
645
- this.element.id = 'ol-toggle-routing';
646
- this.element.innerHTML = 'Toggle Route Control';
647
- this.element.onclick = () =>
648
- this.active ? this.deactivate() : this.activate();
649
- Object.assign(this.element.style, {
650
- position: 'absolute',
651
- right: '10px',
652
- top: '10px',
653
- });
654
- }
655
-
656
- /**
657
- * Create the interaction used to modify vertexes of features.
658
- * @private
659
- */
660
- createModifyInteraction() {
661
585
  /**
662
- * @type {ol.interaction.Modify}
586
+ * Remove click listener from map.
663
587
  * @private
664
588
  */
665
- // Define and add modify interaction
666
- this.modifyInteraction = new Modify({
667
- source: this.routingLayer.olLayer.getSource(),
668
- pixelTolerance: 4,
669
- hitDetection: this.routingLayer.olLayer,
670
- deleteCondition: (e) => {
671
- const feats = e.target.getFeaturesAtPixel(e.pixel, {
672
- hitTolerance: 5,
673
- });
674
- const viaPoint = feats.find(
675
- (feat) => feat.getGeometry() instanceof Point && feat.get('index'),
676
- );
677
- if (click(e) && viaPoint) {
678
- // Remove node & viaPoint if an existing viaPoint was clicked
679
- this.removeViaPoint(viaPoint.get('index'));
680
- return true;
589
+ removeListeners() {
590
+ if (this.onMapClickKey) {
591
+ unByKey(this.onMapClickKey);
681
592
  }
682
- return false;
683
- },
684
- });
685
- this.modifyInteraction.on('modifystart', this.onModifyStart);
686
- this.modifyInteraction.on('modifyend', this.onModifyEnd);
687
- this.modifyInteraction.setActive(false);
688
- }
689
-
690
- /**
691
- * Add click listener to map.
692
- * @private
693
- */
694
- addListeners() {
695
- if (!this.modify) {
696
- return;
697
593
  }
698
- this.removeListeners();
699
- /** @ignore */
700
- this.onMapClickKey = this.map.on('singleclick', this.onMapClick);
701
- }
702
-
703
- /**
704
- * Remove click listener from map.
705
- * @private
706
- */
707
- removeListeners() {
708
- unByKey(this.onMapClickKey);
709
- }
710
-
711
- activate() {
712
- super.activate();
713
- if (this.map) {
714
- /** @ignore */
715
- this.format = new GeoJSON({
716
- featureProjection: this.map.getView().getProjection(),
717
- });
718
-
719
- /** @ignore */
720
- this.graphsResolutions = RoutingControl.getGraphsResolutions(
721
- this.graphs,
722
- this.map,
723
- );
724
-
725
- // Clean the modifyInteraction if present
726
- this.map.removeInteraction(this.modifyInteraction);
727
-
728
- // Add modify interaction, RoutingLayer and listeners
729
- this.routingLayer.init(this.map);
730
- this.map.addInteraction(this.modifyInteraction);
731
- this.modifyInteraction.setActive(this.modify);
732
- this.addListeners();
733
- } else {
734
- // fall back to some default values if map is not available
735
- this.format = new GeoJSON({ featureProjection: 'EPSG:3857' });
736
- this.graphsResolutions = this.graphs;
594
+ activate() {
595
+ var _a, _b;
596
+ super.activate();
597
+ if (this.map) {
598
+ /** @ignore */
599
+ this.format = new GeoJSON({
600
+ featureProjection: this.map.getView().getProjection(),
601
+ });
602
+ /** @ignore */
603
+ this.graphsResolutions = RoutingControl.getGraphsResolutions(this.graphs, this.map);
604
+ // Clean the modifyInteraction if present
605
+ if (this.modifyInteraction) {
606
+ this.map.removeInteraction(this.modifyInteraction);
607
+ }
608
+ // Add modify interaction, RoutingLayer and listeners
609
+ (_a = this.routingLayer) === null || _a === void 0 ? void 0 : _a.attachToMap(this.map);
610
+ if (this.modifyInteraction) {
611
+ this.map.addInteraction(this.modifyInteraction);
612
+ }
613
+ (_b = this.modifyInteraction) === null || _b === void 0 ? void 0 : _b.setActive(this.modify);
614
+ this.addListeners();
615
+ }
737
616
  }
738
- }
739
-
740
- deactivate() {
741
- if (this.map) {
742
- // Remove modify interaction, RoutingLayer, listeners and viaPoints
743
- this.routingLayer.terminate(this.map);
744
- this.map.removeInteraction(this.modifyInteraction);
745
- this.removeListeners();
746
- this.reset();
617
+ deactivate() {
618
+ var _a;
619
+ if (this.map) {
620
+ // Remove modify interaction, RoutingLayer, listeners and viaPoints
621
+ (_a = this.routingLayer) === null || _a === void 0 ? void 0 : _a.detachFromMap();
622
+ if (this.modifyInteraction) {
623
+ this.map.removeInteraction(this.modifyInteraction);
624
+ }
625
+ this.removeListeners();
626
+ this.reset();
627
+ }
747
628
  }
748
- super.deactivate();
749
- }
629
+ render() { }
750
630
  }
751
-
752
631
  export default RoutingControl;