-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathdefault-map.tsx
489 lines (460 loc) · 16.2 KB
/
default-map.tsx
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
/* eslint-disable react/prop-types */
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
import { connect } from 'react-redux'
import { GeolocateControl, NavigationControl } from 'react-map-gl'
import { injectIntl } from 'react-intl'
import BaseMap from '@opentripplanner/base-map'
import generateOTP2TileLayers from '@opentripplanner/otp2-tile-overlay'
import React, { Component } from 'react'
import styled from 'styled-components'
import {
assembleBasePath,
bikeRentalQuery,
carRentalQuery,
vehicleRentalQuery
} from '../../actions/api'
import { ComponentContext } from '../../util/contexts'
import { getActiveItinerary, getActiveSearch } from '../../util/state'
import { getCurrentPosition } from '../../actions/location'
import { MainPanelContent } from '../../actions/ui-constants'
import { setLocation, setMapPopupLocationAndGeocode } from '../../actions/map'
import { setViewedStop } from '../../actions/ui'
import { updateOverlayVisibility } from '../../actions/config'
import VehiclePositionRetriever from '../viewers/vehicle-position-retriever'
import ElevationPointMarker from './elevation-point-marker'
import EndpointsOverlay from './connected-endpoints-overlay'
import FullTransitVehicleOverlay from './connected-full-transit-vehicle-overlay'
import GeoJsonLayer from './connected-geojson-layer'
import ItinSummaryOverlay from './itinerary-summary-overlay'
import NearbyViewDotOverlay from './nearby-view-dot-overlay'
import ParkAndRideOverlay from './connected-park-and-ride-overlay'
import PointPopup from './point-popup'
import RoutePreviewOverlay from './route-preview-overlay'
import RouteViewerOverlay from './connected-route-viewer-overlay'
import StopsOverlay from './connected-stops-overlay'
import TransitiveOverlay from './connected-transitive-overlay'
import TransitVehicleOverlay from './connected-transit-vehicle-overlay'
import TripViewerOverlay from './connected-trip-viewer-overlay'
import VehicleRentalOverlay from './connected-vehicle-rental-overlay'
import withMap from './with-map'
const MapContainer = styled.div`
height: 100%;
width: 100%;
.map {
height: 100%;
width: 100%;
}
* {
box-sizing: unset;
}
.maplibregl-popup-content,
.mapboxgl-popup-content {
border-radius: 10px;
box-shadow: 0 3px 14px 4px rgb(0 0 0 / 20%);
}
`
/**
* Get the configured display names for the specified company ids.
*/
function getCompanyNames(companyIds, config, intl) {
return intl.formatList(
(companyIds || []).map(
(id) =>
config.companies?.find((company) => company.id === id)?.label || id
),
{ type: 'conjunction' }
)
}
/**
* Determines the localized name of a map layer by its type.
*/
function getLayerName(overlay, config, intl) {
const { companies, name, type } = overlay
// HACK: Support for street/satellite configs that use the name.
switch (name) {
case 'Streets':
return intl.formatMessage({ id: 'components.MapLayers.streets' })
case 'Satellite':
return intl.formatMessage({ id: 'components.MapLayers.satellite' })
default:
if (name) return name
}
// If overlay.name is not specified, use the type to determine the name.
switch (type) {
case 'streets':
return intl.formatMessage({ id: 'components.MapLayers.streets' })
case 'satellite':
return intl.formatMessage({ id: 'components.MapLayers.satellite' })
case 'bike-rental':
case 'otp2-bike-rental':
case 'rentalStations':
return intl.formatMessage(
{ id: 'components.MapLayers.bike-rental' },
{
companies: getCompanyNames(companies, config, intl)
}
)
case 'car-rental':
return intl.formatMessage({ id: 'components.MapLayers.car-rental' })
case 'micromobility-rental':
case 'otp2-micromobility-rental':
return intl.formatMessage(
{
id: 'components.MapLayers.micromobility-rental'
},
{
companies: getCompanyNames(companies, config, intl)
}
)
case 'park-and-ride':
return intl.formatMessage({ id: 'components.MapLayers.park-and-ride' })
case 'stops':
return intl.formatMessage({ id: 'components.MapLayers.stops' })
case 'stations':
return intl.formatMessage({ id: 'components.MapLayers.stations' })
case 'rentalVehicles':
if (overlay.network)
return getCompanyNames([overlay.network], config, intl)
return intl.formatMessage({ id: 'components.MapLayers.shared-vehicles' })
case 'otp2':
// The otp2 type will result in multiple layers, so don't show a warning.
return type
default:
console.warn(`No name found for overlay type ${type}.`)
return type
}
}
class DefaultMap extends Component {
static contextType = ComponentContext
constructor(props) {
super(props)
// We have to maintain the map state because the underlying map also (incorrectly?) uses a state.
// Not maintaining a state causes re-renders to the map's configured coordinates.
const {
initLat: lat = null,
initLon: lon = null,
initZoom: zoom = 13
} = props.mapConfig || {}
this.state = {
lat,
lon,
zoom
}
}
/**
* Checks whether the modes have changed between old and new queries and
* whether to update the map overlays accordingly (e.g., to show rental vehicle
* options on the map).
*
* Note: This functionality only works for the tabbed interface,
* as that UI mode sets the access mode and company in the query params.
* TODO: Implement for the batch interface.
*/
_handleQueryChange = (oldQuery, newQuery) => {
const { overlays = [] } = this.props.mapConfig || {}
if (oldQuery.mode) {
// Determine any added/removed modes
const oldModes = oldQuery.mode.split(',')
const newModes = newQuery.mode.split(',')
const removed = oldModes.filter((m) => !newModes.includes(m))
const added = newModes.filter((m) => !oldModes.includes(m))
const overlayVisibility = []
for (const oConfig of overlays) {
if (!oConfig.modes || oConfig.modes.length !== 1) continue
// TODO: support multi-mode overlays
const overlayMode = oConfig.modes[0]
if (
(overlayMode === 'CAR_RENT' ||
overlayMode === 'CAR_HAIL' ||
overlayMode === 'MICROMOBILITY_RENT' ||
overlayMode === 'SCOOTER') &&
oConfig.companies
) {
// Special handling for company-based mode overlays (e.g. carshare, car-hail)
const overlayCompany = oConfig.companies[0] // TODO: handle multi-company overlays
if (added.includes(overlayMode)) {
// Company-based mode was just selected; enable overlay iff overlay's company is active
if (newQuery.companies?.includes(overlayCompany)) {
overlayVisibility.push({
overlay: oConfig,
visible: true
})
}
} else if (removed.includes(overlayMode)) {
// Company-based mode was just deselected; disable overlay (regardless of company)
overlayVisibility.push({
overlay: oConfig,
visible: false
})
} else if (
newModes.includes(overlayMode) &&
oldQuery.companies !== newQuery.companies
) {
// Company-based mode remains selected but companies change
overlayVisibility.push({
overlay: oConfig,
visible: newQuery.companies.includes(overlayCompany)
})
}
} else {
// Default handling for other modes
if (added.includes(overlayMode)) {
overlayVisibility.push({
overlay: oConfig,
visible: true
})
}
if (removed.includes(overlayMode)) {
overlayVisibility.push({
overlay: oConfig,
visible: false
})
}
}
}
// Only trigger update action if there are overlays to update.
if (overlayVisibility.length > 0) {
this.props.updateOverlayVisibility(overlayVisibility)
}
}
}
onMapClick = (e) => {
this.props.setMapPopupLocationAndGeocode(e)
}
componentDidMount() {
// HACK: Set state lat and lon to null to prevent re-rendering of the
// underlying OTP-UI map.
this.setState({
lat: null,
lon: null
})
}
componentDidUpdate(prevProps) {
// Check if any overlays should be toggled due to mode change
this._handleQueryChange(prevProps.query, this.props.query)
}
render() {
const {
bikeRentalQuery,
bikeRentalStations,
carRentalQuery,
carRentalStations,
config,
getCurrentPosition,
intl,
itinerary,
mapConfig,
nearbyViewActive,
pending,
setLocation,
setViewedStop,
vehicleRentalQuery,
vehicleRentalStations,
viewedRouteStops
} = this.props
const { getCustomMapOverlays, getTransitiveRouteLabel, ModeIcon } =
this.context
const { baseLayers, maxZoom, navigationControlPosition, overlays } =
mapConfig || {}
const { lat, lon, zoom } = this.state
const vectorTilesEndpoint = `${assembleBasePath(config)}${
config.api?.path
}/vectorTiles`
const bikeStations = [
...bikeRentalStations.filter(
(station) =>
!station.isFloatingVehicle || station.isFloatingVehicle === false
),
...vehicleRentalStations.filter(
(station) => station.isFloatingBike === true
)
]
const scooterStations = vehicleRentalStations.filter(
(station) => station.isFloatingBike === false && station.isFloatingVehicle
)
const baseLayersWithNames = baseLayers?.map((baseLayer) => ({
...baseLayer,
name: getLayerName(baseLayer, config, intl)
}))
const baseLayerUrls = baseLayersWithNames?.map((bl) => bl.url)
const baseLayerNames = baseLayersWithNames?.map((bl) => bl.name)
return (
<MapContainer className="percy-hide">
<BaseMap
baseLayer={
baseLayerUrls?.length > 1 ? baseLayerUrls : baseLayerUrls?.[0]
}
baseLayerNames={baseLayerNames}
center={[lat, lon]}
mapLibreProps={{ reuseMaps: true }}
maxZoom={maxZoom}
// In Leaflet, this was an onclick handler. Creating a click handler in
// MapLibreGL would require writing a custom event handler for all mouse events
onContextMenu={this.onMapClick}
showEverything={nearbyViewActive}
zoom={zoom}
>
<PointPopup />
<NearbyViewDotOverlay />
<ItinSummaryOverlay />
<RoutePreviewOverlay />
{/* The default overlays */}
<EndpointsOverlay />
<RouteViewerOverlay />
<TransitVehicleOverlay ModeIcon={ModeIcon} />
<GeolocateControl
onGeolocate={() => {
getCurrentPosition(intl)
}}
position="top-left"
/>
<TransitiveOverlay
getTransitiveRouteLabel={getTransitiveRouteLabel}
/>
<TripViewerOverlay />
<ElevationPointMarker />
{/* The configurable overlays */}
{overlays?.map((overlayConfig, k) => {
const namedLayerProps = {
...overlayConfig,
id: k,
key: k,
name: getLayerName(overlayConfig, config, intl)
}
switch (overlayConfig.type) {
case 'geojson':
return (
<GeoJsonLayer {...namedLayerProps} url={overlayConfig.url} />
)
case 'bike-rental':
return (
<VehicleRentalOverlay
{...namedLayerProps}
refreshVehicles={bikeRentalQuery}
stations={bikeRentalStations}
/>
)
case 'car-rental':
return (
<VehicleRentalOverlay
{...namedLayerProps}
refreshVehicles={carRentalQuery}
stations={carRentalStations}
/>
)
case 'park-and-ride':
return <ParkAndRideOverlay {...namedLayerProps} />
case 'stops':
return <StopsOverlay {...namedLayerProps} />
case 'micromobility-rental':
return (
<VehicleRentalOverlay
{...namedLayerProps}
refreshVehicles={vehicleRentalQuery}
stations={vehicleRentalStations}
/>
)
case 'otp2-micromobility-rental':
return (
<VehicleRentalOverlay
key={k}
{...namedLayerProps}
refreshVehicles={vehicleRentalQuery}
stations={scooterStations}
/>
)
case 'otp2-bike-rental':
return (
<VehicleRentalOverlay
key={k}
{...namedLayerProps}
refreshVehicles={bikeRentalQuery}
stations={bikeStations}
/>
)
case 'otp2':
// This must be a method that returns an array of JSX
// as the base-map requires that every toggleable layer
// is its own component, and not a subcomponent of another component
return generateOTP2TileLayers(
overlayConfig.layers.map((l) => ({
...l,
name: getLayerName(l, config, intl) || l.network || l.type
})),
vectorTilesEndpoint,
setLocation,
setViewedStop,
viewedRouteStops,
config.companies
)
case 'realtime-vehicles':
return <FullTransitVehicleOverlay {...namedLayerProps} />
default:
return null
}
})}
{/* If set, custom overlays are shown if no active itinerary is shown or pending. */}
{typeof getCustomMapOverlays === 'function' &&
getCustomMapOverlays(!itinerary && !pending)}
<NavigationControl
position={navigationControlPosition || 'bottom-right'}
/>
{overlays.map((o) => o.type).includes('realtime-vehicles') && (
<VehiclePositionRetriever fetchAll />
)}
</BaseMap>
</MapContainer>
)
}
}
// connect to the redux store
const mapStateToProps = (state) => {
const activeSearch = getActiveSearch(state)
const viewedRoute = state.otp?.ui?.viewedRoute?.routeId
const nearbyViewerActive =
state.otp.ui.mainPanelContent === MainPanelContent.NEARBY_VIEW
const viewedRoutePatterns = Object.entries(
state.otp?.transitIndex?.routes?.[viewedRoute]?.patterns || {}
)
const viewedRouteStops =
viewedRoute && !nearbyViewerActive
? // Ensure we don't have duplicates
Array.from(
new Set(
// Generate a list of every stop id the pattern stops at
viewedRoutePatterns.reduce((acc, cur) => {
// Convert pattern object to list of the pattern's stops
return [...cur?.[1]?.stops.map((s) => s.id), ...acc]
}, [])
)
)
: null
return {
bikeRentalStations: state.otp.overlay.bikeRental.stations,
carRentalStations: state.otp.overlay.carRental.stations,
config: state.otp.config,
itinerary: getActiveItinerary(state),
mapConfig: state.otp.config.map,
nearbyViewActive:
state.otp.ui.mainPanelContent === MainPanelContent.NEARBY_VIEW,
pending: activeSearch ? Boolean(activeSearch.pending) : false,
query: state.otp.currentQuery,
vehicleRentalStations: state.otp.overlay.vehicleRental.stations,
viewedRouteStops
}
}
const mapDispatchToProps = {
bikeRentalQuery,
carRentalQuery,
getCurrentPosition,
setLocation,
setMapPopupLocationAndGeocode,
setViewedStop,
updateOverlayVisibility,
vehicleRentalQuery
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(injectIntl(withMap(DefaultMap)))