-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectRoute.js
More file actions
221 lines (208 loc) · 7.29 KB
/
SelectRoute.js
File metadata and controls
221 lines (208 loc) · 7.29 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
import React, { useEffect, useState } from 'react';
import { View, Text, TouchableOpacity, Platform } from 'react-native';
import MapView, { Polyline, Marker } from 'react-native-maps';
import {
decodeRoute,
getCurrentLocation,
startLocationTracking,
} from './utils/mapUtils';
import locationCircleIcon from './assets/location-circle.png';
import selectRouteStyles from './components/styles/SelectRoute.styles';
import { retrieveData } from './caching';
export default function SelectRouteScreen({ navigation, route }) {
const { origin, destination, routeData } = route.params;
const [routes, setRoutes] = useState([]);
const [location, setLocation] = useState(null);
const [errorMessage, setErrorMessage] = useState('');
const [polylineCoordinates, setPolylineCoordinates] = useState([]);
const [currentRoute, setCurrentRoute] = useState(routeData.routes[0]);
const [scores, setScores] = useState([]);
// Get current location
useEffect(() => {
(async () => {
try {
const initialLocation = await getCurrentLocation();
setLocation(initialLocation);
const locationSubscription = await startLocationTracking(setLocation);
return () => locationSubscription.remove();
} catch (error) {
setErrorMessage(error.message);
return null;
}
})();
}, [location]);
// Generate polyline
// Decode and set polyline coordinates
useEffect(() => {
if (routeData && routeData.routes && routeData.routes.length > 0) {
const encodedPolyline = currentRoute.overview_polyline.points;
const decodedPath = decodeRoute(encodedPolyline); // Decode into lat/lng pairs
setPolylineCoordinates(decodedPath);
setRoutes(routeData.routes); // Set the routes state
}
}, [currentRoute.overview_polyline.points, routeData]);
// Display all route options
const displaySelectedRoute = (index) => {
const selectedRoute = routeData.routes[index];
setCurrentRoute(selectedRoute);
const encodedPolyline = selectedRoute.overview_polyline.points;
const decodedPath = decodeRoute(encodedPolyline); // Decode into lat/lng pairs
setPolylineCoordinates(decodedPath);
};
const sendSustainabilityScore = async (
startRouteFlag,
sustainabilityScore,
sustainabilityUsername,
// eslint-disable-next-line consistent-return
) => {
try {
const baseUrl =
Platform.OS === 'web'
? 'http://localhost'
: process.env.EXPO_PUBLIC_API_URL;
console.log(`Sending request to ${baseUrl}/update_sus_stats`);
const response = await fetch(`${baseUrl}/update_sus_stats`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: sustainabilityUsername,
flag: startRouteFlag,
modeDistances: sustainabilityScore,
}),
});
const data = await response.json();
console.log('response (transport score): ', data);
return data;
} catch (error) {
console.log('Error sending sustainability scores and distances:', error);
}
};
const getSustainabilityScore = async (index, startRouteFlag, sustainabilityUsername) => {
const sustainabilityScore = {
Bus: 0,
Train: 0,
WALKING: 0,
Tram: 0,
DRIVING: 0,
BICYCLING: 0,
};
routeData.routes[index].legs[0].steps.forEach((step) => {
let key = '';
if (step.travel_mode === 'TRANSIT') {
// eslint-disable-next-line prefer-destructuring
key = step.html_instructions.trim().split(' ')[0];
console.log('key: ', key);
} else {
key = step.travel_mode;
}
sustainabilityScore[key] += step.distance.value / 1000;
});
console.log('sustainability score: ', sustainabilityScore);
const transportScore = await sendSustainabilityScore(
startRouteFlag,
sustainabilityScore,
sustainabilityUsername,
);
return transportScore;
};
useEffect(() => {
for (let i = 0; i < routeData.routes.length; i += 1) {
setScores((prevScores) => [
...prevScores,
getSustainabilityScore(i, false, '')
]);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const startJourney = async (index, routeOption) => {
const sustainabilityUsername = await retrieveData('username');
if (sustainabilityUsername != null) {
getSustainabilityScore(index, true, sustainabilityUsername);
}
navigation.navigate('DisplayRouteScreen', {
origin,
destination,
routeData: routeOption,
polylineCoordinates,
});
};
return (
<View style={selectRouteStyles.container}>
{errorMessage && (
<Text style={selectRouteStyles.error}>{errorMessage}</Text>
)}
{!errorMessage && location && (
<>
<MapView
style={selectRouteStyles.map}
initialRegion={{
latitude:
routes.length > 0
? routes[0].legs[0].start_location.lat
: location.latitude,
longitude:
routes.length > 0
? routes[0].legs[0].start_location.lng
: location.longitude,
latitudeDelta: 0.01,
longitudeDelta: 0.01,
}}
>
<Marker
coordinate={location}
title="Your Location"
description="Real-time location"
icon={locationCircleIcon}
/>
{polylineCoordinates.length > 0 && (
<Marker
coordinate={polylineCoordinates[polylineCoordinates.length - 1]}
title="Destination"
description="Destination of the route"
/>
)}
{polylineCoordinates.length > 0 && (
<Polyline
coordinates={polylineCoordinates}
strokeColor="#1063D5"
strokeWidth={4}
/>
)}
</MapView>
<View>
{routes.map((routeOption, index) => (
<View
key={index} // eslint-disable-line react/no-array-index-key
style={selectRouteStyles.routeContainer}
>
<TouchableOpacity
onPress={() => displaySelectedRoute(index)}
style={selectRouteStyles.routeButton}
>
<Text>Route {index + 1}</Text>
<Text>Distance: {routeOption.legs[0].distance.text}</Text>
<Text>Duration: {routeOption.legs[0].duration.text}</Text>
<Text>Sustainability score: {scores[index]}</Text>
</TouchableOpacity>
{/* routeData needs to rename the route variable because that is what react navigator calls its properties */}
<TouchableOpacity
onPress={() => {
startJourney(index, routeOption);
}}
style={selectRouteStyles.startButton}
>
<Text>Start Journey</Text>
</TouchableOpacity>
</View>
))}
</View>
</>
)}
{!errorMessage && !location && (
<Text style={selectRouteStyles.loadingText}>Loading...</Text>
)}
</View>
);
}