-
Notifications
You must be signed in to change notification settings - Fork 0
/
trimet_trip_game_reset.html
464 lines (379 loc) · 15.4 KB
/
trimet_trip_game_reset.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Portland Polygons Map</title>
<style>
#map { height: 600px; }
#coordinates { margin-top: 10px; }
/* body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
} */
#buttons {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
button {
font-size: 18px;
padding: 10px 20px;
cursor: pointer;
}
#message {
font-size: 18px;
font-weight: bold;
}
.disabled {
opacity: 0.5;
cursor: not-allowed;
}
</style>
</head>
<body>
<div id="map"></div>
<button id="selectRandomPolygons">Select Two Random Polygons and Create Points</button>
<div id="coordinates"></div>
<div id="buttons"></div>
<div id="message"></div>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI="
crossorigin=""/>
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"
integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM="
crossorigin=""></script>
<script type="text/javascript" src="https://rawgit.com/jieter/Leaflet.encoded/master/Polyline.encoded.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Turf.js/6.5.0/turf.min.js"></script>
<script>
// look up stops near the origin and end of each leg for the next guess list
// https://developer.trimet.org/ws/v1/stops?json=true&appId=8CBD14D520C6026CC7EEE56A9&showRoutes=true&meters=1609&ll=45.51704561447618,-122.65432834625246
let attemptsLeft = 2;
function createButtons(numbers, correctAnswer) {
const buttonsContainer = document.getElementById('buttons');
numbers.forEach(number => {
const button = document.createElement('button');
button.textContent = number;
button.addEventListener('click', () => checkAnswer(number, button, correctAnswer));
buttonsContainer.appendChild(button);
});
}
function checkAnswer(number, button, correctAnswer) {
if (attemptsLeft > 0) {
const messageElement = document.getElementById('message');
if (number === correctAnswer) {
button.style.backgroundColor = 'green';
messageElement.textContent = "Congratulations, that's correct!";
disableAllButtons();
} else {
button.style.backgroundColor = 'gray';
attemptsLeft--;
if (attemptsLeft > 0) {
messageElement.textContent = `Sorry, that's incorrect. You have ${attemptsLeft} attempt left.`;
} else {
messageElement.textContent = `Sorry, that's incorrect. The correct answer was ${correctAnswer}.`;
revealCorrectAnswer();
}
}
button.disabled = true;
}
}
function disableAllButtons() {
const buttons = document.querySelectorAll('button');
buttons.forEach(button => {
if (button.textContent != correctAnswer) {
button.disabled = true;
button.classList.add('disabled');
}
});
}
function revealCorrectAnswer() {
const buttons = document.querySelectorAll('button');
buttons.forEach(button => {
if (button.textContent == correctAnswer) {
button.style.backgroundColor = 'green';
} else {
button.disabled = true;
button.classList.add('disabled');
}
});
}
function parseNearRoutes(response) {
allRoutes = [];
response.resultSet.location.forEach((location, index) => {
// console.log("one location");
// console.log(location);
const routes = location.route;
routes.forEach((route, index) => {
oneRoute = route.route;
// console.log("oneRoute");
// console.log(oneRoute);
allRoutes.push(oneRoute);
});
});
console.log("allRoutes");
console.log(allRoutes);
uniqRoutes = [...new Set(allRoutes)]
return uniqRoutes
}
function makeSynchronousAPICall(url, params) {
const xhr = new XMLHttpRequest();
xhr.open('GET', buildURLWithParams(url, params), false); // false for synchronous
xhr.send();
if (xhr.status === 200) {
return JSON.parse(xhr.responseText);
} else {
throw new Error('API call failed with status ' + xhr.status);
}
}
function buildURLWithParams(url, params) {
const queryParams = new URLSearchParams(params);
return `${url}?${queryParams.toString()}`;
}
function getColorForMode(mode) {
if (mode==="WALK") {
// block of code to be executed if condition1 is true
lineColor="#CECECE";
} else if (mode==="BUS") {
// block of code to be executed if the condition1 is false and condition2 is true
lineColor="#FE9900";
} else if (mode==="TRAM") {
// block of code to be executed if the condition1 is false and condition2 is true
lineColor="#CC6CE7";
} else {
// block of code to be executed if the condition1 is false and condition2 is false
lineColor="#000000";
}
return lineColor;
}
;
// Assuming 'response' is your JSON response from the API
function parseItineraryLegs(response, itineraryGroup) {
itineraryGroup.clearLayers();
// Iterate through all itineraries
response.plan.itineraries.forEach((itinerary, index) => {
// Iterate through legs of each itinerary
console.log("we made it here");
console.log(itinerary);
nonWalkLegIds = [];
itinerary.legs.forEach(leg => {
const mode = leg.mode;
const geometry = leg.legGeometry.points;
const polylineOptions = {
color: getColorForMode(mode),
route: leg.route,
weight: 2,
opacity: 1
};
const polyline = L.Polyline.fromEncoded(geometry, polylineOptions);
if (leg.mode != 'WALK') {
itineraryGroup.addLayer(polyline);
}
else {
}
});
});
// map.fitBounds(itineraryGroup.getBounds());
itineraryGroup.addTo(map);
}
// Assuming 'response' is your JSON response from the API
function parseItineraryRoutes(response) {
// Iterate through all itineraries
response.plan.itineraries.forEach((itinerary, index) => {
nonWalkRoutes = [];
itinerary.legs.forEach(leg => {
if (leg.mode != 'WALK') {
nonWalkRoutes.push(Number(leg.route));
}
else {
}
});
});
console.log("nonWalkRoutes inside parseItineraryRoutes");
console.log(nonWalkRoutes);
return nonWalkRoutes
}
// Initialize the map
const map = L.map('map').setView([45.5231, -122.6765], 11); // Portland coordinates
// Add OpenStreetMap tile layer
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
const geojsonUrl = 'https://meysohn-sandbox.s3.amazonaws.com/trimet_trip_planner/tm_route_buffer_blockgroup.geojson';
let geojsonLayer;
let polygons = [];
let randomPointsLayer;
let originPoint, destinationPoint;
const itineraryGroup = L.layerGroup();
itineraryGroup.addTo(map);
// Function to load GeoJSON from S3
function loadGeoJSONFromS3() {
fetch(geojsonUrl)
.then(response => response.json())
.then(data => {
geojsonLayer = L.geoJSON(data, {
style: {
fillColor: 'white',
weight: 2,
opacity: 0,
color: '#3388ff',
fillOpacity: 0
}
}).addTo(map);
// Store all polygons for later use
geojsonLayer.eachLayer(layer => {
if (layer instanceof L.Polygon) {
polygons.push(layer);
}
});
// Fit the map to the GeoJSON bounds
map.fitBounds(geojsonLayer.getBounds());
})
.catch(error => {
console.error("Error loading GeoJSON:", error);
});
}
// Function to create a random point within a polygon
function createRandomPointInPolygon(polygon) {
const bounds = polygon.getBounds();
let point;
do {
const lat = bounds.getSouth() + Math.random() * (bounds.getNorth() - bounds.getSouth());
const lng = bounds.getWest() + Math.random() * (bounds.getEast() - bounds.getWest());
point = turf.point([lng, lat]);
} while (!turf.booleanPointInPolygon(point, polygon.toGeoJSON()));
return point;
}
// Function to select two random polygons and create labeled points
function selectRandomPolygonsAndCreatePoints() {
// Remove previous random points if any
if (randomPointsLayer) {
map.removeLayer(randomPointsLayer);
}
// Reset previously selected polygons
geojsonLayer.resetStyle();
if (polygons.length < 2) {
console.error("Not enough polygons to select from");
return;
}
// Select two unique random indices
const indices = [];
while (indices.length < 2) {
const index = Math.floor(Math.random() * polygons.length);
if (!indices.includes(index)) {
indices.push(index);
}
}
const randomPoints = [];
// Highlight selected polygons and create random points
indices.forEach((index, i) => {
const polygon = polygons[index];
polygon.setStyle({
fillColor: 'red',
fillOpacity: 0.9
});
polygon.bringToFront();
// Create a random point within the polygon
const randomPoint = createRandomPointInPolygon(polygon);
randomPoint.properties = {
label: i === 0 ? "Origin" : "Destination"
};
randomPoints.push(randomPoint);
// Store the point for later access
if (i === 0) {
originPoint = randomPoint;
} else {
destinationPoint = randomPoint;
}
});
// Add random points to the map
randomPointsLayer = L.geoJSON(turf.featureCollection(randomPoints), {
pointToLayer: (feature, latlng) => {
const marker = L.circleMarker(latlng, {
radius: 8,
fillColor: feature.properties.label === "Origin" ? "#00ff00" : "#ff0000",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
});
// Add a popup with the label
marker.bindPopup(feature.properties.label, {
closeButton: false,
offset: L.point(0, -4)
});
// Open the popup immediately
marker.openPopup();
return marker;
}
}).addTo(map);
// Display coordinates
displayCoordinates();
}
// Function to display coordinates
function displayCoordinates() {
const coordinatesDiv = document.getElementById('coordinates');
if (originPoint && destinationPoint) {
const originCoords = originPoint.geometry.coordinates;
const destCoords = destinationPoint.geometry.coordinates;
coordinatesDiv.innerHTML = `
<strong>Origin:</strong> [${originCoords[1].toFixed(6)}, ${originCoords[0].toFixed(6)}]<br>
<strong>Destination:</strong> [${destCoords[1].toFixed(6)}, ${destCoords[0].toFixed(6)}]
`;
//
const apiUrl = 'https://maps.trimet.org/otp_mod/plan';
const parameters = {
fromPlace: `'${originCoords[1].toFixed(6)}, ${originCoords[0].toFixed(6)}'`,
toPlace: `'${destCoords[1].toFixed(6)}, ${destCoords[0].toFixed(6)}'`,
date: '2024-09-17',
time: '14:20',
mode: 'WALK,BUS,TRAM,RAIL,GONDOLA',
maxWalkDistance:805, //805 meters ~ 1/2 mile
walkSpeed: 1.34,
numItineraries: 2,
otherThanPreferredRoutesPenalty: 900
};
// https://developer.trimet.org/ws/v1/stops?json=true&appId=8CBD14D520C6026CC7EEE56A9&showRoutes=true&meters=1609&ll=45.51704561447618,-122.65432834625246
const apiUrl2 = 'https://developer.trimet.org/ws/v1/stops';
const parameters2 = {
ll: `${originCoords[1].toFixed(6)},${originCoords[0].toFixed(6)}`,
meters: 1609,
json: true,
appId: '8CBD14D520C6026CC7EEE56A9',
showRoutes:true
};
apiResponse = makeSynchronousAPICall(apiUrl, parameters);
console.log("test sync api response");
console.log(apiResponse);
parseItineraryLegs(apiResponse, itineraryGroup);
nonWalkRoutes = parseItineraryRoutes(apiResponse);
console.log("nonWalkRoutes outside parseItineraryRoutes");
console.log(nonWalkRoutes);
apiResponse2 = makeSynchronousAPICall(apiUrl2, parameters2);
console.log("test sync api response 2");
console.log(apiResponse2);
parsedRoutes = parseNearRoutes(apiResponse2);
console.log("parsedRoutes put into createButtons");
console.log(parsedRoutes);
createButtons(parsedRoutes, nonWalkRoutes[0]);
} else {
coordinatesDiv.innerHTML = "Points not yet created";
}
}
// Load GeoJSON when the page loads
loadGeoJSONFromS3();
// Add click event listener to the button
document.getElementById('selectRandomPolygons').addEventListener('click', selectRandomPolygonsAndCreatePoints);
// Access origin coordinates
const originLat = originPoint.geometry.coordinates[1];
const originLng = originPoint.geometry.coordinates[0];
// Access destination coordinates
const destLat = destinationPoint.geometry.coordinates[1];
const destLng = destinationPoint.geometry.coordinates[0];
</script>
</body>
</html>