Skip to content

feat: see planned rout even when no actual ride was executed #1070

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 62 additions & 64 deletions src/hooks/useSingleLineData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,101 +6,99 @@ import { BusStop } from 'src/model/busStop'
import { SearchContext } from 'src/model/pageState'
import { Point } from 'src/pages/timeBasedMap'

const formatTime = (time: moment.Moment) => time.format('HH:mm:ss')

export const useSingleLineData = (lineRef?: number, routeIds?: number[]) => {
const {
search: { timestamp },
} = useContext(SearchContext)

const [filteredPositions, setFilteredPositions] = useState<Point[]>([])
const [startTime, setStartTime] = useState<string>('00:00:00')
const [plannedRouteStops, setPlannedRouteStops] = useState<BusStop[]>([])
const today = new Date(timestamp)
const tomorrow = new Date(today)
tomorrow.setDate(tomorrow.getDate() + 1)
const [startTime, setStartTime] = useState<string>()

const [today, tomorrow] = useMemo(() => {
const today = moment(timestamp).startOf('day')
return [today, today.clone().add(1, 'day')]
}, [timestamp])

const { locations, isLoading: locationsAreLoading } = useVehicleLocations({
from: +today.setHours(0, 0, 0, 0),
to: +tomorrow.setHours(0, 0, 0, 0),
from: today.valueOf(),
to: tomorrow.valueOf(),
lineRef,
splitMinutes: 360,
pause: !lineRef,
})

const positions = useMemo(() => {
const pos = locations.map<Point>((location) => ({
return locations.map<Point>((location) => ({
loc: [location.lat, location.lon],
color: location.velocity,
operator: location.siri_route__operator_ref,
bearing: location.bearing,
recorded_at_time: new Date(location.recorded_at_time).getTime(),
point: location,
}))

return pos
}, [locations])

function convertTo24HourAndToNumber(time: string): number {
const match = time.match(/(\d+):(\d+):(\d+)\s(AM|PM)/)
if (!match) return 0
const options = useMemo(() => {
const uniqueTimes = new Set<string>()

const [, hour, minute, , modifier] = match
let newHour = parseInt(hour, 10)
if (modifier === 'AM' && newHour === 12) newHour = 0
if (modifier === 'PM' && newHour !== 12) newHour += 12
for (const position of positions) {
const startTime = position.point?.siri_ride__scheduled_start_time
if (startTime) {
const momentTime = moment(startTime)
if (momentTime.isBetween(today, tomorrow)) {
uniqueTimes.add(formatTime(momentTime))
}
}
}

return newHour * 60 + parseInt(minute, 10)
}
return Array.from(uniqueTimes)
.sort()
.map((time) => ({ value: time, label: time }))
}, [positions, today, tomorrow])

const options = useMemo(() => {
const filteredPositions = positions.filter((position) => {
const startTime = position.point?.siri_ride__scheduled_start_time
return !!startTime && +new Date(startTime) > +today.setHours(0, 0, 0, 0)
// Set Bus Postions
useEffect(() => {
if (!startTime) {
setFilteredPositions([])
return
}

const filtered = positions.filter((position) => {
const scheduledTime = position.point?.siri_ride__scheduled_start_time
return scheduledTime && formatTime(moment(scheduledTime)) === startTime
})

if (filteredPositions.length === 0) return []

const uniqueTimes = Array.from(
new Set(
filteredPositions
.map((position) => position.point?.siri_ride__scheduled_start_time)
.filter((time): time is string => !!time)
.map((time) => time.trim()),
),
)
.map((time) => new Date(time).toLocaleTimeString()) // Convert to 24-hour time string
.map((time) => ({
value: time,
label: time,
}))

const sortedOptions = uniqueTimes.sort(
(a, b) => convertTo24HourAndToNumber(a.value) - convertTo24HourAndToNumber(b.value),
)

return sortedOptions
}, [positions])
setFilteredPositions(filtered)
}, [startTime, positions])

// Set Bus Planned Stop
useEffect(() => {
if (startTime !== '00:00:00' && positions.length > 0) {
setFilteredPositions(
positions.filter(
(position) =>
new Date(position.point?.siri_ride__scheduled_start_time ?? 0).toLocaleTimeString() ===
startTime,
),
)
}
if (startTime !== '00:00:00') {
const [hours, minutes] = startTime.split(':')
const startTimeTimestamp = +new Date(
positions[0].point?.siri_ride__scheduled_start_time ?? 0,
).setHours(+hours, +minutes, 0, 0)
handlePlannedRouteStops(routeIds ?? [], startTimeTimestamp)
const abortController = new AbortController()

if (routeIds?.length) {
const [hour, minute] = startTime ? startTime.split(':').map(Number) : [0, 0]
const startTimeTimestamp = today.clone().set({ hour, minute, second: 0, millisecond: 0 })

getStopsForRouteAsync(routeIds, startTimeTimestamp)
.then((stops) => {
if (!abortController.signal.aborted) {
setPlannedRouteStops(stops)
}
})
.catch(() => {
if (!abortController.signal.aborted) {
setPlannedRouteStops([])
}
})
} else {
setPlannedRouteStops([])
}
}, [startTime])

const handlePlannedRouteStops = async (routeIds: number[], startTimeTs: number) => {
const stops = await getStopsForRouteAsync(routeIds, moment(startTimeTs))
setPlannedRouteStops(stops)
}
return () => abortController.abort()
}, [startTime, today, routeIds])

return {
locationsAreLoading,
Expand Down
10 changes: 5 additions & 5 deletions src/pages/Map.scss
Original file line number Diff line number Diff line change
Expand Up @@ -52,20 +52,20 @@ main > div,
img {
width: 20px;
height: 20px;
}

}
}

&-title {
width: 100px;
text-align: left;
color: black;
}
}
}
}

.map-index.dark {
background-color: #303230;
}
.map-index.dark {
background-color: #303230;
}

pre {
Expand Down
4 changes: 2 additions & 2 deletions src/pages/components/FilterPositionsByStartTimeSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ type FilterPositionsByStartTimeSelectorProps = {
label: string
}[]
startTime?: string
setStartTime: (time: string) => void
setStartTime: (time?: string) => void
}

export function FilterPositionsByStartTimeSelector({
Expand All @@ -25,7 +25,7 @@ export function FilterPositionsByStartTimeSelector({
sx={{ width: '100%' }}
disablePortal
value={value}
onChange={(e, value) => setStartTime(value ? value.value : '0')}
onChange={(e, value) => setStartTime(value?.value)}
id="start-time-select"
options={options}
renderInput={(params) => <TextField {...params} label={t('choose_start_time')} />}
Expand Down
6 changes: 3 additions & 3 deletions src/pages/components/RouteSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import { formatted } from 'src/locale/utils'

type RouteSelectorProps = {
routes: BusRoute[]
routeKey: string | undefined
setRouteKey: (routeKey: string) => void
routeKey?: string
setRouteKey: (routeKey?: string) => void
}

const getRouteTitle = (route: BusRoute, t: TFunction<'translation', undefined>) =>
Expand Down Expand Up @@ -39,7 +39,7 @@ const RouteSelector = ({ routes, routeKey, setRouteKey }: RouteSelectorProps) =>
<Autocomplete
disablePortal
value={value}
onChange={(e, value) => setRouteKey(value ? value.key : '0')}
onChange={(e, value) => setRouteKey(value?.key)}
id="route-select"
options={routes}
renderInput={(params) => (
Expand Down
66 changes: 35 additions & 31 deletions src/pages/components/map-related/MapContent.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { t } from 'i18next'
import { useRef, useEffect, useState } from 'react'
import { useRef, useEffect, useState, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { Marker, Polyline, Popup, TileLayer, useMap } from 'react-leaflet'
import { Icon, IconOptions, Marker as LeafletMarker } from 'leaflet'
Expand All @@ -12,38 +12,32 @@ import { MapIndex } from './MapIndex'
import MapFooterButtons from './MapFooterButtons/MapFooterButtons'
import { useAgencyList } from 'src/api/agencyList'

// configs for planned & actual routes - line color & marker icon
const getIcon = (path: string, width: number = 10, height: number = 10): Icon<IconOptions> => {
return new Icon<IconOptions>({
iconUrl: path,
iconSize: [width, height],
})
}
const actualRouteStopMarkerPath = '/marker-dot.png'
const plannedRouteStopMarkerPath = '/marker-bus-stop.png'
const actualRouteLineColor = 'orange'
const plannedRouteLineColor = 'black'
const actualRouteStopMarker = getIcon(actualRouteStopMarkerPath, 20, 20)
const plannedRouteStopMarker = getIcon(plannedRouteStopMarkerPath, 20, 25)

export function MapContent({ positions, plannedRouteStops, showNavigationButtons }: MapProps) {
useRecenterOnDataChange({ positions, plannedRouteStops })
const markerRef = useRef<{ [key: number]: LeafletMarker | null }>({})
const map = useMap()
const [tileUrl, setTileUrl] = useState('https://tile-a.openstreetmap.fr/hot/{z}/{x}/{y}.png')

const agencyList = useAgencyList()
const getIcon = (path: string, width: number = 10, height: number = 10): Icon<IconOptions> => {
return new Icon<IconOptions>({
iconUrl: path,
iconSize: [width, height],
})
}
// configs for planned & actual routes - line color & marker icon
const actualRouteStopMarkerPath = '/marker-dot.png'
const plannedRouteStopMarkerPath = '/marker-bus-stop.png'
const actualRouteLineColor = 'orange'
const plannedRouteLineColor = 'black'
const actualRouteStopMarker = getIcon(actualRouteStopMarkerPath, 20, 20)
const plannedRouteStopMarker = getIcon(plannedRouteStopMarkerPath, 20, 25)
const navigateMarkers = (positionId: number) => {
const loc = positions[positionId]?.loc
if (!map || !loc) return
const marker = markerRef?.current && markerRef?.current[positionId]
if (marker) {
map.flyTo(loc, map.getZoom())
marker.openPopup()
}
}
const map = useMap()
const { i18n } = useTranslation()
const [tileUrl, setTileUrl] = useState('https://tile-a.openstreetmap.fr/hot/{z}/{x}/{y}.png')

useRecenterOnDataChange({ positions, plannedRouteStops })

useEffect(() => {
const handleLanguageChange = (lng: string) => {
console.log('Language changed to:', lng)
const newUrl =
lng === 'he'
? 'https://tile-a.openstreetmap.fr/hot/{z}/{x}/{y}.png'
Expand All @@ -56,6 +50,19 @@ export function MapContent({ positions, plannedRouteStops, showNavigationButtons
}
}, [])

const navigateMarkers = useCallback(
(positionId: number) => {
const pos = positions[positionId]
if (!map || !pos?.loc) return
const marker = markerRef.current[positionId]
if (marker) {
map.flyTo(pos.loc, map.getZoom())
marker.openPopup()
}
},
[map, positions],
)

return (
<>
<TileLayer
Expand Down Expand Up @@ -117,10 +124,7 @@ export function MapContent({ positions, plannedRouteStops, showNavigationButtons
plannedRouteStops.map((stop) => {
const { latitude, longitude } = stop.location
return (
<Marker
key={'' + latitude + longitude}
position={[latitude, longitude]}
icon={plannedRouteStopMarker}></Marker>
<Marker key={stop.key} position={[latitude, longitude]} icon={plannedRouteStopMarker} />
)
})}
{positions.length && (
Expand Down
39 changes: 28 additions & 11 deletions src/pages/components/map-related/useRecenterOnDataChange.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,36 @@
import { useEffect } from 'react'
import { useEffect, useMemo } from 'react'
import { LatLngTuple } from 'leaflet'
import { useMap } from 'react-leaflet'
import { MapProps } from './map-types'

export function useRecenterOnDataChange({ positions }: MapProps) {
export function useRecenterOnDataChange({ positions, plannedRouteStops }: MapProps) {
const map = useMap()
const positionsSum = positions.reduce(
(acc, { loc }) => [acc[0] + loc[0], acc[1] + loc[1]],
[0, 0],
)
const mean: LatLngTuple = [positionsSum[0] / positions.length, positionsSum[1] / positions.length]
console.log('mean: ', mean)

const center = useMemo(() => {
const sum: LatLngTuple = [0, 0]
const totalPoints = positions.length + plannedRouteStops.length

if (totalPoints === 0) return sum

for (const position of positions) {
sum[0] += position.loc[0]
sum[1] += position.loc[1]
}

for (const stop of plannedRouteStops) {
sum[0] += stop.location.latitude
sum[1] += stop.location.longitude
}

sum[0] /= totalPoints
sum[1] /= totalPoints

return sum
}, [positions, plannedRouteStops])

useEffect(() => {
if (mean[0] || mean[1]) {
map.setView(mean, map.getZoom(), { animate: true })
if (center[0] || center[1]) {
map.setView(center, map.getZoom(), { animate: true })
}
}, [mean])
}, [...center, map])
}
Loading
Loading