-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathspecies-observation-map.html
644 lines (523 loc) · 18.5 KB
/
species-observation-map.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Species observation map</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.5.3/MarkerCluster.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.5.3/MarkerCluster.Default.css">
<style>
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 20px;
font-family: Helvetica, Arial, sans-serif;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
h1 {
margin-top: 0;
}
.search-panel {
display: flex;
flex-direction: column;
gap: 15px;
margin-bottom: 20px;
padding: 15px;
background-color: #f5f5f5;
border-radius: 5px;
}
.search-row {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: flex-end;
}
.search-group {
flex: 1;
min-width: 250px;
}
.search-group label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
.search-input {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
}
.days-input {
width: 80px;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
}
.search-button {
padding: 8px 16px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
.search-button:hover {
background-color: #45a049;
}
#map {
height: 600px;
border-radius: 5px;
border: 1px solid #ddd;
}
.autocomplete-container {
position: relative;
}
.autocomplete-results {
position: absolute;
z-index: 1000;
width: 100%;
max-height: 300px;
overflow-y: auto;
background-color: white;
border: 1px solid #ccc;
border-top: none;
border-radius: 0 0 4px 4px;
display: none;
}
.autocomplete-item {
padding: 8px 12px;
cursor: pointer;
border-bottom: 1px solid #eee;
}
.autocomplete-item:hover {
background-color: #f0f0f0;
}
.autocomplete-item-scientific {
font-style: italic;
color: #666;
font-size: 0.9em;
}
.loading {
text-align: center;
padding: 20px;
font-style: italic;
color: #666;
}
.observation-info {
line-height: 1.5;
}
.observation-info img {
max-width: 150px;
max-height: 150px;
margin-top: 10px;
border-radius: 4px;
}
.stats-panel {
margin-top: 15px;
padding: 15px;
background-color: #f5f5f5;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="container">
<h1>Species observation map</h1>
<div class="search-panel">
<div class="search-row">
<div class="search-group">
<label for="species-search">Search for a species:</label>
<div class="autocomplete-container">
<input type="text" id="species-search" class="search-input" placeholder="Enter species name (e.g., California Brown Pelican)">
<div id="autocomplete-results" class="autocomplete-results"></div>
</div>
</div>
<div class="search-group" style="flex: 0 0 auto;">
<label for="days-input">Sightings in the past</label>
<div style="display: flex; align-items: center;">
<input type="number" id="days-input" class="days-input" value="30" min="1" max="365">
<span style="margin-left: 5px;">days</span>
</div>
</div>
<div class="search-group" style="flex: 0 0 auto;">
<button id="search-button" class="search-button">Search</button>
</div>
</div>
<div id="taxon-details" style="display: none;">
<div id="selected-taxon-info"></div>
</div>
</div>
<div id="map"></div>
<div id="stats-panel" class="stats-panel" style="display: none;">
<h2>Observation statistics</h2>
<div id="stats-content"></div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.markercluster/1.5.3/leaflet.markercluster.min.js"></script>
<script type="module">
// Global variables
let map;
let markers;
let selectedTaxonId = null;
let selectedTaxonName = null;
// Initialize the map
function initMap() {
map = L.map('map').setView([20, 0], 2);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// Create marker cluster group with default settings
markers = L.markerClusterGroup({
disableClusteringAtZoom: 16,
spiderfyOnMaxZoom: true,
showCoverageOnHover: true,
zoomToBoundsOnClick: true,
maxClusterRadius: 80
});
map.addLayer(markers);
}
// Handle species search input
function setupSpeciesSearch() {
const searchInput = document.getElementById('species-search');
const resultsContainer = document.getElementById('autocomplete-results');
let debounceTimer;
searchInput.addEventListener('input', function() {
clearTimeout(debounceTimer);
const query = this.value.trim();
if (query.length < 2) {
resultsContainer.style.display = 'none';
return;
}
debounceTimer = setTimeout(() => {
fetchTaxaAutocomplete(query);
}, 300);
});
// Show results when input is focused
searchInput.addEventListener('focus', function() {
if (this.value.trim().length >= 2) {
resultsContainer.style.display = 'block';
}
});
// Click outside to close autocomplete
document.addEventListener('click', function(e) {
if (!searchInput.contains(e.target) && !resultsContainer.contains(e.target)) {
resultsContainer.style.display = 'none';
}
});
}
// Fetch taxa autocomplete results
async function fetchTaxaAutocomplete(query) {
const resultsContainer = document.getElementById('autocomplete-results');
resultsContainer.style.display = 'block';
resultsContainer.innerHTML = '<div class="loading">Searching...</div>';
try {
const response = await fetch(`https://api.inaturalist.org/v1/taxa/autocomplete?q=${encodeURIComponent(query)}&per_page=10`);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
displayAutocompleteResults(data.results);
} catch (error) {
console.error('Error fetching taxa:', error);
resultsContainer.innerHTML = '<div class="loading">Error fetching results</div>';
}
}
// Display autocomplete results
function displayAutocompleteResults(results) {
const resultsContainer = document.getElementById('autocomplete-results');
if (results.length === 0) {
resultsContainer.innerHTML = '<div class="loading">No results found</div>';
return;
}
resultsContainer.innerHTML = '';
results.forEach(taxon => {
const item = document.createElement('div');
item.className = 'autocomplete-item';
const commonName = taxon.preferred_common_name || '';
const scientificName = taxon.name || '';
let displayName = commonName;
if (commonName && scientificName) {
displayName = `${commonName} <span class="autocomplete-item-scientific">(${scientificName})</span>`;
} else if (scientificName) {
displayName = `<span class="autocomplete-item-scientific">${scientificName}</span>`;
}
item.innerHTML = displayName;
item.addEventListener('click', () => {
document.getElementById('species-search').value = commonName || scientificName;
resultsContainer.style.display = 'none';
selectTaxon(taxon);
});
resultsContainer.appendChild(item);
});
resultsContainer.style.display = 'block';
}
// Select a taxon from autocomplete
function selectTaxon(taxon) {
selectedTaxonId = taxon.id;
selectedTaxonName = taxon.preferred_common_name || taxon.name;
const detailsContainer = document.getElementById('taxon-details');
const infoContainer = document.getElementById('selected-taxon-info');
let content = `<strong>Selected: ${selectedTaxonName}</strong>`;
if (taxon.preferred_common_name && taxon.name && taxon.preferred_common_name !== taxon.name) {
content += ` <span style="font-style: italic;">(${taxon.name})</span>`;
}
infoContainer.innerHTML = content;
detailsContainer.style.display = 'block';
// Update URL with the selected taxon
updateUrlHash();
}
// Search for observations
async function searchObservations() {
if (!selectedTaxonId) {
alert('Please select a species first');
return;
}
const daysInput = document.getElementById('days-input');
const days = parseInt(daysInput.value);
if (isNaN(days) || days < 1) {
alert('Please enter a valid number of days');
return;
}
// Update URL with current search parameters
updateUrlHash();
// Calculate date range
const endDate = new Date();
const startDate = new Date();
startDate.setDate(startDate.getDate() - days);
const formattedStartDate = formatDate(startDate);
const formattedEndDate = formatDate(endDate);
console.log(`Searching for observations from ${formattedStartDate} to ${formattedEndDate}`);
// Clear previous markers
markers.clearLayers();
// Show loading state
const statsPanel = document.getElementById('stats-panel');
statsPanel.style.display = 'block';
const statsContent = document.getElementById('stats-content');
statsContent.innerHTML = '<div class="loading">Loading observations...</div>';
try {
// Fetch observations
await fetchObservationPages(formattedStartDate, formattedEndDate);
// Get the total number of markers
const totalMarkers = markers.getLayers().length;
console.log(`Total markers added: ${totalMarkers}`);
// If no markers were added, show a message
if (totalMarkers === 0) {
statsContent.innerHTML = `<p>No observations found for ${selectedTaxonName} in the past ${days} days.</p>`;
} else {
// Set map view to show all markers
const bounds = markers.getBounds();
if (bounds.isValid()) {
console.log(`Setting map bounds to: ${bounds.toBBoxString()}`);
map.fitBounds(bounds, { padding: [50, 50] });
} else {
console.log('Marker bounds not valid, keeping current view');
}
// Update stats
statsContent.innerHTML = `
<p>Found ${totalMarkers} observations of ${selectedTaxonName} in the past ${days} days.</p>
<p>Click on the markers to see observation details.</p>
`;
}
} catch (error) {
console.error('Error fetching observations:', error);
statsContent.innerHTML = '<p>Error loading observations. Please try again.</p>';
}
}
// Format date to YYYY-MM-DD
function formatDate(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
// Fetch observations (paginated)
async function fetchObservationPages(startDate, endDate, page = 1, totalFetched = 0) {
const perPage = 200; // Maximum per page
const url = `https://api.inaturalist.org/v1/observations?taxon_id=${selectedTaxonId}&d1=${startDate}&d2=${endDate}&per_page=${perPage}&page=${page}&return_bounds=true&order=desc&order_by=observed_on`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(`Fetched page ${page} with ${data.results.length} observations`);
// Add markers for each observation
let markersAdded = 0;
data.results.forEach(observation => {
if (addObservationMarker(observation)) {
markersAdded++;
}
});
console.log(`Added ${markersAdded} markers from page ${page}`);
const newTotalFetched = totalFetched + data.results.length;
// Update loading message
document.getElementById('stats-content').innerHTML = `<div class="loading">Loaded ${newTotalFetched} observations so far...</div>`;
// If there are more pages and we haven't hit our limit, fetch the next page
// Limit to max 1000 observations (5 pages) to avoid overwhelming the browser
if (data.page < data.total_pages && data.page < 5 && newTotalFetched < 1000) {
await fetchObservationPages(startDate, endDate, page + 1, newTotalFetched);
}
} catch (error) {
console.error('Error fetching observations page:', error);
throw error;
}
}
// Add a marker for an observation
function addObservationMarker(observation) {
// Skip observations without coordinates
if (!observation.geojson || !observation.geojson.coordinates) {
return false;
}
// Extract coordinates (API returns [lng, lat])
const lng = observation.geojson.coordinates[0];
const lat = observation.geojson.coordinates[1];
// Validate coordinates
if (!isFinite(lat) || !isFinite(lng) || lat === null || lng === null) {
console.log(`Invalid coordinates for observation ${observation.id}: [${lat}, ${lng}]`);
return false;
}
// Create marker
const marker = L.marker([lat, lng]);
// Create popup content
let popupContent = '<div class="observation-info">';
popupContent += `<strong>${selectedTaxonName}</strong><br>`;
popupContent += `Date: ${formatObservationDate(observation.observed_on)}<br>`;
if (observation.place_guess) {
popupContent += `Location: ${observation.place_guess}<br>`;
}
if (observation.user && observation.user.login) {
popupContent += `Observer: ${observation.user.name || observation.user.login}<br>`;
}
// Quality grade
const qualityGrade = observation.quality_grade || 'unknown';
popupContent += `Quality: ${qualityGrade.charAt(0).toUpperCase() + qualityGrade.slice(1)}<br>`;
// Add link to observation
popupContent += `<a href="https://www.inaturalist.org/observations/${observation.id}" target="_blank">View on iNaturalist</a><br>`;
// Add photo if available
if (observation.photos && observation.photos.length > 0 && observation.photos[0].url) {
popupContent += `<img src="${observation.photos[0].url}" alt="Observation photo">`;
}
popupContent += '</div>';
// Set popup
marker.bindPopup(popupContent);
// Add to marker cluster
markers.addLayer(marker);
return true;
}
// Format observation date
function formatObservationDate(dateString) {
if (!dateString) return 'Unknown';
const date = new Date(dateString);
return date.toLocaleDateString();
}
// Update URL hash with current state
function updateUrlHash() {
const days = document.getElementById('days-input').value;
if (selectedTaxonId && selectedTaxonName) {
const stateObj = {
taxonId: selectedTaxonId,
taxonName: selectedTaxonName,
days: days
};
const hashValue = encodeURIComponent(JSON.stringify(stateObj));
// Use history API to update URL without reloading the page
history.pushState(stateObj, '', `#${hashValue}`);
}
}
// Load state from URL hash
async function loadStateFromHash() {
const hash = window.location.hash;
if (hash && hash.length > 1) {
try {
const decodedHash = decodeURIComponent(hash.slice(1));
const stateObj = JSON.parse(decodedHash);
if (stateObj && stateObj.taxonId && stateObj.taxonName && stateObj.days) {
console.log('Loading state from URL hash:', stateObj);
// Set days input
document.getElementById('days-input').value = stateObj.days;
// Set the species search input
document.getElementById('species-search').value = stateObj.taxonName;
// Set the taxon details
selectedTaxonId = stateObj.taxonId;
selectedTaxonName = stateObj.taxonName;
const detailsContainer = document.getElementById('taxon-details');
const infoContainer = document.getElementById('selected-taxon-info');
infoContainer.innerHTML = `<strong>Selected: ${stateObj.taxonName}</strong>`;
detailsContainer.style.display = 'block';
// Search for observations
await searchObservations();
}
} catch (error) {
console.error('Error parsing hash state:', error);
}
}
}
// Handle browser navigation events
window.addEventListener('popstate', async (event) => {
if (event.state) {
// Load state from the history state object
selectedTaxonId = event.state.taxonId;
selectedTaxonName = event.state.taxonName;
document.getElementById('days-input').value = event.state.days;
document.getElementById('species-search').value = event.state.taxonName;
const detailsContainer = document.getElementById('taxon-details');
const infoContainer = document.getElementById('selected-taxon-info');
infoContainer.innerHTML = `<strong>Selected: ${event.state.taxonName}</strong>`;
detailsContainer.style.display = 'block';
await searchObservations();
} else {
// Reset state if no state in history
selectedTaxonId = null;
selectedTaxonName = null;
document.getElementById('species-search').value = '';
document.getElementById('days-input').value = '30';
document.getElementById('taxon-details').style.display = 'none';
markers.clearLayers();
document.getElementById('stats-panel').style.display = 'none';
}
});
// Initialize
document.addEventListener('DOMContentLoaded', async () => {
initMap();
setupSpeciesSearch();
// Add event listener to search button
document.getElementById('search-button').addEventListener('click', searchObservations);
// Allow pressing Enter in the days input to search
document.getElementById('days-input').addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
searchObservations();
}
});
// Load state from URL hash
await loadStateFromHash();
});
// Handle direct lookup of a taxon by ID
async function lookupTaxonById(taxonId) {
try {
const response = await fetch(`https://api.inaturalist.org/v1/taxa/${taxonId}`);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
if (data.results && data.results.length > 0) {
return data.results[0];
}
return null;
} catch (error) {
console.error('Error looking up taxon by ID:', error);
return null;
}
}
</script>
</body>
</html>