-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
375 lines (321 loc) · 10.2 KB
/
Copy pathscript.js
File metadata and controls
375 lines (321 loc) · 10.2 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
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
// Initialize map
let map
let currentLayer = "street"
let trafficVisible = true
const trafficMarkers = []
let routeLayer
let chart
function checkLibraries() {
const leafletLoaded = typeof window.L !== "undefined" && window.L.map
const chartLoaded = typeof window.Chart !== "undefined"
console.log("[v0] Leaflet loaded:", leafletLoaded)
console.log("[v0] Chart.js loaded:", chartLoaded)
return { leafletLoaded, chartLoaded }
}
// Map initialization with improved error handling
function initMap() {
console.log("[v0] Starting map initialization...")
const { leafletLoaded } = checkLibraries()
if (!leafletLoaded) {
console.error("[v0] Leaflet library not available yet, retrying...")
setTimeout(initMap, 500)
return
}
const mapContainer = document.getElementById("traffic-map")
if (!mapContainer) {
console.error("[v0] Map container #traffic-map not found!")
return
}
console.log("[v0] Map container found:", mapContainer)
console.log("[v0] Container size:", mapContainer.offsetWidth, "x", mapContainer.offsetHeight)
try {
// Clear any existing map
if (map) {
map.remove()
}
const L = window.L
map = L.map("traffic-map", {
center: [40.7128, -74.006],
zoom: 13,
zoomControl: true,
attributionControl: true,
})
console.log("[v0] Map initialized successfully")
console.log("[v0] Map view:", map.getCenter(), "Zoom:", map.getZoom())
// Street layer
const streetLayer = L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: "© OpenStreetMap contributors",
maxZoom: 19,
detectRetina: true,
})
// Satellite layer
const satelliteLayer = L.tileLayer(
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
{
attribution: "Tiles © Esri",
maxZoom: 18,
detectRetina: true,
},
)
streetLayer.addTo(map)
console.log("[v0] Street layer added")
// Store layers for switching
map.streetLayer = streetLayer
map.satelliteLayer = satelliteLayer
// Add traffic events
addTrafficEvents()
// Update traffic events every 5 seconds
setInterval(updateTrafficEvents, 5000)
// Initialize chart
initChart()
// Update metrics
updateMetrics()
console.log("[v0] Map initialization complete")
} catch (error) {
console.error("[v0] Error during map initialization:", error.message)
console.error("[v0] Stack:", error.stack)
}
}
// Add traffic events to map
function addTrafficEvents() {
console.log("[v0] Adding traffic events...")
const events = [
{ lat: 40.758, lng: -73.9855, type: "Accident", severity: "high", description: "Multi-vehicle collision" },
{ lat: 40.7489, lng: -73.968, type: "Construction", severity: "medium", description: "Road work in progress" },
{ lat: 40.7614, lng: -73.9776, type: "Congestion", severity: "medium", description: "Heavy traffic" },
{ lat: 40.7505, lng: -73.9972, type: "Incident", severity: "low", description: "Minor incident" },
{ lat: 40.7282, lng: -73.7949, type: "Delay", severity: "low", description: "Traffic delay" },
]
const L = window.L
events.forEach((event) => {
const color = event.severity === "high" ? "#ff4757" : event.severity === "medium" ? "#ffa500" : "#00d084"
const marker = L.circleMarker([event.lat, event.lng], {
radius: 8,
fillColor: color,
color: color,
weight: 2,
opacity: 0.8,
fillOpacity: 0.7,
}).addTo(map)
marker.bindPopup(`<strong>${event.type}</strong><br>${event.description}`)
trafficMarkers.push({ marker, event })
})
console.log("[v0] Traffic events added:", events.length)
}
// Update traffic events
function updateTrafficEvents() {
const feedContent = document.getElementById("trafficEvents")
if (!feedContent) return
const events = [
{ type: "Accident", severity: "high", description: "Multi-vehicle collision on 5th Ave", time: "now" },
{ type: "Construction", severity: "medium", description: "Road work on Broadway", time: "2 min ago" },
{ type: "Congestion", severity: "medium", description: "Heavy traffic on Park Ave", time: "5 min ago" },
{ type: "Incident", severity: "low", description: "Minor incident on 3rd Ave", time: "10 min ago" },
]
feedContent.innerHTML = events
.map(
(event) => `
<div class="traffic-event">
<div class="event-header">
<span class="event-type">${event.type}</span>
<span class="event-time">${event.time}</span>
</div>
<p>${event.description}</p>
<span class="event-severity severity-${event.severity}">${event.severity.toUpperCase()}</span>
</div>
`,
)
.join("")
}
// Switch map layer
function switchLayer(layer) {
console.log("[v0] Switching to layer:", layer)
if (!map) {
console.error("[v0] Map not initialized")
return
}
currentLayer = layer
const L = window.L
if (layer === "street") {
map.removeLayer(map.satelliteLayer)
map.addLayer(map.streetLayer)
} else if (layer === "satellite") {
map.removeLayer(map.streetLayer)
map.addLayer(map.satelliteLayer)
}
// Update button states
document.querySelectorAll(".layer-btn").forEach((btn) => btn.classList.remove("active"))
document.querySelectorAll(".layer-btn")[layer === "street" ? 0 : 1].classList.add("active")
}
// Toggle traffic visibility
function toggleTraffic() {
trafficVisible = !trafficVisible
console.log("[v0] Traffic visibility toggled:", trafficVisible)
trafficMarkers.forEach(({ marker }) => {
if (trafficVisible) {
map.addLayer(marker)
} else {
map.removeLayer(marker)
}
})
}
// Zoom controls
function zoomIn() {
if (map) map.zoomIn()
}
function zoomOut() {
if (map) map.zoomOut()
}
// Get route
function getRoute() {
const source = document.getElementById("source").value
const destination = document.getElementById("destination").value
if (!source || !destination) {
alert("Please enter both source and destination")
return
}
if (!map) {
console.error("[v0] Map not initialized")
return
}
console.log("[v0] Getting route from", source, "to", destination)
// Simulate route
const routeCoords = [
[40.7128, -74.006],
[40.758, -73.9855],
[40.7614, -73.9776],
]
if (routeLayer) {
map.removeLayer(routeLayer)
}
const L = window.L
routeLayer = L.polyline(routeCoords, {
color: "#00d4ff",
weight: 3,
opacity: 0.8,
dashArray: "5, 5",
}).addTo(map)
map.fitBounds(routeLayer.getBounds())
}
// Initialize chart
function initChart() {
console.log("[v0] Initializing chart...")
const ctx = document.getElementById("predictionChart")
if (!ctx) {
console.warn("[v0] Chart canvas not found")
return
}
const { chartLoaded } = checkLibraries()
if (!chartLoaded) {
console.error("[v0] Chart.js not loaded")
return
}
const Chart = window.Chart
const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`)
const actualData = Array.from({ length: 24 }, () => Math.floor(Math.random() * 100) + 20)
const predictedData = Array.from({ length: 24 }, () => Math.floor(Math.random() * 100) + 20)
chart = new Chart(ctx, {
type: "line",
data: {
labels: hours,
datasets: [
{
label: "Actual Traffic",
data: actualData,
borderColor: "#ff6b35",
backgroundColor: "rgba(255, 107, 53, 0.1)",
tension: 0.4,
fill: true,
},
{
label: "AI Prediction",
data: predictedData,
borderColor: "#00d4ff",
backgroundColor: "rgba(0, 212, 255, 0.1)",
tension: 0.4,
fill: true,
},
],
},
options: {
responsive: true,
maintainAspectRatio: true,
plugins: {
legend: {
labels: {
color: "#f5f5f5",
},
},
},
scales: {
y: {
ticks: { color: "#f5f5f5" },
grid: { color: "rgba(255, 255, 255, 0.1)" },
},
x: {
ticks: { color: "#f5f5f5" },
grid: { color: "rgba(255, 255, 255, 0.1)" },
},
},
},
})
console.log("[v0] Chart initialized successfully")
}
// Update metrics
function updateMetrics() {
document.getElementById("avgDelay").textContent = Math.floor(Math.random() * 30) + 10 + " min"
document.getElementById("congestionLevel").textContent = Math.floor(Math.random() * 100) + "%"
document.getElementById("activeIncidents").textContent = Math.floor(Math.random() * 10) + 3
document.getElementById("optimalRoutes").textContent = Math.floor(Math.random() * 5) + 2
// Add predictions
const predictionsList = document.getElementById("predictionsList")
if (predictionsList) {
const predictions = [
{ time: "12:00 PM", value: "45 min" },
{ time: "1:00 PM", value: "52 min" },
{ time: "2:00 PM", value: "38 min" },
{ time: "3:00 PM", value: "65 min" },
{ time: "4:00 PM", value: "78 min" },
]
predictionsList.innerHTML = predictions
.map(
(p) => `
<div class="prediction-item">
<span class="prediction-time">${p.time}</span>
<span class="prediction-value">${p.value}</span>
</div>
`,
)
.join("")
}
}
document.addEventListener("DOMContentLoaded", () => {
console.log("[v0] DOM loaded")
// Wait for libraries to load
let attempts = 0
const maxAttempts = 20
function waitForLibraries() {
const { leafletLoaded, chartLoaded } = checkLibraries()
if (leafletLoaded && chartLoaded) {
console.log("[v0] All libraries loaded, initializing app...")
initMap()
updateTrafficEvents()
} else if (attempts < maxAttempts) {
attempts++
setTimeout(waitForLibraries, 250)
} else {
console.error("[v0] Libraries failed to load after", maxAttempts * 250, "ms")
}
}
waitForLibraries()
// Smooth scrolling for navigation links
document.querySelectorAll('a[href^="#"]').forEach((anchor) => {
anchor.addEventListener("click", function (e) {
e.preventDefault()
const target = document.querySelector(this.getAttribute("href"))
if (target) {
target.scrollIntoView({ behavior: "smooth" })
}
})
})
})