-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
457 lines (380 loc) · 14.7 KB
/
script.js
File metadata and controls
457 lines (380 loc) · 14.7 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
// Initialize the map — worldCopyJump wraps panning, maxBounds prevents white bars
const worldBounds = L.latLngBounds([[-90, -180], [90, 180]]);
const map = L.map('map', {
center: [20, 0],
zoom: 2,
maxZoom: 18,
maxBounds: worldBounds.pad(0.1),
maxBoundsViscosity: 1.0,
worldCopyJump: true
});
// Set minZoom so tiles always fill the viewport (recalculated on resize)
function updateMinZoom() {
const minZoom = map.getBoundsZoom(worldBounds, false);
map.setMinZoom(minZoom);
if (map.getZoom() < minZoom) {
map.setZoom(minZoom);
}
}
map.whenReady(updateMinZoom);
map.on('resize', updateMinZoom);
const lightTileLayer = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
attribution: '© OpenStreetMap © CartoDB',
subdomains: 'abcd',
maxZoom: 19
});
const darkTileLayer = L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
attribution: '© OpenStreetMap © CartoDB',
subdomains: 'abcd',
maxZoom: 19
});
let isDarkMode = true;
darkTileLayer.addTo(map);
let markers = [];
const geocodeCache = new Map();
// DOM elements
const locationInput = document.getElementById('locationInput');
const addPinsBtn = document.getElementById('addPinsBtn');
const clearPinsBtn = document.getElementById('clearPinsBtn');
const status = document.getElementById('status');
const themeToggle = document.getElementById('themeToggle');
const panelToggle = document.getElementById('panelToggle');
const controlsPanel = document.getElementById('controlsPanel');
const pinColorInput = document.getElementById('pinColor');
function hexToRgb(hex) {
const n = parseInt(hex.replace('#', ''), 16);
return `${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}`;
}
function createCustomIcon(size = 20) {
const color = pinColorInput.value;
const rgb = hexToRgb(color);
const customProps = `
--pin-color: ${color};
--pin-glow: rgba(${rgb}, 0.3);
`;
const darkStyles = `
background: rgba(${rgb}, 0.25);
border: 2px solid ${color};
box-shadow: 0 0 10px rgba(${rgb}, 0.3);
animation: markerPulse 3s ease-in-out infinite;
`;
const lightStyles = `
background: ${color};
border: 2px solid #ffffff;
box-shadow: 0 2px 8px rgba(${rgb}, 0.4);
`;
return L.divIcon({
className: 'custom-marker',
html: `<div style="
${customProps}
${isDarkMode ? darkStyles : lightStyles}
border-radius: 50%;
width: ${size}px;
height: ${size}px;
cursor: pointer;
"></div>`,
iconSize: [size, size],
iconAnchor: [size/2, size/2],
popupAnchor: [0, -size/2]
});
}
async function geocodeLocation(locationName) {
const normalizedName = locationName.trim().toLowerCase();
if (geocodeCache.has(normalizedName)) {
return geocodeCache.get(normalizedName);
}
const encodedLocation = encodeURIComponent(locationName.trim());
const url = `https://nominatim.openstreetmap.org/search?format=json&q=${encodedLocation}&limit=1&addressdetails=1`;
try {
const response = await fetch(url);
const data = await response.json();
const result = (data && data.length > 0)
? { name: data[0].display_name, lat: parseFloat(data[0].lat), lng: parseFloat(data[0].lon), success: true }
: { name: locationName, success: false, error: 'Location not found' };
geocodeCache.set(normalizedName, result);
return result;
} catch {
// Network errors are not cached so retries work
return { name: locationName, success: false, error: 'Network error' };
}
}
// Process locations in parallel batches with real-time visual updates
async function processLocationsInBatches(locations, batchSize = 3, onLocationProcessed) {
const results = [];
for (let i = 0; i < locations.length; i += batchSize) {
const batch = locations.slice(i, i + batchSize);
const batchPromises = batch.map(async (location, index) => {
const globalIndex = i + index;
updateStatus(`Processing ${globalIndex + 1}/${locations.length}: ${location.name}`, '');
const result = await geocodeLocation(location.name);
const processedItem = { location, result, index: globalIndex };
if (onLocationProcessed) {
onLocationProcessed(processedItem);
}
return processedItem;
});
const batchResults = await Promise.all(batchPromises);
results.push(...batchResults);
// Small delay between batches to be respectful to the API
if (i + batchSize < locations.length) {
await new Promise(resolve => setTimeout(resolve, 100));
}
}
return results;
}
// Add pins for locations
async function addPins() {
const inputText = locationInput.value.trim();
if (!inputText) {
updateStatus('Please enter some locations first.', 'error');
return;
}
// Split by comma, but rejoin parts that are within parentheses
// so value numbers like "1,234" don't break the location
const parts = inputText.split(',');
const locations = [];
let currentLocation = '';
let insideParentheses = false;
for (const part of parts) {
if (insideParentheses) {
// Continue accumulating inside parenthesized value
currentLocation += ',' + part;
} else {
// Start a new location segment
if (currentLocation.trim()) {
locations.push(currentLocation.trim());
}
currentLocation = part;
}
const openParens = (part.match(/\(/g) || []).length;
const closeParens = (part.match(/\)/g) || []).length;
if (openParens > closeParens) {
insideParentheses = true;
} else if (closeParens >= openParens) {
insideParentheses = false;
}
}
if (currentLocation.trim()) {
locations.push(currentLocation.trim());
}
const parsedLocations = locations.map(loc => {
const trimmed = loc.trim();
const match = trimmed.match(/^(.+?)\s*\(([0-9,]+)\)$/);
if (match) {
// Remove commas from the number and parse
const numberStr = match[2].replace(/,/g, '');
return {
name: match[1].trim(),
value: parseInt(numberStr, 10),
originalInput: trimmed
};
} else {
return {
name: trimmed,
value: null,
originalInput: trimmed
};
}
}).filter(loc => loc.name);
if (parsedLocations.length === 0) {
updateStatus('Please enter valid locations.', 'error');
return;
}
addPinsBtn.disabled = true;
addPinsBtn.innerHTML = 'Adding Pins <span class="loading-spinner"></span>';
updateStatus(`Geocoding ${parsedLocations.length} location(s)...`, '');
// Calculate size scaling for pins based on values
const values = parsedLocations.filter(loc => loc.value !== null).map(loc => loc.value);
const minValue = values.length > 0 ? Math.min(...values) : 0;
const maxValue = values.length > 0 ? Math.max(...values) : 0;
let successCount = 0;
let failedLocations = [];
const createMarkerForLocation = ({ location, result }) => {
if (result.success) {
const pinSize = calculatePinSize(location.value, minValue, maxValue);
const marker = L.marker([result.lat, result.lng], {
icon: createCustomIcon(pinSize)
}).addTo(map);
const valueText = location.value !== null ? ` (${location.value})` : '';
const popupContent = `
<div class="custom-popup">
<div class="popup-title">${location.name}${valueText}</div>
<div class="popup-subtitle">${result.name}</div>
</div>
`;
marker.bindPopup(popupContent, {
maxWidth: 300,
closeButton: true
});
marker.on('mouseover', function() {
this.openPopup();
});
marker.locationData = location;
markers.push(marker);
successCount++;
} else {
failedLocations.push(`${location.originalInput} (${result.error})`);
}
};
// Process locations with real-time visual feedback
await processLocationsInBatches(parsedLocations, 3, createMarkerForLocation);
if (markers.length > 0) {
const group = new L.featureGroup(markers);
map.fitBounds(group.getBounds().pad(0.1), { maxZoom: 6 });
}
let statusMessage = `Successfully added ${successCount} pin(s)`;
if (failedLocations.length > 0) {
statusMessage += `. Failed: ${failedLocations.join(', ')}`;
}
updateStatus(statusMessage, successCount > 0 ? 'success' : 'error');
addPinsBtn.disabled = false;
addPinsBtn.innerHTML = 'Add Pins';
}
function clearPins() {
markers.forEach(marker => map.removeLayer(marker));
markers = [];
updateStatus('All pins cleared.', 'success');
// Reset map view
map.setView([20, 0], 2);
}
function updateStatus(message, type = '') {
status.textContent = message;
status.className = `status ${type}`;
}
// Scale pin size between 12px (min) and 64px (max) based on relative value
function calculatePinSize(value, minValue = 0, maxValue = 100) {
if (value === null) return 24; // Default size for locations without values
const valueRange = maxValue - minValue || 1;
const minSize = 12;
const maxSize = 64;
const normalizedValue = (value - minValue) / valueRange;
return Math.round(minSize + (normalizedValue * (maxSize - minSize)));
}
// Destroy and recreate all markers with current theme/color settings
function rebuildMarkers() {
const existingMarkers = [...markers];
markers.forEach(marker => map.removeLayer(marker));
markers = [];
const allValues = existingMarkers
.map(m => m.locationData?.value)
.filter(v => v !== null && v !== undefined);
const minValue = allValues.length > 0 ? Math.min(...allValues) : 0;
const maxValue = allValues.length > 0 ? Math.max(...allValues) : 0;
existingMarkers.forEach(marker => {
const locationData = marker.locationData;
const value = locationData ? locationData.value : null;
const pinSize = calculatePinSize(value, minValue, maxValue);
const newMarker = L.marker(marker.getLatLng(), {
icon: createCustomIcon(pinSize)
}).addTo(map);
const popup = marker.getPopup();
if (popup) {
newMarker.bindPopup(popup.getContent(), {
maxWidth: 300,
closeButton: true
});
newMarker.on('mouseover', function() {
this.openPopup();
});
}
newMarker.locationData = locationData;
markers.push(newMarker);
});
}
function toggleTheme() {
isDarkMode = !isDarkMode;
document.body.classList.toggle('dark-mode');
if (isDarkMode) {
map.removeLayer(lightTileLayer);
darkTileLayer.addTo(map);
} else {
map.removeLayer(darkTileLayer);
lightTileLayer.addTo(map);
}
rebuildMarkers();
}
panelToggle.addEventListener('click', () => {
controlsPanel.classList.toggle('collapsed');
});
L.DomEvent.disableClickPropagation(controlsPanel);
L.DomEvent.disableScrollPropagation(controlsPanel);
// ---- Panel drag ----
(function initPanelDrag() {
const header = controlsPanel.querySelector('.panel-header');
let dragging = false, startX, startY, startLeft, startTop;
header.addEventListener('mousedown', (e) => {
// Ignore clicks on buttons inside the header
if (e.target.closest('button')) return;
dragging = true;
controlsPanel.classList.add('interacting');
const rect = controlsPanel.getBoundingClientRect();
const wrapperRect = controlsPanel.parentElement.getBoundingClientRect();
startX = e.clientX;
startY = e.clientY;
startLeft = rect.left - wrapperRect.left;
startTop = rect.top - wrapperRect.top;
e.preventDefault();
});
window.addEventListener('mousemove', (e) => {
if (!dragging) return;
const wrapperRect = controlsPanel.parentElement.getBoundingClientRect();
let newLeft = startLeft + (e.clientX - startX);
let newTop = startTop + (e.clientY - startY);
// Clamp within wrapper
newLeft = Math.max(0, Math.min(newLeft, wrapperRect.width - controlsPanel.offsetWidth));
newTop = Math.max(0, Math.min(newTop, wrapperRect.height - controlsPanel.offsetHeight));
controlsPanel.style.left = newLeft + 'px';
controlsPanel.style.top = newTop + 'px';
});
window.addEventListener('mouseup', () => {
if (dragging) {
dragging = false;
controlsPanel.classList.remove('interacting');
}
});
})();
// ---- Panel resize ----
(function initPanelResize() {
const handle = controlsPanel.querySelector('.panel-resize-handle');
let resizing = false, startX, startY, startW, startH;
handle.addEventListener('mousedown', (e) => {
resizing = true;
controlsPanel.classList.add('interacting');
startX = e.clientX;
startY = e.clientY;
startW = controlsPanel.offsetWidth;
startH = controlsPanel.offsetHeight;
e.preventDefault();
e.stopPropagation();
});
window.addEventListener('mousemove', (e) => {
if (!resizing) return;
const wrapperRect = controlsPanel.parentElement.getBoundingClientRect();
const panelLeft = controlsPanel.offsetLeft;
const panelTop = controlsPanel.offsetTop;
let newW = startW + (e.clientX - startX);
let newH = startH + (e.clientY - startY);
// Clamp to wrapper bounds
newW = Math.max(200, Math.min(newW, wrapperRect.width - panelLeft));
newH = Math.max(120, Math.min(newH, wrapperRect.height - panelTop));
controlsPanel.style.width = newW + 'px';
controlsPanel.style.height = newH + 'px';
});
window.addEventListener('mouseup', () => {
if (resizing) {
resizing = false;
controlsPanel.classList.remove('interacting');
}
});
})();
// Event listeners
pinColorInput.addEventListener('input', rebuildMarkers);
addPinsBtn.addEventListener('click', addPins);
clearPinsBtn.addEventListener('click', clearPins);
themeToggle.addEventListener('click', toggleTheme);
locationInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && e.ctrlKey) {
addPins();
}
});
updateStatus('Enter locations and click "Add Pins" to get started.', '');