forked from valhalla/web-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-directions-queries.ts
More file actions
244 lines (218 loc) · 6.54 KB
/
use-directions-queries.ts
File metadata and controls
244 lines (218 loc) · 6.54 KB
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
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
import { toast } from 'sonner';
import type {
ActiveWaypoint,
ParsedDirectionsGeometry,
ValhallaRouteResponse,
} from '@/components/types';
import {
getValhallaUrl,
buildDirectionsRequest,
parseDirectionsGeometry,
} from '@/utils/valhalla';
import {
reverse_geocode,
forward_geocode,
parseGeocodeResponse,
} from '@/utils/nominatim';
import { filterProfileSettings } from '@/utils/filter-profile-settings';
import { getDirectionsLanguage } from '@/utils/directions-language';
import { useCommonStore } from '@/stores/common-store';
import { useDirectionsStore, type Waypoint } from '@/stores/directions-store';
import { router } from '@/routes';
const getActiveWaypoints = (waypoints: Waypoint[]): ActiveWaypoint[] =>
waypoints.flatMap((wp) => wp.geocodeResults.filter((r) => r.selected));
async function fetchDirections() {
const waypoints = useDirectionsStore.getState().waypoints;
const profile = router.state.location.search.profile;
const { dateTime, settings: rawSettings } = useCommonStore.getState();
const activeWaypoints = getActiveWaypoints(waypoints);
if (activeWaypoints.length < 2) {
return null;
}
const settings = filterProfileSettings(profile || 'bicycle', rawSettings);
const language = getDirectionsLanguage();
const valhallaRequest = buildDirectionsRequest({
profile: profile || 'bicycle',
activeWaypoints,
// @ts-expect-error todo: initial settings and filtered settings types mismatch
settings,
dateTime,
language,
});
const { data } = await axios.get<ValhallaRouteResponse>(
getValhallaUrl() + '/route',
{
params: { json: JSON.stringify(valhallaRequest.json) },
headers: { 'Content-Type': 'application/json' },
}
);
// Parse geometry for main route
(data as ParsedDirectionsGeometry).decodedGeometry =
parseDirectionsGeometry(data);
// Parse geometry for alternates
data.alternates?.forEach((alternate, i) => {
if (alternate) {
(data.alternates![i] as ParsedDirectionsGeometry).decodedGeometry =
parseDirectionsGeometry(alternate);
}
});
return data as ParsedDirectionsGeometry;
}
export function useDirectionsQuery() {
const showLoading = useCommonStore((state) => state.showLoading);
const zoomTo = useCommonStore((state) => state.zoomTo);
const receiveRouteResults = useDirectionsStore(
(state) => state.receiveRouteResults
);
const clearRoutes = useDirectionsStore((state) => state.clearRoutes);
return useQuery({
queryKey: ['directions'],
queryFn: async () => {
showLoading(true);
try {
const data = await fetchDirections();
if (data) {
receiveRouteResults({ data });
zoomTo(data.decodedGeometry);
}
return data;
} catch (error) {
clearRoutes();
if (axios.isAxiosError(error) && error.response) {
const response = error.response;
let error_msg = response.data.error;
if (response.data.error_code === 154) {
error_msg += ` for route.`;
}
toast.warning(`${response.data.status}`, {
description: `${error_msg}`,
position: 'bottom-center',
duration: 5000,
closeButton: true,
});
}
throw error;
} finally {
setTimeout(() => showLoading(false), 500);
}
},
enabled: false,
retry: false,
});
}
async function fetchReverseGeocode(lng: number, lat: number) {
const response = await reverse_geocode(lng, lat);
const addresses = parseGeocodeResponse(response.data, [lng, lat]);
if (addresses.length === 0) {
toast.warning('No addresses', {
description: 'Sorry, no addresses can be found.',
position: 'bottom-center',
duration: 5000,
closeButton: true,
});
}
return addresses as ActiveWaypoint[];
}
export function useReverseGeocodeDirections() {
const receiveGeocodeResults = useDirectionsStore(
(state) => state.receiveGeocodeResults
);
const updateTextInput = useDirectionsStore((state) => state.updateTextInput);
const addEmptyWaypointToEnd = useDirectionsStore(
(state) => state.addEmptyWaypointToEnd
);
const updatePlaceholderAddressAtIndex = useDirectionsStore(
(state) => state.updatePlaceholderAddressAtIndex
);
const reverseGeocode = async (
lng: number,
lat: number,
index: number,
options?: { isPermalink?: boolean }
) => {
// For permalink loading, add waypoint if needed
if (options?.isPermalink) {
const currentLen = useDirectionsStore.getState().waypoints.length;
if (index >= currentLen) {
const toAdd = index - currentLen + 1;
for (let i = 0; i < toAdd; i++)
{
addEmptyWaypointToEnd();
}
}
}
// Set placeholder immediately
updatePlaceholderAddressAtIndex(index, lng, lat);
try {
const addresses = await fetchReverseGeocode(lng, lat);
receiveGeocodeResults({
addresses,
index,
});
updateTextInput({
inputValue: addresses[0]?.title || '',
index,
addressindex: 0,
});
return addresses;
} catch (error) {
console.error('Reverse geocode error:', error);
throw error;
}
};
return { reverseGeocode };
}
async function fetchForwardGeocode(
userInput: string,
lngLat?: [number, number]
): Promise<ActiveWaypoint[]> {
if (lngLat) {
return [
{
title: lngLat.toString(),
key: 0,
selected: false,
addresslnglat: lngLat,
sourcelnglat: lngLat,
displaylnglat: lngLat,
addressindex: 0,
},
];
}
const response = await forward_geocode(userInput);
const addresses = parseGeocodeResponse(response.data);
if (addresses.length === 0) {
toast.warning('No addresses', {
description: 'Sorry, no addresses can be found.',
position: 'bottom-center',
duration: 5000,
closeButton: true,
});
}
return addresses as ActiveWaypoint[];
}
export function useForwardGeocodeDirections() {
const receiveGeocodeResults = useDirectionsStore(
(state) => state.receiveGeocodeResults
);
const forwardGeocode = async (
userInput: string,
index: number,
lngLat?: [number, number]
) => {
try {
const addresses = await fetchForwardGeocode(userInput, lngLat);
receiveGeocodeResults({
addresses,
index,
});
return addresses;
} catch (error) {
console.error('Forward geocode error:', error);
throw error;
}
};
return { forwardGeocode };
}