-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp-3d.js
More file actions
2737 lines (2585 loc) · 107 KB
/
Copy pathapp-3d.js
File metadata and controls
2737 lines (2585 loc) · 107 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
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// NorCal Touge Spots — 3D Cesium build
// Uses Cesium World Terrain + Bing Aerial imagery via Cesium Ion's free tier.
// Renders routes as ground-clamped polylines, POIs as billboards, and the
// Tilden golf course as a stack of color-coded ground polygons.
(function () {
"use strict";
// ─── Cesium Ion token ────────────────────────────────────────
// Cesium ships a default token that works for demo use (with a watermark
// and modest rate limits). For production use replace with your own free
// token from https://cesium.com/ion/tokens — sign up is free and gives
// higher quotas + lets you turn off the demo banner.
// Leaving Cesium.Ion.defaultAccessToken untouched falls back to the
// bundled demo token.
if (window.CESIUM_ION_TOKEN) {
Cesium.Ion.defaultAccessToken = window.CESIUM_ION_TOKEN;
}
const RATING_COLORS = {
5.0: Cesium.Color.fromCssColorString("#16a34a"),
4.5: Cesium.Color.fromCssColorString("#84cc16"),
4.0: Cesium.Color.fromCssColorString("#eab308"),
3.5: Cesium.Color.fromCssColorString("#f97316"),
3.0: Cesium.Color.fromCssColorString("#ef4444"),
};
const ROLL_RACING_COLOR = Cesium.Color.fromCssColorString("#a855f7");
const DIG_RACING_COLOR = Cesium.Color.fromCssColorString("#ec4899");
function isDragStrip(route) {
return Array.isArray(route?.tags) && route.tags.includes("drag-strip");
}
function isRollRacing(route) {
return Array.isArray(route?.tags) && route.tags.includes("roll-racing");
}
function isDigRacing(route) {
return Array.isArray(route?.tags) && route.tags.includes("dig-racing");
}
function colorForRoute(route) {
if (isRollRacing(route)) return ROLL_RACING_COLOR;
if (isDigRacing(route)) return DIG_RACING_COLOR;
if (isDragStrip(route)) return ROLL_RACING_COLOR;
return colorForRating(route.rating);
}
function colorForRating(r) {
if (r >= 5) return RATING_COLORS[5.0];
if (r >= 4.5) return RATING_COLORS[4.5];
if (r >= 4) return RATING_COLORS[4.0];
if (r >= 3.5) return RATING_COLORS[3.5];
return RATING_COLORS[3.0];
}
function colorForRatingHex(r) {
if (r >= 5) return "#16a34a";
if (r >= 4.5) return "#84cc16";
if (r >= 4) return "#eab308";
if (r >= 3.5) return "#f97316";
return "#ef4444";
}
function dragStripLabel(route) {
if (isRollRacing(route)) return "🏁 Roll Racing";
if (isDigRacing(route)) return "🏁 Dig Racing";
return "🏁 Drag strip";
}
function classForRoute(route) {
if (isRollRacing(route)) return "r-roll";
if (isDigRacing(route)) return "r-dig";
if (isDragStrip(route)) return "r-roll";
if (route.rating >= 5) return "r-5";
if (route.rating >= 4.5) return "r-45";
if (route.rating >= 4) return "r-4";
if (route.rating >= 3.5) return "r-35";
return "r-3";
}
function metersToMiles(m) { return m * 0.000621371; }
function fmtDistance(m) {
const mi = metersToMiles(m);
return mi >= 10 ? `${mi.toFixed(0)} mi` : `${mi.toFixed(1)} mi`;
}
function fmtDuration(s) {
const min = s / 60;
if (min < 60) return `${Math.round(min)} min`;
const h = Math.floor(min / 60);
const m = Math.round(min % 60);
return m === 0 ? `${h} hr` : `${h} hr ${m} min`;
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, (c) => ({
"&": "&", "<": "<", ">": ">", '"': """, "'": "'",
}[c]));
}
function haversine(lat1, lon1, lat2, lon2) {
const R = 6371000;
const toRad = (d) => (d * Math.PI) / 180;
const dLat = toRad(lat2 - lat1);
const dLon = toRad(lon2 - lon1);
const a =
Math.sin(dLat / 2) ** 2 +
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) ** 2;
return 2 * R * Math.asin(Math.sqrt(a));
}
// ─── App state ───────────────────────────────────────────────
let viewer;
let routesData = null;
/** id → { polyline: Entity, marker: Entity, poiEntities: Entity[], route } */
const routeLayers = {};
let activeId = null;
const filters = {
rating: 0,
region: "all",
type: "all",
search: "",
favoritesOnly: false,
maxLengthMi: Infinity,
maxFromBerkeleyMin: Infinity,
};
// ─── Favorites (persisted in localStorage) ──────────────────
const FAV_KEY = "tougespot_favorites_v1";
function loadFavorites() {
try {
const raw = localStorage.getItem(FAV_KEY);
if (!raw) return new Set();
return new Set(JSON.parse(raw));
} catch { return new Set(); }
}
function saveFavorites(set) {
try { localStorage.setItem(FAV_KEY, JSON.stringify([...set])); } catch {}
}
const favorites = loadFavorites();
function toggleFavorite(id) {
if (favorites.has(id)) favorites.delete(id);
else favorites.add(id);
saveFavorites(favorites);
renderRouteList();
if (filters.favoritesOnly) applyFilters();
}
// ─── Cesium init ─────────────────────────────────────────────
async function initViewer() {
// Terrain stack — with hard timeouts so a slow CDN can't block boot:
// 1. Cesium World Terrain (Ion; best quality)
// 2. Esri World Elevation 3D (free, no key)
// 3. Flat ellipsoid (last resort)
const withTimeout = (p, ms, label) => Promise.race([
p,
new Promise((_, reject) => setTimeout(() => reject(new Error(label + " timed out after " + ms + "ms")), ms)),
]);
let terrainProvider;
let usingRealTerrain = false;
let terrainSource = "flat";
try {
terrainProvider = await withTimeout(
Cesium.createWorldTerrainAsync({ requestVertexNormals: true, requestWaterMask: true }),
4000,
"Cesium World Terrain"
);
usingRealTerrain = true;
terrainSource = "Cesium World Terrain";
} catch (eIon) {
console.warn("Cesium World Terrain unavailable, trying Esri…", eIon.message || eIon);
try {
terrainProvider = await withTimeout(
Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
"https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"
),
5000,
"Esri World Elevation"
);
usingRealTerrain = true;
terrainSource = "Esri World Elevation";
} catch (eEsri) {
console.warn("Esri terrain unavailable, using flat globe:", eEsri.message || eEsri);
terrainProvider = new Cesium.EllipsoidTerrainProvider();
}
}
// Multiple free imagery providers, all from Esri (no API key required).
// We default to the gray canvas because:
// - way smaller payloads → loads faster on slow machines
// - the gray base makes our colored route polylines pop visually
// - it's the "simplified, roads-focused" look the project goals call for
const BASEMAPS = {
gray: {
label: "B&W (light)",
base: () => new Cesium.UrlTemplateImageryProvider({
url: "https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}",
maximumLevel: 16,
credit: "Esri Light Gray Canvas",
}),
// Reference layer = labels + bold road network drawn over the base
ref: () => new Cesium.UrlTemplateImageryProvider({
url: "https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Reference/MapServer/tile/{z}/{y}/{x}",
maximumLevel: 16,
}),
},
dark: {
label: "B&W (dark)",
base: () => new Cesium.UrlTemplateImageryProvider({
url: "https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Base/MapServer/tile/{z}/{y}/{x}",
maximumLevel: 16,
credit: "Esri Dark Gray Canvas",
}),
ref: () => new Cesium.UrlTemplateImageryProvider({
url: "https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Reference/MapServer/tile/{z}/{y}/{x}",
maximumLevel: 16,
}),
},
satellite: {
label: "Satellite",
base: () => new Cesium.UrlTemplateImageryProvider({
url: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
maximumLevel: 19,
credit: "Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community",
}),
},
};
viewer = new Cesium.Viewer("map", {
terrainProvider,
baseLayerPicker: false, // we set our own imagery below
animation: false,
timeline: false,
fullscreenButton: true,
geocoder: false,
homeButton: true,
infoBox: true,
navigationHelpButton: false, // we have our own help overlay
sceneModePicker: true,
selectionIndicator: true,
shadows: false,
shouldAnimate: false,
// ?snap=1 enables preserveDrawingBuffer so the snapshot tool can read
// pixels back. Slight perf cost — off by default.
contextOptions: {
webgl: {
preserveDrawingBuffer: new URL(window.location.href).searchParams.get("snap") === "1",
},
},
});
// Default to satellite — gives the realistic terrain texture so the 3D
// depth reads visually. Gray/dark are alternatives via the sidebar toggle.
function applyBasemap(name) {
const b = BASEMAPS[name] || BASEMAPS.satellite;
viewer.imageryLayers.removeAll();
viewer.imageryLayers.addImageryProvider(b.base());
if (b.ref) viewer.imageryLayers.addImageryProvider(b.ref());
window.__currentBasemap__ = name;
}
window.__applyBasemap__ = applyBasemap;
window.__BASEMAPS__ = BASEMAPS;
applyBasemap("satellite");
// Expose viewer so devtools / scripts can drive the camera
window.__viewer__ = viewer;
// Tell the user (in the loading banner) which mode we're in
const loading = document.getElementById("loading");
if (loading && !usingRealTerrain) {
loading.innerHTML =
"Loading routes… <span style='color:#fbbf24;font-size:11px;'>(flat globe — add a free Cesium Ion token for real terrain)</span>";
} else if (loading && usingRealTerrain) {
loading.innerHTML = `Loading routes… <span style='color:#86efac;font-size:11px;'>(3D terrain via ${escapeHtml(terrainSource)})</span>`;
}
// Visual polish — punch up the contrast and atmosphere
if (usingRealTerrain) {
// Slight vertical exaggeration so the East Bay hills feel hilly rather
// than gentle. 1.5 is enough to be readable without looking cartoonish.
viewer.scene.verticalExaggeration = 1.5;
}
// We're using Esri imagery + Esri terrain, NOT Cesium Ion services, so
// the Cesium ion branding/logo does not legally need to be displayed.
// Hide the logo container while keeping the Esri credit text visible.
const creditCont = viewer.cesiumWidget.creditContainer;
creditCont.style.color = "#cbd5e1";
// Apply CSS belt-and-braces in case the logo container is recreated later.
const style = document.createElement("style");
style.textContent = `
.cesium-credit-logoContainer { display: none !important; }
.cesium-credit-textContainer { font-size: 10px; color: rgba(229,231,235,0.7) !important; }
`;
document.head.appendChild(style);
// Atmosphere / fog / lighting defaults — start subtle, the user can
// toggle them on/off from the sidebar.
viewer.scene.skyAtmosphere.show = true; // gentle horizon haze
viewer.scene.fog.enabled = true;
// Enable lighting so buildings get directional shading (more 3D-feeling)
viewer.scene.globe.enableLighting = true;
viewer.scene.globe.depthTestAgainstTerrain = true;
// Brighten ambient so shadowed building faces stay readable
viewer.scene.light = new Cesium.SunLight();
viewer.scene.globe.atmosphereLightIntensity = 5.0;
// Default camera: tilted overhead view of the Bay Area
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(-122.2, 37.6, 65000),
orientation: {
heading: Cesium.Math.toRadians(0),
pitch: Cesium.Math.toRadians(-55),
roll: 0,
},
duration: 0,
});
// UC Berkeley origin marker
viewer.entities.add({
name: "UC Berkeley",
position: Cesium.Cartesian3.fromDegrees(-122.2585, 37.8719),
billboard: {
image: makeOriginPin(),
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scale: 1,
},
description:
"<strong>UC Berkeley</strong><br>Origin point — drive times measured from here.",
});
// Click handler for routes / POIs.
// - Click a route polyline or its start pin → open detail panel
// - Click a POI billboard or polygon → fly camera in close, show description
// - Click empty space → close detail
viewer.screenSpaceEventHandler.setInputAction((click) => {
const picked = viewer.scene.pick(click.position);
if (picked && picked.id) {
const id = picked.id;
if (id._routeId) {
openDetail(id._routeId);
return;
}
// Generic entity click — Cesium's selectionIndicator + InfoBox handle
// the popup; here we add a fly-in for non-route POIs/polygons so the
// user gets a guided zoom.
if (id.position) {
const pos = id.position.getValue ? id.position.getValue(viewer.clock.currentTime) : id.position;
if (pos) {
const carto = Cesium.Cartographic.fromCartesian(pos);
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(
Cesium.Math.toDegrees(carto.longitude),
Cesium.Math.toDegrees(carto.latitude) - 0.003,
900
),
orientation: { heading: 0, pitch: Cesium.Math.toRadians(-35), roll: 0 },
duration: 1.4,
});
}
} else if (id.polygon) {
// Polygon (golf feature, area POI) — fly to centroid
viewer.flyTo(id, {
duration: 1.4,
offset: new Cesium.HeadingPitchRange(0, Cesium.Math.toRadians(-35), 1500),
});
}
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
// Hover handler — when the cursor enters a route polyline, beef it up;
// when it leaves, restore. Also drives the live coords HUD readout.
let hoverEntity = null;
const coordsEl = document.getElementById("hud-coords");
const ellipsoid = viewer.scene.globe.ellipsoid;
viewer.screenSpaceEventHandler.setInputAction((move) => {
// Coords HUD
if (coordsEl) {
const cartesian = viewer.camera.pickEllipsoid(move.endPosition, ellipsoid);
if (cartesian) {
const c = Cesium.Cartographic.fromCartesian(cartesian);
coordsEl.textContent =
`${Cesium.Math.toDegrees(c.latitude).toFixed(5)}, ${Cesium.Math.toDegrees(c.longitude).toFixed(5)}`;
}
}
// Hover highlight on routes
const picked = viewer.scene.pick(move.endPosition);
const newHover = picked && picked.id && picked.id._routeId ? picked.id : null;
if (newHover === hoverEntity) return;
// Reset previous
if (hoverEntity && hoverEntity.polyline) {
const id = hoverEntity._routeId;
const wasActive = id === activeId;
hoverEntity.polyline.width = wasActive ? 9 : 5;
}
hoverEntity = newHover;
if (hoverEntity && hoverEntity.polyline) {
hoverEntity.polyline.width = 11;
document.body.style.cursor = "pointer";
} else {
document.body.style.cursor = "";
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
}
// Origin pin as data-URL canvas — Cesium billboards take an image
function makeOriginPin() {
const canvas = document.createElement("canvas");
canvas.width = 36;
canvas.height = 36;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#fff";
ctx.strokeStyle = "#0b1015";
ctx.lineWidth = 3;
ctx.beginPath();
ctx.arc(18, 18, 14, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#0b1015";
ctx.font = "bold 16px system-ui";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("B", 18, 18);
return canvas.toDataURL();
}
function makePoiPin(glyph, bg) {
const canvas = document.createElement("canvas");
canvas.width = 40;
canvas.height = 40;
const ctx = canvas.getContext("2d");
ctx.fillStyle = bg;
ctx.strokeStyle = "rgba(0,0,0,0.6)";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(20, 20, 16, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
ctx.font = "18px system-ui";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(glyph, 20, 20);
return canvas.toDataURL();
}
// ─── Route loading ──────────────────────────────────────────
async function loadRoutes() {
const res = await fetch("routes.json");
if (!res.ok) throw new Error(`routes.json ${res.status}`);
routesData = await res.json();
const loading = document.getElementById("loading");
let pendingTrace = [];
for (const route of routesData.routes) {
if (route.geometry && route.geometry.coordinates && route.geometry.coordinates.length) {
route._geom = route.geometry;
route._distance = route.length_m || 0;
route._duration = route.duration_s || 0;
route._fromBerkeley = route.from_origin_s || 0;
renderRouteOnMap(route);
} else {
pendingTrace.push(route);
}
}
// Routes without precomputed geometry — straight-line fallback in 3D mode
// (live OSRM/Valhalla tracing is preserved in the 2D build; in 3D we
// prioritize quick boot since the heavy lifting is the terrain stream).
for (const route of pendingTrace) {
route._geom = {
type: "LineString",
coordinates: route.waypoints.map(([lat, lon]) => [lon, lat]),
};
route._distance = 0;
route._duration = 0;
route._fromBerkeley = (haversine(
routesData.metadata.origin.lat,
routesData.metadata.origin.lon,
route.waypoints[0][0],
route.waypoints[0][1]
) / 1000) * 72; // 72 sec/km rough estimate
renderRouteOnMap(route);
}
// Standalone POIs (not tied to a route)
if (Array.isArray(routesData.pois)) {
for (const poi of routesData.pois) {
renderPoi(poi, null);
}
}
renderRouteList();
flyToVisible();
loading.classList.add("hidden");
}
function renderRouteOnMap(route) {
const color = colorForRoute(route);
const dragStrip = isDragStrip(route);
// routes.json geometry is [lon, lat]
const positions = Cesium.Cartesian3.fromDegreesArray(
route._geom.coordinates.flat()
);
// PolylineGlowMaterial gives a soft halo around each route — really pops
// on the gray basemap and reads cleanly on satellite too.
const baseWidth = dragStrip ? 6 : 5;
const glowMaterial = dragStrip
? new Cesium.PolylineDashMaterialProperty({ color, dashLength: 16 })
: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.22,
taperPower: 1,
color,
});
const polylineEntity = viewer.entities.add({
name: route.name,
polyline: {
positions,
width: baseWidth,
clampToGround: true,
material: glowMaterial,
// depthFailMaterial keeps the line readable when it dips behind a
// ridge in 3D oblique view
depthFailMaterial: new Cesium.PolylineDashMaterialProperty({
color: color.withAlpha(0.55),
dashLength: 12,
}),
},
});
polylineEntity._routeId = route.id;
// Invisible thick "click target" polyline so the route is easy to pick
// even on touch devices where pointer accuracy is poor.
const pickTarget = viewer.entities.add({
polyline: {
positions,
width: 22,
clampToGround: true,
material: Cesium.Color.TRANSPARENT,
},
});
pickTarget._routeId = route.id;
// Start-point billboard
const start = route._geom.coordinates[0];
const markerEntity = viewer.entities.add({
name: route.name,
position: Cesium.Cartesian3.fromDegrees(start[0], start[1]),
billboard: {
image: makeRoutePin(route),
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scale: 1,
},
description: routePopupHtml(route),
});
markerEntity._routeId = route.id;
// POIs along this route
const poiEntities = [];
if (Array.isArray(route.pois)) {
for (const poi of route.pois) {
const ents = renderPoi(poi, route);
if (Array.isArray(ents)) poiEntities.push(...ents);
else if (ents) poiEntities.push(ents);
}
}
// Distance label at the route midpoint — small floating chip
let distanceLabel = null;
const geomCoords = route._geom.coordinates;
if (route._distance && geomCoords.length > 1) {
const midIdx = Math.floor(geomCoords.length / 2);
const [mLon, mLat] = geomCoords[midIdx];
const distMi = (route._distance / 1609.344).toFixed(1);
distanceLabel = viewer.entities.add({
position: Cesium.Cartesian3.fromDegrees(mLon, mLat),
label: {
text: `${distMi} mi`,
font: "bold 11px system-ui",
fillColor: Cesium.Color.WHITE,
outlineColor: Cesium.Color.BLACK,
outlineWidth: 3,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
showBackground: true,
backgroundColor: color.withAlpha(0.85),
backgroundPadding: new Cesium.Cartesian2(7, 4),
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
pixelOffset: new Cesium.Cartesian2(0, -8),
// Only show distance labels at moderate zoom to avoid clutter
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 50000),
},
});
}
routeLayers[route.id] = {
polyline: polylineEntity,
pickTarget,
marker: markerEntity,
poiEntities,
distanceLabel,
route,
};
}
function makeRoutePin(route) {
const canvas = document.createElement("canvas");
canvas.width = 44;
canvas.height = 56;
const ctx = canvas.getContext("2d");
const bg = colorForRoute(route).toCssColorString();
// Drop pin shape
ctx.fillStyle = bg;
ctx.strokeStyle = "rgba(0,0,0,0.6)";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(22, 22, 18, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
// Pointer
ctx.beginPath();
ctx.moveTo(14, 36);
ctx.lineTo(22, 54);
ctx.lineTo(30, 36);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#fff";
ctx.font = "bold 16px system-ui";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
if (isDragStrip(route)) {
ctx.fillText("🏁", 22, 22);
} else {
ctx.fillText(String(route.rating), 22, 22);
}
return canvas.toDataURL();
}
function routePopupHtml(route) {
const distStr = route._distance ? fmtDistance(route._distance) : "—";
const durStr = route._duration ? fmtDuration(route._duration) : "—";
const fromB = route._fromBerkeley ? fmtDuration(route._fromBerkeley) : "—";
const ratingChip = isDragStrip(route)
? `<span style="color:${colorForRoute(route).toCssColorString()};">${dragStripLabel(route)}</span>`
: `<strong>${route.rating}/5</strong>`;
return `
<div style="font-family:system-ui;color:#e5e7eb;">
<h3 style="margin:0 0 4px 0;">${escapeHtml(route.name)}</h3>
<div style="font-size:12px;color:#9ca3af;margin-bottom:8px;">
${ratingChip} · ${escapeHtml(route.region)} · ${escapeHtml(route.surface || "paved")}
</div>
<div style="font-size:12px;line-height:1.5;">
<div>↔ ${distStr} · ${durStr} drive</div>
<div>🚗 ${fromB} from Berkeley</div>
</div>
<div style="margin-top:10px;font-size:12px;line-height:1.4;">${escapeHtml(route.summary || "")}</div>
</div>
`;
}
// ─── POIs ───────────────────────────────────────────────────
function renderPoi(poi, route) {
// Polygon-with-features POI (Tilden golf course)
if (poi.features_url) {
return renderAreaWithFeatures(poi, route);
}
// Simple polygon POI (perimeter only)
if (Array.isArray(poi.polygon) && poi.polygon.length >= 3) {
return renderSimplePolygonPoi(poi, route);
}
// Point POI (vista, crash, donut, etc.)
const iconKind = poi.icon || "pin";
const glyphMap = {
crash: ["💥", "#ef4444"],
vista: ["📷", "#0ea5e9"],
donut: ["🍩", "#d946ef"],
golf: ["🏌", "#16a34a"],
pin: ["📍", "#64748b"],
};
const [glyph, bg] = glyphMap[iconKind] || glyphMap.pin;
const ent = viewer.entities.add({
name: poi.title || iconKind,
position: Cesium.Cartesian3.fromDegrees(poi.lon, poi.lat),
billboard: {
image: makePoiPin(glyph, bg),
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scale: 0.9,
},
description: poiPopupHtml(poi, route),
});
return ent;
}
function renderSimplePolygonPoi(poi, route) {
const positions = poi.polygon.flatMap(([lat, lon]) => [lon, lat]);
const ent = viewer.entities.add({
name: poi.title || "area",
polygon: {
hierarchy: Cesium.Cartesian3.fromDegreesArray(positions),
material: Cesium.Color.fromCssColorString("#16a34a").withAlpha(0.45),
classificationType: Cesium.ClassificationType.TERRAIN,
},
description: poiPopupHtml(poi, route),
});
return ent;
}
// Color palette for the golf-course features
const GOLF_STYLES = {
green: { fill: "#22c55e", alpha: 0.95, outline: "#14532d" },
fairway: { fill: "#4ade80", alpha: 0.7, outline: "#166534" },
tee: { fill: "#86efac", alpha: 0.85, outline: "#15803d" },
bunker: { fill: "#fde68a", alpha: 0.95, outline: "#a16207" },
driving_range:{ fill: "#bef264", alpha: 0.5, outline: "#65a30d" },
clubhouse: { fill: "#374151", alpha: 0.9, outline: "#1f2937" },
rough: { fill: "#65a30d", alpha: 0.4, outline: "#3f6212" },
default: { fill: "#16a34a", alpha: 0.4, outline: "#16a34a" },
};
function renderAreaWithFeatures(poi, route) {
const ents = [];
// Loading-state perimeter while features stream in
let placeholder = null;
if (Array.isArray(poi.polygon) && poi.polygon.length >= 3) {
const perimPositions = poi.polygon.flatMap(([lat, lon]) => [lon, lat]);
placeholder = viewer.entities.add({
name: poi.title,
polygon: {
hierarchy: Cesium.Cartesian3.fromDegreesArray(perimPositions),
material: Cesium.Color.fromCssColorString("#16a34a").withAlpha(0.25),
classificationType: Cesium.ClassificationType.TERRAIN,
},
});
ents.push(placeholder);
}
fetch(poi.features_url)
.then((r) => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json();
})
.then((data) => {
if (placeholder) {
viewer.entities.remove(placeholder);
const idx = ents.indexOf(placeholder);
if (idx >= 0) ents.splice(idx, 1);
}
const features = data.features || [];
for (const f of features) {
if (!f.coords || f.coords.length < 2) continue;
if (f.shape === "line") {
// hole centerlines + cart paths
const linePositions = Cesium.Cartesian3.fromDegreesArray(
f.coords.flatMap(([lat, lon]) => [lon, lat])
);
if (f.kind === "hole") {
const ent = viewer.entities.add({
name: poi.title,
polyline: {
positions: linePositions,
width: 2.5,
clampToGround: true,
material: new Cesium.PolylineDashMaterialProperty({
color: Cesium.Color.fromCssColorString("#facc15"),
dashLength: 14,
}),
},
description: golfFeatureDesc(poi, f),
});
// Add hole-number label at midpoint with high contrast (works on
// both gray and satellite basemaps).
const mid = f.coords[Math.floor(f.coords.length / 2)];
if (mid && f.ref) {
const lblEnt = viewer.entities.add({
position: Cesium.Cartesian3.fromDegrees(mid[1], mid[0]),
label: {
text: String(f.ref),
font: "bold 13px system-ui",
fillColor: Cesium.Color.WHITE,
outlineColor: Cesium.Color.BLACK,
outlineWidth: 4,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
showBackground: true,
backgroundColor: Cesium.Color.fromCssColorString("#0b1015").withAlpha(0.75),
backgroundPadding: new Cesium.Cartesian2(6, 3),
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
pixelOffset: new Cesium.Cartesian2(0, -10),
distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 6000),
},
});
ents.push(lblEnt);
}
ents.push(ent);
} else if (f.kind === "cartpath") {
const ent = viewer.entities.add({
polyline: {
positions: linePositions,
width: 1.5,
clampToGround: true,
material: new Cesium.PolylineDashMaterialProperty({
color: Cesium.Color.fromCssColorString("#a8a29e").withAlpha(0.7),
dashLength: 6,
}),
},
});
ents.push(ent);
}
continue;
}
// polygon features
const style = GOLF_STYLES[f.kind] || GOLF_STYLES.default;
const positions = f.coords.flatMap(([lat, lon]) => [lon, lat]);
const ent = viewer.entities.add({
name: poi.title,
polygon: {
hierarchy: Cesium.Cartesian3.fromDegreesArray(positions),
material: Cesium.Color.fromCssColorString(style.fill).withAlpha(style.alpha),
classificationType: Cesium.ClassificationType.TERRAIN,
},
description: golfFeatureDesc(poi, f),
});
ents.push(ent);
}
})
.catch((err) => {
console.warn(`Failed to load features for "${poi.title}":`, err);
});
return ents;
}
function golfFeatureDesc(poi, f) {
const head = escapeHtml(poi.title || "");
const sub = f.ref
? `Hole ${escapeHtml(f.ref)}${f.par ? ` · par ${escapeHtml(f.par)}` : ""}`
: f.name
? escapeHtml(f.name)
: escapeHtml(f.kind.replace(/_/g, " "));
return `
<div style="font-family:system-ui;color:#e5e7eb;">
<h3 style="margin:0 0 4px 0;">${head}</h3>
<div style="font-size:12px;color:#9ca3af;">${sub}</div>
${poi.description ? `<div style="font-size:12px;line-height:1.5;margin-top:8px;">${escapeHtml(poi.description)}</div>` : ""}
</div>
`;
}
function poiPopupHtml(poi, route) {
const warningBlock = poi.warning
? `<div style="background:#7f1d1d;color:#fff;padding:6px 8px;border-radius:6px;margin-bottom:8px;font-weight:600;">
${escapeHtml(poi.warning_label || "⚠ WARNING")}
${poi.warning_subtitle ? `<div style="font-weight:400;font-size:11px;margin-top:2px;">${escapeHtml(poi.warning_subtitle)}</div>` : ""}
</div>`
: "";
const onRoute = route ? `<div style="font-size:11px;color:#9ca3af;margin-bottom:6px;">On <em>${escapeHtml(route.name)}</em></div>` : "";
return `
<div style="font-family:system-ui;color:#e5e7eb;">
${warningBlock}
<h3 style="margin:0 0 4px 0;">${escapeHtml(poi.title || "")}</h3>
${onRoute}
${poi.description ? `<div style="font-size:12px;line-height:1.5;">${escapeHtml(poi.description)}</div>` : ""}
</div>
`;
}
// ─── Visibility / filtering ─────────────────────────────────
function visibleRoutes() {
if (!routesData) return [];
const q = (filters.search || "").trim().toLowerCase();
return routesData.routes.filter((r) => {
const ds = isDragStrip(r);
const roll = isRollRacing(r);
const dig = isDigRacing(r);
if (filters.rating > 0 && !ds && r.rating < filters.rating) return false;
if (filters.rating > 0 && ds) return false;
if (filters.region !== "all" && r.region !== filters.region) return false;
if (filters.type === "touge" && ds) return false;
if (filters.type === "roll-racing" && !roll) return false;
if (filters.type === "dig-racing" && !dig) return false;
if (filters.type === "drag-strip" && !ds) return false;
if (q) {
const hay = `${r.name || ""} ${r.region || ""} ${r.summary || ""}`.toLowerCase();
if (!hay.includes(q)) return false;
}
if (filters.favoritesOnly && !favorites.has(r.id)) return false;
if (filters.maxLengthMi !== Infinity && r._distance) {
const mi = r._distance / 1609.344;
if (mi > filters.maxLengthMi) return false;
}
if (filters.maxFromBerkeleyMin !== Infinity && r._fromBerkeley) {
const min = r._fromBerkeley / 60;
if (min > filters.maxFromBerkeleyMin) return false;
}
return true;
});
}
function applyFilters() {
const visibleIds = new Set(visibleRoutes().map((r) => r.id));
Object.entries(routeLayers).forEach(([id, layer]) => {
const show = visibleIds.has(id);
layer.polyline.show = show;
layer.marker.show = show;
if (layer.pickTarget) layer.pickTarget.show = show;
if (layer.distanceLabel) layer.distanceLabel.show = show;
(layer.poiEntities || []).forEach((e) => { if (e) e.show = show; });
});
renderRouteList();
flyToVisible();
}
function flyToVisible() {
const visible = visibleRoutes();
if (!visible.length) return;
let lonMin = 180, lonMax = -180, latMin = 90, latMax = -90;
for (const r of visible) {
if (!r._geom) continue;
for (const [lon, lat] of r._geom.coordinates) {
if (lon < lonMin) lonMin = lon;
if (lon > lonMax) lonMax = lon;
if (lat < latMin) latMin = lat;
if (lat > latMax) latMax = lat;
}
}
if (lonMin > lonMax) return;
const padding = 0.05;
viewer.camera.flyTo({
destination: Cesium.Rectangle.fromDegrees(
lonMin - padding, latMin - padding,
lonMax + padding, latMax + padding
),
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-55),
roll: 0,
},
duration: 1.5,
});
}
// ─── Sidebar list ───────────────────────────────────────────
function renderRouteStats(routes) {
const el = document.getElementById("route-stats");
if (!el) return;
if (!routes.length) { el.innerHTML = ""; return; }
const totalMi = routes.reduce((s, r) => s + (r._distance || 0), 0) / 1609.344;
const ratings = routes.filter((r) => !isDragStrip(r) && r.rating).map((r) => r.rating);
const avgRating = ratings.length ? (ratings.reduce((a, b) => a + b, 0) / ratings.length) : null;
const totalDriveMin = routes.reduce((s, r) => s + (r._duration || 0), 0) / 60;
el.innerHTML = `
<span class="stat"><strong>${routes.length}</strong> route${routes.length === 1 ? "" : "s"}</span>
<span class="stat"><strong>${Math.round(totalMi)}</strong> mi total</span>
${avgRating ? `<span class="stat"><strong>${avgRating.toFixed(1)}</strong> avg ★</span>` : ""}
<span class="stat"><strong>${Math.round(totalDriveMin)}</strong> min driving</span>
`;
}
function renderRouteList() {
const container = document.getElementById("route-list");
container.innerHTML = "";
const sorted = visibleRoutes().sort((a, b) => {
const aDs = isDragStrip(a), bDs = isDragStrip(b);
if (aDs !== bDs) return aDs ? 1 : -1;
return (b.rating || 0) - (a.rating || 0);
});
renderRouteStats(sorted);
if (!sorted.length) {
container.innerHTML = `
<div class="route-list-empty">
<div>No routes match these filters.</div>
<button class="clear-filters" id="clear-filters-btn">Clear filters</button>
</div>
`;
document.getElementById("clear-filters-btn")?.addEventListener("click", () => {
// Reset all filter chips, sliders, and search input
document.querySelectorAll("#rating-chips .chip").forEach((c) =>
c.classList.toggle("active", c.dataset.rating === "0"));
document.querySelectorAll("#region-chips .chip").forEach((c) =>
c.classList.toggle("active", c.dataset.region === "all"));
document.querySelectorAll("#type-chips .chip").forEach((c) =>
c.classList.toggle("active", c.dataset.type === "all"));
document.getElementById("toggle-favorites")?.classList.remove("active");
const search = document.getElementById("route-search");
if (search) search.value = "";
const lenSlider = document.getElementById("max-length");
const lenVal = document.getElementById("max-length-val");
if (lenSlider && lenVal) { lenSlider.value = lenSlider.max; lenVal.textContent = "∞"; }
const fromSlider = document.getElementById("max-from-berkeley");
const fromVal = document.getElementById("max-from-berkeley-val");
if (fromSlider && fromVal) { fromSlider.value = fromSlider.max; fromVal.textContent = "∞"; }
filters.rating = 0;