-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
685 lines (611 loc) · 22.9 KB
/
Copy pathscript.js
File metadata and controls
685 lines (611 loc) · 22.9 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
const storageKey = "geogrub.mvp.plan";
const weatherApiBase = "https://api.weather.gov";
const marketCenters = {
"austin": [30.2672, -97.7431],
"austin, tx": [30.2672, -97.7431],
"seattle": [47.6062, -122.3321],
"seattle, wa": [47.6062, -122.3321],
"atlanta": [33.749, -84.388],
"atlanta, ga": [33.749, -84.388],
"new york": [40.7128, -74.006],
"new york city": [40.7128, -74.006],
"los angeles": [34.0522, -118.2437],
"la": [34.0522, -118.2437],
"seoul": [37.5665, 126.978],
"seoul, korea": [37.5665, 126.978]
};
const seedPlan = {
name: "Weekend taco route",
market: "Austin, TX",
vendor: "tacos",
daypart: "lunch",
weatherTolerance: 6,
locations: [
{
id: crypto.randomUUID(),
name: "Mueller market lawn",
cue: "Family weekend demand, nearby parks, low direct competition before noon.",
event: 86,
access: 82,
weather: 81,
competition: 72,
permit: 74,
lat: 30.2983,
lng: -97.7045
},
{
id: crypto.randomUUID(),
name: "Rainey Street edge",
cue: "Live music spillover, hotel foot traffic, strong late-evening appetite.",
event: 92,
access: 78,
weather: 72,
competition: 64,
permit: 54,
lat: 30.2587,
lng: -97.7381
},
{
id: crypto.randomUUID(),
name: "UT west campus",
cue: "Dense student audience, walkable blocks, strong study-break behavior.",
event: 74,
access: 88,
weather: 69,
competition: 58,
permit: 62,
lat: 30.2849,
lng: -97.7419
}
]
};
const vendorModifiers = {
tacos: { label: "Street tacos", event: 1.05, access: 1, weather: 0.95, competition: 0.92, permit: 1 },
coffee: { label: "Mobile coffee", event: 0.9, access: 1.08, weather: 1.03, competition: 0.98, permit: 1 },
dessert: { label: "Dessert cart", event: 1.08, access: 0.96, weather: 1, competition: 0.95, permit: 1 },
retail: { label: "Maker goods", event: 1, access: 0.92, weather: 0.94, competition: 1.08, permit: 1.04 }
};
const daypartModifiers = {
lunch: { label: "Lunch rush", event: 0.92, access: 1.08, weather: 1, competition: 1, permit: 1, times: ["11:00a", "12:15p", "1:30p"] },
evening: { label: "Evening event", event: 1.1, access: 0.98, weather: 0.96, competition: 0.98, permit: 1, times: ["5:00p", "6:45p", "8:15p"] },
weekend: { label: "Weekend market", event: 1.06, access: 1, weather: 1.02, competition: 1, permit: 1.02, times: ["9:30a", "12:00p", "3:00p"] }
};
let plan = normalizePlan(loadPlan());
let rebalanceOffset = 0;
let selectedLocationId = null;
let draftPoint = null;
let map = null;
let markerLayer = null;
let draftMarker = null;
let locationMarkers = new Map();
const els = {
navPills: document.querySelectorAll(".nav-pill"),
views: document.querySelectorAll(".view"),
planName: document.querySelector("#planName"),
marketName: document.querySelector("#marketName"),
vendor: document.querySelector("#vendor"),
daypart: document.querySelector("#daypart"),
weatherTolerance: document.querySelector("#weatherTolerance"),
weatherValue: document.querySelector("#weatherValue"),
savePlanBtn: document.querySelector("#savePlanBtn"),
resetBtn: document.querySelector("#resetBtn"),
rebalanceBtn: document.querySelector("#rebalanceBtn"),
mapTitle: document.querySelector("#mapTitle"),
avgScore: document.querySelector("#avgScore"),
mapCanvas: document.querySelector("#mapCanvas"),
mapStatus: document.querySelector("#mapStatus"),
zoomInBtn: document.querySelector("#zoomInBtn"),
zoomOutBtn: document.querySelector("#zoomOutBtn"),
centerMapBtn: document.querySelector("#centerMapBtn"),
locations: document.querySelector("#locations"),
candidateCount: document.querySelector("#candidateCount"),
candidateForm: document.querySelector("#candidateForm"),
candidateName: document.querySelector("#candidateName"),
candidateCue: document.querySelector("#candidateCue"),
coordinateReadout: document.querySelector("#coordinateReadout"),
clearDraftBtn: document.querySelector("#clearDraftBtn"),
weatherStatus: document.querySelector("#weatherStatus"),
refreshWeatherBtn: document.querySelector("#refreshWeatherBtn"),
eventScore: document.querySelector("#eventScore"),
accessScore: document.querySelector("#accessScore"),
weatherScore: document.querySelector("#weatherScore"),
competitionScore: document.querySelector("#competitionScore"),
permitScore: document.querySelector("#permitScore"),
routeTitle: document.querySelector("#routeTitle"),
schedule: document.querySelector("#schedule"),
copyRouteBtn: document.querySelector("#copyRouteBtn"),
reportTitle: document.querySelector("#reportTitle"),
reportOutput: document.querySelector("#reportOutput"),
downloadReportBtn: document.querySelector("#downloadReportBtn")
};
function loadPlan() {
try {
const saved = JSON.parse(localStorage.getItem(storageKey));
return saved?.locations?.length ? saved : structuredClone(seedPlan);
} catch {
return structuredClone(seedPlan);
}
}
function normalizePlan(rawPlan) {
const fallbackCenter = getMarketCenter(rawPlan.market || seedPlan.market);
return {
...rawPlan,
locations: rawPlan.locations.map((location, index) => {
if (Number.isFinite(location.lat) && Number.isFinite(location.lng)) return location;
const offset = (index + 1) * 0.012;
return {
...location,
lat: fallbackCenter[0] + offset,
lng: fallbackCenter[1] - offset
};
})
};
}
function savePlan() {
localStorage.setItem(storageKey, JSON.stringify(plan));
}
function getMarketCenter(market) {
const key = String(market || "").trim().toLowerCase();
return marketCenters[key] || marketCenters.austin;
}
function syncPlanFromInputs() {
const previousMarket = plan.market;
plan.name = els.planName.value.trim() || "Untitled GeoGrub plan";
plan.market = els.marketName.value.trim() || "Custom market";
plan.vendor = els.vendor.value;
plan.daypart = els.daypart.value;
plan.weatherTolerance = Number(els.weatherTolerance.value);
if (map && previousMarket !== plan.market && marketCenters[plan.market.toLowerCase()]) {
map.setView(getMarketCenter(plan.market), 13);
}
}
function hydrateInputs() {
els.planName.value = plan.name;
els.marketName.value = plan.market;
els.vendor.value = plan.vendor;
els.daypart.value = plan.daypart;
els.weatherTolerance.value = plan.weatherTolerance;
els.weatherValue.textContent = plan.weatherTolerance;
}
function clampScore(value) {
return Math.max(0, Math.min(99, Math.round(value)));
}
function formatLatLng(point) {
return `${point.lat.toFixed(5)}, ${point.lng.toFixed(5)}`;
}
function parseWindMph(windSpeed) {
const matches = String(windSpeed || "").match(/\d+/g);
if (!matches) return 0;
return Math.max(...matches.map(Number));
}
function calculateWeatherFit(period) {
let score = 100;
const precipChance = Number(period.probabilityOfPrecipitation?.value ?? 0);
const wind = parseWindMph(period.windSpeed);
const temp = Number(period.temperature ?? 70);
const forecast = String(period.shortForecast || "").toLowerCase();
score -= precipChance * 0.45;
score -= Math.max(0, wind - 12) * 0.9;
score -= Math.max(0, 45 - temp) * 1.1;
score -= Math.max(0, temp - 92) * 1.2;
if (forecast.includes("thunder")) score -= 20;
if (forecast.includes("rain") || forecast.includes("showers")) score -= 12;
if (forecast.includes("snow") || forecast.includes("sleet") || forecast.includes("ice")) score -= 24;
if (forecast.includes("fog")) score -= 7;
return clampScore(score);
}
function weatherSummary(period) {
const precipChance = Number(period.probabilityOfPrecipitation?.value ?? 0);
return `${period.shortForecast || "Forecast"} · ${period.temperature}F · wind ${period.windSpeed || "n/a"} · precip ${precipChance}%`;
}
async function fetchWeatherFit(point) {
els.weatherStatus.textContent = "Fetching live weather...";
els.refreshWeatherBtn.disabled = true;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 8000);
try {
const pointResponse = await fetch(`${weatherApiBase}/points/${point.lat.toFixed(4)},${point.lng.toFixed(4)}`, {
headers: { "Accept": "application/geo+json" },
signal: controller.signal
});
if (!pointResponse.ok) throw new Error(`Point lookup failed: ${pointResponse.status}`);
const pointData = await pointResponse.json();
const hourlyUrl = pointData.properties?.forecastHourly;
if (!hourlyUrl) throw new Error("Hourly forecast unavailable");
const hourlyResponse = await fetch(hourlyUrl, {
headers: { "Accept": "application/geo+json" },
signal: controller.signal
});
if (!hourlyResponse.ok) throw new Error(`Hourly forecast failed: ${hourlyResponse.status}`);
const hourlyData = await hourlyResponse.json();
const period = hourlyData.properties?.periods?.[0];
if (!period) throw new Error("Hourly period unavailable");
const fit = calculateWeatherFit(period);
const summary = weatherSummary(period);
draftPoint = {
...draftPoint,
weatherFit: fit,
weatherSummary: summary
};
els.weatherScore.value = fit;
els.weatherStatus.textContent = `Weather fit ${fit}/99 · ${summary}`;
} catch (error) {
els.weatherStatus.textContent = "Weather unavailable. You can still set Weather fit manually.";
} finally {
clearTimeout(timeoutId);
els.refreshWeatherBtn.disabled = false;
}
}
function scoreLocation(location) {
const vendor = vendorModifiers[plan.vendor];
const daypart = daypartModifiers[plan.daypart];
const weatherWeight = 0.1 + plan.weatherTolerance / 50;
const raw =
location.event * 0.31 * vendor.event * daypart.event +
location.access * 0.2 * vendor.access * daypart.access +
location.weather * weatherWeight * vendor.weather * daypart.weather +
(100 - location.competition) * 0.15 * vendor.competition * daypart.competition +
location.permit * 0.16 * vendor.permit * daypart.permit +
rebalanceOffset;
return clampScore(raw);
}
function scoreDrivers(location) {
const risks = [];
const strengths = [];
if (location.event >= 80) strengths.push("strong event demand");
if (location.access >= 80) strengths.push("easy access");
if (location.weather >= 75) strengths.push("weather-resilient setup");
if (location.permit < 60) risks.push("permit follow-up needed");
if (location.competition > 72) risks.push("high competition");
if (location.weather < 62) risks.push("weather exposure");
return { strengths, risks };
}
function rankedLocations() {
return plan.locations
.map((location) => ({ ...location, score: scoreLocation(location), drivers: scoreDrivers(location) }))
.sort((a, b) => b.score - a.score);
}
function riskLabel(location) {
if (location.permit < 60) return "permit check";
if (location.competition > 72) return "crowded field";
if (location.weather < 62) return "weather watch";
return "clean fit";
}
function recommendation(location, index) {
const times = daypartModifiers[plan.daypart].times;
const time = times[index] || times[times.length - 1];
const lead = location.score >= 78 ? "Prioritize" : location.score >= 68 ? "Test" : "Back up";
return {
time,
text: `${lead} ${location.name}. ${location.cue} Watch ${riskLabel(location)} before committing inventory.`
};
}
function initMap() {
if (!window.L) {
els.mapCanvas.innerHTML = '<div class="map-fallback">Map tiles could not load. Check your network connection and reload.</div>';
els.mapStatus.textContent = "Map provider unavailable.";
return;
}
map = L.map("mapCanvas", {
zoomControl: false,
scrollWheelZoom: true
}).setView(getMarketCenter(plan.market), 13);
L.control.zoom({ position: "bottomleft" }).addTo(map);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
maxZoom: 19,
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(map);
markerLayer = L.layerGroup().addTo(map);
map.on("click", (event) => setDraftPoint(event.latlng));
}
function fitMapToLocations() {
if (!map || !plan.locations.length) return;
const bounds = L.latLngBounds(plan.locations.map((location) => [location.lat, location.lng]));
map.fitBounds(bounds.pad(0.22), { maxZoom: 14 });
}
function markerHtml(location, index) {
return `
<button class="real-map-marker ${location.id === selectedLocationId ? "selected" : ""}" type="button">
<span>${index + 1}</span>
<strong>${location.score}</strong>
</button>
`;
}
function renderMap(ranked) {
if (!map || !markerLayer) return;
markerLayer.clearLayers();
locationMarkers = new Map();
ranked.forEach((location, index) => {
const marker = L.marker([location.lat, location.lng], {
icon: L.divIcon({
className: "geogrub-marker-wrap",
html: markerHtml(location, index),
iconSize: [52, 52],
iconAnchor: [26, 46],
popupAnchor: [0, -44]
})
});
marker.bindPopup(`
<strong>${escapeHtml(location.name)}</strong>
<p>${escapeHtml(location.cue)}</p>
<small>Fit ${location.score}/99 · ${formatLatLng(location)}</small>
`);
marker.on("click", () => focusLocation(location.id));
marker.addTo(markerLayer);
locationMarkers.set(location.id, marker);
});
renderDraftMarker();
}
function setDraftPoint(latlng) {
draftPoint = { lat: latlng.lat, lng: latlng.lng };
els.coordinateReadout.textContent = `Map point: ${formatLatLng(draftPoint)}`;
els.mapStatus.textContent = `Next candidate will be placed at ${formatLatLng(draftPoint)}.`;
renderDraftMarker();
fetchWeatherFit(draftPoint);
}
function renderDraftMarker() {
if (!map) return;
if (draftMarker) {
draftMarker.remove();
draftMarker = null;
}
if (!draftPoint) {
els.coordinateReadout.textContent = "Map point: auto";
return;
}
draftMarker = L.marker([draftPoint.lat, draftPoint.lng], {
icon: L.divIcon({
className: "draft-marker-wrap",
html: '<span class="draft-real-marker"></span>',
iconSize: [30, 42],
iconAnchor: [15, 36]
})
}).addTo(map);
}
function renderLocations(ranked) {
els.locations.innerHTML = ranked
.map(
(location, index) => `
<article class="location-card ${location.id === selectedLocationId ? "selected" : ""}">
<span class="rank">${index + 1}</span>
<div>
<h3>${escapeHtml(location.name)}</h3>
<p>${escapeHtml(location.cue)}</p>
<div class="driver-row">
<span>Event ${location.event}</span>
<span>Access ${location.access}</span>
<span>Weather ${location.weather}</span>
<span>Comp ${location.competition}</span>
<span>Permit ${location.permit}</span>
${location.weatherSummary ? `<span>${escapeHtml(location.weatherSummary)}</span>` : ""}
<span>${formatLatLng(location)}</span>
</div>
</div>
<div class="metric-stack">
<span class="fit-score">${location.score}</span>
<span class="risk">${riskLabel(location)}</span>
<button type="button" data-focus="${location.id}">Map</button>
<button type="button" data-remove="${location.id}">Remove</button>
</div>
</article>
`
)
.join("");
}
function renderRoute(ranked) {
els.routeTitle.textContent = `${plan.name} schedule`;
els.schedule.innerHTML = ranked
.map((location, index) => {
const rec = recommendation(location, index);
return `
<li>
<span class="time">${rec.time}</span>
<span class="stop">
<strong>${escapeHtml(location.name)}</strong>
<span>${escapeHtml(rec.text)}</span>
</span>
</li>
`;
})
.join("");
}
function buildReport(ranked) {
const best = ranked[0];
const avg = ranked.length
? Math.round(ranked.reduce((total, location) => total + location.score, 0) / ranked.length)
: 0;
return `# GeoGrub Plan: ${plan.name}
Market: ${plan.market}
Vendor: ${vendorModifiers[plan.vendor].label}
Selling window: ${daypartModifiers[plan.daypart].label}
Average fit score: ${avg}
## Recommendation
${best ? `Start with ${best.name} (${best.score}/99). ${best.cue}` : "Add at least one candidate location to generate a recommendation."}
## Ranked Locations
${ranked
.map((location, index) => {
const rec = recommendation(location, index);
const strengths = location.drivers.strengths.join(", ") || "balanced fundamentals";
const risks = location.drivers.risks.join(", ") || "no major red flags";
return `${index + 1}. ${location.name} - ${location.score}/99
- Coordinates: ${formatLatLng(location)}
- Weather: ${location.weatherSummary || "Manual weather score"}
- Best time: ${rec.time}
- Strengths: ${strengths}
- Risks: ${risks}
- Action: ${rec.text}`;
})
.join("\n\n")}
## Scoring Model
GeoGrub weights event demand, access, weather fit, competition pressure, and permit readiness. Competition is inverted, so lower competition improves the score. Vendor type, selling window, and weather tolerance adjust the final fit score.
`;
}
function renderReport(ranked) {
els.reportTitle.textContent = `${plan.name} report`;
els.reportOutput.value = buildReport(ranked);
}
function render() {
syncPlanFromInputs();
els.weatherValue.textContent = plan.weatherTolerance;
const ranked = rankedLocations();
const avg = ranked.length
? Math.round(ranked.reduce((total, location) => total + location.score, 0) / ranked.length)
: 0;
els.mapTitle.textContent = `${plan.market} pop-up plan`;
els.avgScore.textContent = avg;
els.candidateCount.textContent = `${plan.locations.length} stop${plan.locations.length === 1 ? "" : "s"}`;
renderMap(ranked);
renderLocations(ranked);
renderRoute(ranked);
renderReport(ranked);
}
function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, (char) => ({
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
})[char]);
}
function addCandidate(event) {
event.preventDefault();
const marketCenter = getMarketCenter(plan.market);
const fallbackCenter = map ? map.getCenter() : { lat: marketCenter[0], lng: marketCenter[1] };
const point = draftPoint || { lat: fallbackCenter.lat, lng: fallbackCenter.lng };
plan.locations.push({
id: crypto.randomUUID(),
name: els.candidateName.value.trim(),
cue: els.candidateCue.value.trim(),
event: Number(els.eventScore.value),
access: Number(els.accessScore.value),
weather: Number(els.weatherScore.value),
competition: Number(els.competitionScore.value),
permit: Number(els.permitScore.value),
lat: point.lat,
lng: point.lng,
weatherSummary: draftPoint?.weatherSummary || "Manual weather score"
});
draftPoint = null;
els.candidateForm.reset();
savePlan();
render();
}
function focusLocation(locationId) {
const location = plan.locations.find((item) => item.id === locationId);
if (!location || !map) return;
selectedLocationId = locationId;
map.setView([location.lat, location.lng], Math.max(map.getZoom(), 15));
els.mapStatus.textContent = `Focused ${location.name} at ${formatLatLng(location)}.`;
render();
locationMarkers.get(locationId)?.openPopup();
}
function centerMap() {
selectedLocationId = null;
if (plan.locations.length) {
fitMapToLocations();
} else if (map) {
map.setView(getMarketCenter(plan.market), 13);
}
els.mapStatus.textContent = "Map centered. Click a real location to place the next candidate.";
render();
}
function switchView(view) {
els.navPills.forEach((button) => button.classList.toggle("active", button.dataset.view === view));
els.views.forEach((panel) => panel.classList.toggle("active", panel.dataset.panel === view));
if (view === "plan" && map) {
setTimeout(() => map.invalidateSize(), 0);
}
}
function downloadReport() {
const blob = new Blob([els.reportOutput.value], { type: "text/markdown" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = `${plan.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "geogrub-plan"}.md`;
link.click();
URL.revokeObjectURL(url);
}
hydrateInputs();
initMap();
render();
fitMapToLocations();
[els.planName, els.vendor, els.daypart, els.weatherTolerance].forEach((field) => {
field.addEventListener("input", render);
field.addEventListener("change", render);
});
els.marketName.addEventListener("change", () => {
render();
if (map) map.setView(getMarketCenter(plan.market), 13);
});
els.marketName.addEventListener("input", render);
els.candidateForm.addEventListener("submit", addCandidate);
els.savePlanBtn.addEventListener("click", () => {
syncPlanFromInputs();
savePlan();
els.savePlanBtn.textContent = "Saved";
setTimeout(() => {
els.savePlanBtn.textContent = "Save plan";
}, 1200);
});
els.resetBtn.addEventListener("click", () => {
plan = normalizePlan(structuredClone(seedPlan));
rebalanceOffset = 0;
selectedLocationId = null;
draftPoint = null;
localStorage.removeItem(storageKey);
hydrateInputs();
els.weatherStatus.textContent = "Click the map to fetch weather for that location.";
render();
fitMapToLocations();
});
els.rebalanceBtn.addEventListener("click", () => {
rebalanceOffset = rebalanceOffset === 0 ? -4 : rebalanceOffset === -4 ? 5 : 0;
render();
});
els.locations.addEventListener("click", (event) => {
const focusButton = event.target.closest("[data-focus]");
if (focusButton) {
focusLocation(focusButton.dataset.focus);
return;
}
const button = event.target.closest("[data-remove]");
if (!button) return;
plan.locations = plan.locations.filter((location) => location.id !== button.dataset.remove);
if (selectedLocationId === button.dataset.remove) selectedLocationId = null;
savePlan();
render();
});
els.zoomInBtn.addEventListener("click", () => map?.zoomIn());
els.zoomOutBtn.addEventListener("click", () => map?.zoomOut());
els.centerMapBtn.addEventListener("click", centerMap);
els.clearDraftBtn.addEventListener("click", () => {
draftPoint = null;
els.mapStatus.textContent = "Draft point cleared. Click the real map to place the next candidate.";
els.weatherStatus.textContent = "Click the map to fetch weather for that location.";
renderDraftMarker();
});
els.refreshWeatherBtn.addEventListener("click", () => {
if (!draftPoint) {
els.weatherStatus.textContent = "Choose a map point first.";
return;
}
fetchWeatherFit(draftPoint);
});
els.navPills.forEach((button) => {
button.addEventListener("click", () => switchView(button.dataset.view));
});
els.copyRouteBtn.addEventListener("click", async () => {
const route = rankedLocations()
.map((location, index) => {
const rec = recommendation(location, index);
return `${rec.time} - ${location.name}: ${rec.text}`;
})
.join("\n");
await navigator.clipboard.writeText(route);
els.copyRouteBtn.textContent = "Copied";
setTimeout(() => {
els.copyRouteBtn.textContent = "Copy route";
}, 1200);
});
els.downloadReportBtn.addEventListener("click", downloadReport);