-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1113 lines (964 loc) · 36.8 KB
/
Copy pathapp.js
File metadata and controls
1113 lines (964 loc) · 36.8 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
// Mapbox token is injected by config.js.php at page load as window.MAPBOX_TOKEN
let MAPBOX_TOKEN = window.MAPBOX_TOKEN || '';
// --- State ---
const state = {
a: null, // { lat, lng, name }
b: null,
map: null,
markers: [],
markerElements: [],
allResults: [], // full unfiltered result set, preserved for filter re-runs
activeFilters: new Set(),
sortBy: 'rating',
distanceBias: 50, // 0 = point A, 50 = midpoint, 100 = point B
routePoints: [], // polyline points from the route
biasMarker: null, // mapbox marker for distance bias point
midpoint: null,
searching: false,
userLocation: null,
aIsAutoFilled: false,
nearMeMode: false,
};
// --- Utilities ---
let toastTimer;
function showToast(msg) {
const el = document.getElementById('toast');
el.textContent = msg;
el.classList.add('visible');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => el.classList.remove('visible'), 2200);
}
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
function haversineKm(lat1, lng1, lat2, lng2) {
const R = 6371;
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLng = (lng2 - lng1) * Math.PI / 180;
const a = Math.sin(dLat / 2) ** 2
+ Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLng / 2) ** 2;
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
// --- Geocoding (Google Places Autocomplete via PHP proxy) ---
async function autocompleteSuggest(query, proximity, signal) {
const params = new URLSearchParams({ action: 'autocomplete', input: query });
if (proximity) {
params.set('lat', proximity.lat);
params.set('lng', proximity.lng);
}
const res = await fetch('api.php?' + params, { signal });
const data = await res.json();
return data.predictions || [];
}
async function fetchPlaceDetails(placeId) {
const res = await fetch('api.php?action=placedetails&place_id=' + encodeURIComponent(placeId));
const data = await res.json();
const loc = data.result?.geometry?.location;
if (!loc) throw new Error('Could not get location for selected place');
return {
lat: loc.lat,
lng: loc.lng,
name: data.result.formatted_address || data.result.name,
};
}
function setupInput(inputEl, listEl, targetKey) {
const otherKey = targetKey === 'a' ? 'b' : 'a';
let autocompleteController = null;
const debouncedSearch = debounce(async (query) => {
if (query.length < 3) { listEl.innerHTML = ''; return; }
autocompleteController?.abort();
autocompleteController = new AbortController();
try {
const predictions = await autocompleteSuggest(query, state[otherKey], autocompleteController.signal);
listEl.innerHTML = '';
predictions.forEach(p => {
const li = document.createElement('li');
li.textContent = p.description;
li.addEventListener('mousedown', async (e) => {
e.preventDefault();
listEl.innerHTML = '';
inputEl.value = p.description;
inputEl.disabled = true;
try {
const place = await fetchPlaceDetails(p.place_id);
state[targetKey] = place;
inputEl.value = place.name;
updateControls();
if (state.a && state.b) runSearch();
} catch (err) {
console.error('fetchPlaceDetails failed:', err);
} finally {
inputEl.disabled = false;
}
});
listEl.appendChild(li);
});
} catch (err) {
if (err.name !== 'AbortError') listEl.innerHTML = '';
}
}, 500);
inputEl.addEventListener('input', () => {
state[targetKey] = null;
updateControls();
debouncedSearch(inputEl.value.trim());
});
inputEl.addEventListener('keydown', (e) => {
const items = listEl.querySelectorAll('li');
const current = listEl.querySelector('li[aria-selected="true"]');
const idx = current ? [...items].indexOf(current) : -1;
if (e.key === 'ArrowDown') {
if (!items.length) return;
e.preventDefault();
const next = items[Math.min(idx + 1, items.length - 1)];
if (current) current.removeAttribute('aria-selected');
next.setAttribute('aria-selected', 'true');
next.scrollIntoView({ block: 'nearest' });
} else if (e.key === 'ArrowUp') {
if (!items.length) return;
e.preventDefault();
if (idx <= 0) return;
const prev = items[idx - 1];
current.removeAttribute('aria-selected');
prev.setAttribute('aria-selected', 'true');
prev.scrollIntoView({ block: 'nearest' });
} else if (e.key === 'Enter') {
const target = current || items[0];
if (target) {
e.preventDefault();
target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
}
} else if (e.key === 'Tab') {
const target = current || items[0];
if (target) target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
} else if (e.key === 'Escape') {
listEl.innerHTML = '';
}
});
inputEl.addEventListener('blur', () => {
setTimeout(() => { listEl.innerHTML = ''; }, 150);
});
if (targetKey === 'a') {
inputEl.addEventListener('focus', () => {
if (state.aIsAutoFilled) {
inputEl.value = '';
state.a = null;
state.aIsAutoFilled = false;
updateControls();
}
});
}
}
function setupLocateButton(btn, inputEl, targetKey) {
btn.addEventListener('click', () => {
if (!navigator.geolocation) {
alert('Geolocation is not supported by your browser.');
return;
}
btn.innerHTML = '<span class="material-icons">hourglass_empty</span>';
navigator.geolocation.getCurrentPosition(
(pos) => {
const { latitude: lat, longitude: lng } = pos.coords;
state[targetKey] = { lat, lng, name: 'My location' };
inputEl.value = 'My location';
btn.innerHTML = '<span class="material-icons">pin_drop</span>';
updateControls();
if (state.a && state.b) runSearch();
},
() => {
btn.innerHTML = '<span class="material-icons">pin_drop</span>';
alert('Could not get your location. Please type an address instead.');
}
);
});
}
function updateControls() {
const ready = !!(state.a && state.b);
searchBtn.disabled = !ready;
shareBtn.hidden = !ready;
}
// --- Filters ---
function applyFilters(restaurants) {
const f = state.activeFilters;
return restaurants.filter(r => {
// Open now
if (f.has('open') && r.opening_hours?.open_now === false) return false;
// Rating (only one rating filter can be active at a time)
if (f.has('rating-45') && (r.rating == null || r.rating < 4.5)) return false;
else if (f.has('rating-40') && (r.rating == null || r.rating < 4.0)) return false;
else if (f.has('rating-35') && (r.rating == null || r.rating < 3.5)) return false;
// Price — pass if no price filters active, or restaurant matches any selected level,
// or restaurant has no price data
const priceFilters = ['price-1', 'price-2', 'price-3', 'price-4'].filter(p => f.has(p));
if (priceFilters.length > 0 && r.price_level != null) {
if (!f.has(`price-${r.price_level}`)) return false;
}
return true;
});
}
function applySort(restaurants) {
const sorted = [...restaurants];
if (state.sortBy === 'distance') {
sorted.sort((x, y) => {
const dBiasX = x._dA * (1 - state.distanceBias / 100) + x._dB * (state.distanceBias / 100);
const dBiasY = y._dA * (1 - state.distanceBias / 100) + y._dB * (state.distanceBias / 100);
return dBiasX - dBiasY;
});
} else {
sorted.sort((x, y) => {
const rd = (y.rating || 0) - (x.rating || 0);
return rd !== 0 ? rd : (y.user_ratings_total || 0) - (x.user_ratings_total || 0);
});
}
return sorted;
}
function refreshResults() {
const visible = applySort(applyFilters(state.allResults));
renderResults(visible, state.a, state.b);
if (state.map) {
if (state.map.isStyleLoaded()) {
addMarkers(state.map, state.a, state.b, visible);
}
}
}
function setupSort() {
const ratingBtn = document.getElementById('sort-rating');
const distanceBtn = document.getElementById('sort-distance');
const biasSlider = document.getElementById('distance-bias');
ratingBtn.addEventListener('click', () => {
state.sortBy = 'rating';
ratingBtn.classList.add('active');
distanceBtn.classList.remove('active');
updateBiasMarker(state.routePoints);
refreshResults();
});
distanceBtn.addEventListener('click', () => {
state.sortBy = 'distance';
distanceBtn.classList.add('active');
ratingBtn.classList.remove('active');
updateBiasMarker(state.routePoints);
refreshResults();
});
biasSlider.addEventListener('input', (e) => {
state.distanceBias = parseFloat(e.target.value);
// Auto-switch to distance sort when slider moves
if (state.sortBy !== 'distance') {
state.sortBy = 'distance';
ratingBtn.classList.remove('active');
distanceBtn.classList.add('active');
}
updateBiasMarker(state.routePoints);
refreshResults();
});
biasSlider.addEventListener('dblclick', () => {
// Get current bias point and search from there (without entering near-me mode)
if (!state.routePoints || state.routePoints.length === 0) return;
const cumulativeDists = [0];
for (let i = 1; i < state.routePoints.length; i++) {
const prevPt = state.routePoints[i - 1];
const currPt = state.routePoints[i];
const segDist = haversineKm(prevPt.lat, prevPt.lng, currPt.lat, currPt.lng);
cumulativeDists.push(cumulativeDists[i - 1] + segDist);
}
const totalDist = cumulativeDists[cumulativeDists.length - 1];
const targetDist = totalDist * (state.distanceBias / 100);
let biasPoint = state.routePoints[0];
for (let i = 0; i < cumulativeDists.length; i++) {
if (cumulativeDists[i] >= targetDist) {
biasPoint = state.routePoints[i];
break;
}
}
runNearMeSearch(biasPoint.lat, biasPoint.lng, false);
});
}
function setupFilters() {
const ratingGroup = ['rating-35', 'rating-40', 'rating-45'];
document.querySelectorAll('.filter-btn').forEach(btn => {
btn.addEventListener('click', () => {
const key = btn.dataset.filter;
if (ratingGroup.includes(key)) {
// Rating filters are mutually exclusive — clicking the active one deselects it
const alreadyActive = state.activeFilters.has(key);
ratingGroup.forEach(k => {
state.activeFilters.delete(k);
document.querySelector(`[data-filter="${k}"]`).classList.remove('active');
});
if (!alreadyActive) {
state.activeFilters.add(key);
btn.classList.add('active');
}
} else {
// All other filters toggle independently
if (state.activeFilters.has(key)) {
state.activeFilters.delete(key);
btn.classList.remove('active');
} else {
state.activeFilters.add(key);
btn.classList.add('active');
}
}
refreshResults();
});
});
}
// --- Share link ---
const shareBtn = document.getElementById('share-btn');
shareBtn.addEventListener('click', () => {
if (!state.a || !state.b) return;
const params = new URLSearchParams({
alat: state.a.lat.toFixed(5),
alng: state.a.lng.toFixed(5),
aname: state.a.name.split(',')[0].trim(),
blat: state.b.lat.toFixed(5),
blng: state.b.lng.toFixed(5),
bname: state.b.name.split(',')[0].trim(),
});
const url = location.origin + location.pathname + '?' + params;
navigator.clipboard.writeText(url).then(() => showToast('Link copied to clipboard'));
});
// --- Midpoint ---
async function getRouteData(a, b) {
const params = new URLSearchParams({
action: 'route',
originLat: a.lat,
originLng: a.lng,
destLat: b.lat,
destLng: b.lng,
});
const res = await fetch('api.php?' + params);
const data = await res.json();
if (data.error) {
const err = new Error(data.error);
err.noRoute = true;
throw err;
}
return data; // { midpoint, p33, p67 }
}
// --- Restaurant fetch & filter ---
// --- Map ---
function clearMapLayers() {
if (!state.map) return;
// Remove layers
['route-line', 'zone-fill', 'nearby-circle'].forEach(layerId => {
if (state.map.getLayer(layerId)) {
state.map.removeLayer(layerId);
}
});
// Remove sources
['route', 'zone', 'nearby-circle'].forEach(sourceId => {
if (state.map.getSource(sourceId)) {
state.map.removeSource(sourceId);
}
});
// Remove markers
state.markerElements.forEach(el => el.remove());
state.markerElements = [];
state.markers.forEach(m => m.remove());
state.markers = [];
}
function initMap(center) {
if (state.map) {
state.map.jumpTo({ center: [center.lng, center.lat], zoom: 12 });
return state.map;
}
if (!mapboxgl) {
console.error('Mapbox GL not loaded');
return null;
}
const mapContainer = document.getElementById('map');
if (!mapContainer) {
console.error('Map container not found');
return null;
}
mapboxgl.accessToken = MAPBOX_TOKEN;
console.log('Creating map with token, center:', center);
try {
state.map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v12',
center: [center.lng, center.lat],
zoom: 12,
});
console.log('Map created successfully');
state.map.addControl(new mapboxgl.NavigationControl(), 'top-right');
} catch (err) {
console.error('Error creating map:', err);
return null;
}
return state.map;
}
function drawRoute(map, polylinePoints) {
const geojson = {
type: 'Feature',
geometry: { type: 'LineString', coordinates: polylinePoints.map(p => [p.lng, p.lat]) },
};
if (map.getSource('route')) { map.getSource('route').setData(geojson); return; }
map.addSource('route', { type: 'geojson', data: geojson });
map.addLayer({
id: 'route-line',
type: 'line',
source: 'route',
layout: { 'line-join': 'round', 'line-cap': 'round' },
paint: { 'line-color': '#4f46e5', 'line-width': 3, 'line-opacity': 0.45 },
});
}
function drawLocationShades(map, a, b, radiusKm = 3) {
if (!a || !b) return;
// Create GeoJSON circles for location points
const aCircle = turf.circle([a.lng, a.lat], radiusKm, { steps: 32 });
const bCircle = turf.circle([b.lng, b.lat], radiusKm, { steps: 32 });
// Remove old sources if they exist
['location-shade-a', 'location-shade-b'].forEach(id => {
if (map.getSource(id)) {
if (map.getLayer(id)) map.removeLayer(id);
map.removeSource(id);
}
});
// Add location A shade (blue)
map.addSource('location-shade-a', { type: 'geojson', data: aCircle });
map.addLayer({
id: 'location-shade-a',
type: 'fill',
source: 'location-shade-a',
paint: { 'fill-color': '#2563eb', 'fill-opacity': 0.08 },
});
// Add location B shade (red)
map.addSource('location-shade-b', { type: 'geojson', data: bCircle });
map.addLayer({
id: 'location-shade-b',
type: 'fill',
source: 'location-shade-b',
paint: { 'fill-color': '#dc2626', 'fill-opacity': 0.08 },
});
}
function drawZone(map, geojson) {
if (!geojson) return;
if (map.getSource('zone')) {
map.getSource('zone').setData(geojson);
return;
}
map.addSource('zone', { type: 'geojson', data: geojson });
map.addLayer({
id: 'zone-fill',
type: 'fill',
source: 'zone',
paint: { 'fill-color': '#4f46e5', 'fill-opacity': 0.07 },
});
map.addLayer({
id: 'zone-border',
type: 'line',
source: 'zone',
paint: { 'line-color': '#4f46e5', 'line-width': 2, 'line-dasharray': [4, 3] },
});
}
function placeMarker(map, lat, lng, className, title) {
const el = document.createElement('div');
el.className = 'marker ' + className;
el.title = title;
const m = new mapboxgl.Marker({ element: el }).setLngLat([lng, lat]).addTo(map);
state.markers.push(m);
return el;
}
function addMarkers(map, a, b, restaurants) {
state.markers.forEach(m => m.remove());
state.markers = [];
state.markerElements = [];
placeMarker(map, a.lat, a.lng, 'marker-a', 'You: ' + a.name);
placeMarker(map, b.lat, b.lng, 'marker-b', 'Friend: ' + b.name);
restaurants.forEach((r, i) => {
const el = placeMarker(
map,
r.geometry.location.lat,
r.geometry.location.lng,
'marker-restaurant',
r.name
);
el.dataset.index = i;
el.addEventListener('click', () => highlightResult(i));
state.markerElements.push(el);
});
const bounds = new mapboxgl.LngLatBounds();
bounds.extend([a.lng, a.lat]);
bounds.extend([b.lng, b.lat]);
restaurants.forEach(r => bounds.extend([r.geometry.location.lng, r.geometry.location.lat]));
map.fitBounds(bounds, { padding: 70, maxZoom: 14 });
}
// --- Results rendering ---
const SKIP_TYPES = new Set(['restaurant', 'food', 'point_of_interest', 'establishment']);
function formatCuisine(types) {
const t = (types || []).find(x => !SKIP_TYPES.has(x));
return t ? t.replace(/_/g, ' ') : 'restaurant';
}
function renderResults(restaurants, a, b) {
const header = document.getElementById('results-header');
const list = document.getElementById('results-list');
const sortControls = document.getElementById('sort-controls');
const n = restaurants.length;
const total = state.allResults.length;
const filtered = total > 0 && n < total;
const noResultsMsg = state.nearMeMode
? 'No restaurants found nearby. Try expanding your search area.'
: 'No restaurants found in the corridor. Try locations farther apart.';
header.textContent = n === 0
? (total > 0 ? 'No restaurants match the current filters.' : noResultsMsg)
: `${n}${filtered ? ` of ${total}` : ''} restaurant${n !== 1 ? 's' : ''} found`;
// Show sort controls only when there are results
if (sortControls) {
sortControls.hidden = n === 0;
}
list.innerHTML = '';
restaurants.forEach((r, i) => {
const dA = (r._dA ?? haversineKm(a.lat, a.lng, r.geometry.location.lat, r.geometry.location.lng)).toFixed(1);
const dB = b ? (r._dB ?? haversineKm(b.lat, b.lng, r.geometry.location.lat, r.geometry.location.lng)).toFixed(1) : null;
const rating = r.rating ? `★${r.rating} (${r.user_ratings_total.toLocaleString()})` : 'No rating';
const price = r.price_level ? '$'.repeat(r.price_level) : '';
const isOpen = r.opening_hours?.open_now;
const cuisine = r.primary_type || formatCuisine(r.types);
const mapsUrl = `https://www.google.com/maps/place/?q=place_id:${encodeURIComponent(r.place_id)}`;
const card = document.createElement('div');
card.className = 'restaurant-card';
card.dataset.index = i;
card.innerHTML = `
<div class="card-main">
<div class="card-name">${escapeHtml(r.name)}</div>
<div class="card-meta">
<span class="card-cuisine">${escapeHtml(cuisine)}</span>
${price ? `<span class="card-price">${price}</span>` : ''}
<span class="card-rating">${rating}</span>
${isOpen !== undefined
? `<span class="card-open ${isOpen ? 'open' : 'closed'}">${isOpen ? 'Open now' : 'Closed'}</span>`
: ''}
</div>
<div class="card-distances">
<span>${dA} km from you</span>
${dB !== null ? `<span>${dB} km from friend</span>` : ''}
</div>
</div>
<a class="card-link" href="${mapsUrl}" target="_blank" rel="noopener noreferrer">View on Maps</a>
`;
card.addEventListener('mouseenter', () => hoverResult(i));
card.addEventListener('mouseleave', () => unhoverResult());
card.addEventListener('click', (e) => {
if (e.target.closest('.card-link')) return;
highlightResult(i);
});
list.appendChild(card);
});
}
function hoverResult(index) {
state.markerElements.forEach(el => {
el.classList.toggle('hover', parseInt(el.dataset.index) === index);
});
}
function unhoverResult() {
state.markerElements.forEach(el => el.classList.remove('hover'));
}
function highlightResult(index) {
document.querySelectorAll('.restaurant-card').forEach((c, i) => {
c.classList.toggle('highlighted', i === index);
});
state.markerElements.forEach(el => {
el.classList.toggle('active', parseInt(el.dataset.index) === index);
});
document.querySelector(`.restaurant-card[data-index="${index}"]`)
?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
function escapeHtml(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
function updateBiasMarker(routePoints) {
// Remove existing marker
const markerEl = document.getElementById('bias-marker');
if (markerEl) {
markerEl.remove();
state.biasMarker = null;
}
// Only show marker when sorting by distance
if (!state.map || !state.a || !state.b || state.sortBy !== 'distance') return;
if (!routePoints || routePoints.length === 0) return;
// Find point along route based on slider position
// Calculate cumulative distance along route
const cumulativeDists = [0];
for (let i = 1; i < routePoints.length; i++) {
const prevPt = routePoints[i - 1];
const currPt = routePoints[i];
const segDist = haversineKm(prevPt.lat, prevPt.lng, currPt.lat, currPt.lng);
cumulativeDists.push(cumulativeDists[i - 1] + segDist);
}
const totalDist = cumulativeDists[cumulativeDists.length - 1];
const targetDist = totalDist * (state.distanceBias / 100);
// Find segment containing target distance
let targetPoint = routePoints[0];
for (let i = 0; i < cumulativeDists.length; i++) {
if (cumulativeDists[i] >= targetDist) {
targetPoint = routePoints[i];
break;
}
}
const el = document.createElement('div');
el.id = 'bias-marker';
el.className = 'bias-marker';
el.innerHTML = '⬜';
state.biasMarker = new mapboxgl.Marker({ element: el }).setLngLat([targetPoint.lng, targetPoint.lat]).addTo(state.map);
}
// --- Search flow ---
const searchBtn = document.getElementById('search-btn');
async function runSearch() {
const a = state.a;
const b = state.b;
if (!a || !b || state.searching) return;
if (!isFinite(a.lat) || !isFinite(a.lng) || !isFinite(b.lat) || !isFinite(b.lng)) return;
removeNearMeCircle(state.map);
state.nearMeMode = false;
state.searching = true;
searchBtn.disabled = true;
// Reset distance bias slider to middle for new search
state.distanceBias = 50;
const biasSlider = document.getElementById('distance-bias');
biasSlider.value = 50;
biasSlider.style.display = '';
try {
const midpoint = { lat: (a.lat + b.lat) / 2, lng: (a.lng + b.lng) / 2 };
state.midpoint = midpoint;
// Show loading state immediately — user sees feedback during API calls
document.getElementById('map-section').hidden = false;
document.getElementById('results-section').hidden = false;
document.getElementById('results-header').textContent = 'Searching…';
document.getElementById('results-list').innerHTML = '<div class="search-loading">Finding restaurants in the middle…</div>';
// Clear map layers and recenter (map was initialized once at startup)
clearMapLayers();
state.map.flyTo({ center: [midpoint.lng, midpoint.lat], zoom: 12 });
const routeData = await getRouteData(a, b);
state.midpoint = routeData.midpoint;
const routePolyline = routeData.polyline || null;
state.routePoints = routePolyline || [];
// Results and radius are returned by the route action (searches run server-side).
const raw = routeData.results || [];
const radiusKm = routeData.radiusKm;
// Bounding box from the trimmed route extent plus both endpoints.
// Using the route (not just A and B) prevents clipping on routes where
// the endpoints share a similar lat/lng (e.g. NJ→Pittsburgh curves north).
const routeLats = routeData.trimmedPolyline.map(p => p.lat);
const routeLngs = routeData.trimmedPolyline.map(p => p.lng);
const minLat = Math.min(a.lat, b.lat, ...routeLats);
const maxLat = Math.max(a.lat, b.lat, ...routeLats);
const minLng = Math.min(a.lng, b.lng, ...routeLngs);
const maxLng = Math.max(a.lng, b.lng, ...routeLngs);
// Zone: buffer the trimmed road path, clipped to route bounding box.
const bboxPoly = turf.bboxPolygon([minLng, minLat, maxLng, maxLat]);
const zoneBuffer = turf.buffer(
turf.lineString(routeData.trimmedPolyline.map(p => [p.lng, p.lat])),
radiusKm, { units: 'kilometers', steps: 32 }
);
const zoneGeoJSON = turf.intersect(zoneBuffer, bboxPoly) || zoneBuffer;
const inBounds = raw.filter(r => {
const { lat, lng } = r.geometry.location;
return lat >= minLat && lat <= maxLat && lng >= minLng && lng <= maxLng;
});
state.allResults = inBounds;
// Pre-compute distances so sort and render don't repeat haversine calls
inBounds.forEach(r => {
const rLat = r.geometry.location.lat;
const rLng = r.geometry.location.lng;
r._dA = haversineKm(a.lat, a.lng, rLat, rLng);
r._dB = haversineKm(b.lat, b.lng, rLat, rLng);
r._dMidpoint = haversineKm(state.midpoint.lat, state.midpoint.lng, rLat, rLng);
});
const displayResults = applySort(applyFilters(inBounds));
const applyMapLayers = () => {
drawLocationShades(state.map, a, b);
if (routePolyline) drawRoute(state.map, routePolyline);
drawZone(state.map, zoneGeoJSON);
addMarkers(state.map, a, b, displayResults);
updateBiasMarker(state.routePoints);
};
if (state.map && state.map.isStyleLoaded()) applyMapLayers();
else if (state.map) state.map.once('load', applyMapLayers);
renderResults(displayResults, a, b);
} catch (err) {
console.error(err);
document.getElementById('map-section').hidden = false;
document.getElementById('results-section').hidden = false;
if (err.noRoute) {
document.getElementById('results-header').textContent = 'No driveable route found between these locations.';
document.getElementById('results-list').innerHTML = '';
// Still show the two pins so the user can see what was searched
const map = state.map || initMap({ lat: (a.lat + b.lat) / 2, lng: (a.lng + b.lng) / 2 });
const showPins = () => { placeMarker(state.map, a.lat, a.lng, 'marker-a', 'You: ' + a.name); placeMarker(state.map, b.lat, b.lng, 'marker-b', 'Friend: ' + b.name); state.map.fitBounds([[a.lng, a.lat], [b.lng, b.lat]], { padding: 70 }); };
if (state.map && state.map.isStyleLoaded()) showPins(); else if (state.map) state.map.once('load', showPins);
} else {
document.getElementById('results-header').textContent = 'Search failed — please try again.';
document.getElementById('results-list').innerHTML = '';
}
} finally {
state.searching = false;
searchBtn.disabled = false;
updateControls();
}
}
searchBtn.addEventListener('click', runSearch);
// --- Location determination ---
async function determineUserLocation() {
return new Promise((resolve) => {
if (!navigator.geolocation) {
console.log('[LOCATION] Geolocation API not available, trying IP-based lookup');
fetchIPLocation()
.then(loc => {
console.log('[LOCATION] ✓ Using IP-based location:', loc);
resolve(loc);
})
.catch(() => {
console.log('[LOCATION] ✗ IP lookup failed, using hardcoded Toronto fallback');
resolve({ lat: 43.8, lng: -79.3 });
});
return;
}
const geolocationTimeout = setTimeout(() => {
console.log('[LOCATION] Browser geolocation timeout (5s), trying IP-based lookup');
fetchIPLocation()
.then(loc => {
console.log('[LOCATION] ✓ Using IP-based location:', loc);
resolve(loc);
})
.catch(() => {
console.log('[LOCATION] ✗ IP lookup failed, using hardcoded Toronto fallback');
resolve({ lat: 43.8, lng: -79.3 });
});
}, 5000);
navigator.geolocation.getCurrentPosition(
(pos) => {
clearTimeout(geolocationTimeout);
const loc = { lat: pos.coords.latitude, lng: pos.coords.longitude };
console.log('[LOCATION] ✓ Using browser geolocation (GPS/precise):', loc);
resolve(loc);
},
(err) => {
clearTimeout(geolocationTimeout);
console.log('[LOCATION] Browser geolocation denied or error:', err.code, err.message);
console.log('[LOCATION] Trying IP-based lookup as fallback');
fetchIPLocation()
.then(loc => {
console.log('[LOCATION] ✓ Using IP-based location:', loc);
resolve(loc);
})
.catch(() => {
console.log('[LOCATION] ✗ IP lookup failed, using hardcoded Toronto fallback');
resolve({ lat: 43.8, lng: -79.3 });
});
}
);
});
}
async function fetchIPLocation() {
try {
const res = await fetch('api.php?action=mylocation');
const data = await res.json();
if (data.lat && data.lng) {
console.log('[IP-API] Got location:', { lat: data.lat, lng: data.lng, city: data.city, isp: data.isp });
return { lat: data.lat, lng: data.lng };
} else {
console.log('[IP-API] No lat/lng in response:', data);
throw new Error('Invalid IP location response');
}
} catch (err) {
console.error('[IP-API] Fetch or parse error:', err.message);
throw err;
}
}
function drawNearMeCircle(map, lat, lng, radiusKm) {
if (map.getSource('nearbyme-circle')) {
map.getSource('nearbyme-circle').setData(makeCircleGeoJSON(lat, lng, radiusKm));
return;
}
const geojson = makeCircleGeoJSON(lat, lng, radiusKm);
map.addSource('nearbyme-circle', { type: 'geojson', data: geojson });
map.addLayer({
id: 'nearbyme-circle-fill',
type: 'fill',
source: 'nearbyme-circle',
paint: { 'fill-color': '#ec4899', 'fill-opacity': 0.08 },
});
map.addLayer({
id: 'nearbyme-circle-border',
type: 'line',
source: 'nearbyme-circle',
paint: { 'line-color': '#ec4899', 'line-width': 2 },
});
}
function makeCircleGeoJSON(lat, lng, radiusKm) {
const points = [];
const numSegments = 64;
for (let i = 0; i < numSegments; i++) {
const angle = (i / numSegments) * 2 * Math.PI;
const dx = radiusKm * Math.cos(angle);
const dy = radiusKm * Math.sin(angle);
const latOffset = dy / 111.0;
const lngOffset = dx / (111.0 * Math.cos(lat * Math.PI / 180));
points.push([lng + lngOffset, lat + latOffset]);
}
points.push(points[0]);
return {
type: 'Feature',
geometry: { type: 'Polygon', coordinates: [points] },
};
}
function removeNearMeCircle(map) {
if (!map) return;
if (map.getLayer('nearbyme-circle-fill')) map.removeLayer('nearbyme-circle-fill');
if (map.getLayer('nearbyme-circle-border')) map.removeLayer('nearbyme-circle-border');
if (map.getSource('nearbyme-circle')) map.removeSource('nearbyme-circle');
}
function removeRouteLayers(map) {
if (!map) return;
if (map.getLayer('route-line')) map.removeLayer('route-line');
if (map.getSource('route')) map.removeSource('route');
if (map.getLayer('zone-fill')) map.removeLayer('zone-fill');
if (map.getLayer('zone-border')) map.removeLayer('zone-border');
if (map.getSource('zone')) map.removeSource('zone');
}
async function runNearMeSearch(lat, lng, setNearMeMode = true) {
const nearmeBtn = document.getElementById('nearbyme-btn');
if (state.searching) return;
removeRouteLayers(state.map);
state.searching = true;
if (setNearMeMode) {
state.nearMeMode = true;
if (nearmeBtn) nearmeBtn.innerHTML = '<span class="material-icons">hourglass_empty</span>';
// Hide distance slider in near-me mode (only one location, no bias needed)
const biasSlider = document.getElementById('distance-bias');
if (biasSlider) biasSlider.style.display = 'none';
}
try {
document.getElementById('map-section').hidden = false;
document.getElementById('results-section').hidden = false;
document.getElementById('results-header').textContent = 'Searching…';
document.getElementById('results-list').innerHTML = '<div class="search-loading">Finding nearby restaurants…</div>';
// Clear map layers and recenter
clearMapLayers();
state.map.flyTo({ center: [lng, lat], zoom: 12 });
const res = await fetch(`api.php?action=nearbyme&lat=${lat}&lng=${lng}`);
const data = await res.json();
console.log('nearbyme API response:', data);
if (data.error) throw new Error(data.error);
const results = data.results || [];
console.log('Found', results.length, 'restaurants');
if (results.length > 0) {
const priceLevels = results.map(r => r.price_level).filter(p => p !== null);
console.log('Price levels found:', new Set(priceLevels), 'distribution:', priceLevels.reduce((acc, p) => {acc[p] = (acc[p]||0)+1; return acc}, {}));
}
state.allResults = results;
const radiusKm = 5;
results.forEach(r => {
const rLat = r.geometry.location.lat;
const rLng = r.geometry.location.lng;
r._dA = haversineKm(lat, lng, rLat, rLng);
r._dB = 0;
r._dMidpoint = haversineKm(lat, lng, rLat, rLng);
});
state.midpoint = { lat, lng };
const displayResults = applySort(applyFilters(results));