-
Notifications
You must be signed in to change notification settings - Fork 6
/
iNatAPIv1_observations.html
389 lines (379 loc) · 22.4 KB
/
iNatAPIv1_observations.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, minimum-scale=1.0" />
<meta name="description" content="iNaturalist API Get Observations" />
<title>iNaturalist API Get Observations</title>
<style>
:root {
background: var(--color-base);
color: var(--color-text);
font: 14px Sans-Serif;
--color-base: white;
--color-alt: whitesmoke;
--color-brand: forestgreen;
--color-text: black;
--color-text-invert: white;
--color-text-link: royalblue;
--color-border: lightgray;
--color-hover: lightgray;
--color-base-translucent: rgba(255,255,255,0.85);
}
@media (prefers-color-scheme: dark) {
:root {
--color-base: black;
--color-alt: #171717;
--color-brand: forestgreen;
--color-text: #bababa;
--color-text-invert: black;
--color-text-link: cornflowerblue;
--color-border: #444;
--color-hover: #444;
--color-base-translucent: rgba(0,0,0,0.85);
}
}
#main { width:100%; }
table, td, th { border-collapse:collapse; margin:0; padding:4px; }
th { position:-webkit-sticky /*Safari*/; position:sticky; top:0; font-weight:600; background:var(--color-brand); color:var(--color-text-invert); text-align:left; vertical-align:bottom; }
tbody>tr { border-width:1px 0px; border-style:solid; border-color:var(--color-border); background:var(--color-alt);}
tr:nth-child(even) { background:var(--color-base); }
.tar { text-align:right; }
.icon { height:48px; width:48px; border-radius:50%; }
.photo { height:64px; width:64px; }
img { margin:0; padding:0; border:0; }
a { text-decoration:none; color:var(--color-text-link); }
a:hover { background:var(--color-hover); }
#nav { margin-left:-8px; position:-webkit-sticky /*Safari*/; position:sticky; left:0; bottom:0; background:var(--color-base-translucent); width:188px; height:52px; border-radius:14px; }
@media print { #nav { display:none; } }
.button, .button_inactive { display:inline-block; margin-left:10px; margin-top:10px; height:32px; width:32px; border:1px solid var(--color-border); border-radius:35%; font-size:24px; vertical-align:middle; text-align:center; }
.button { background:var(--color-alt); }
.button_inactive { background:none; color:var(--color-border); }
.bin_true { text-decoration: underline wavy rgba(34,139,34,0.35); }
.bin_false { text-decoration: underline wavy rgba(178,34,34,0.35); }
</style>
</head>
<body>
<script>
let winurlstr = window.location.href;
let winurlsearchstr = window.location.search;
let winurlexsearchstr = winurlstr.replace(winurlsearchstr,'');
let winurlparams = new URLSearchParams(winurlsearchstr.substring(1));
//let p_per_page = winurlparams.get('per_page') || 200;
//let p_page = winurlparams.get('page') || 1;
let p_options = winurlparams.get('options') || [];
winurlparams.delete('options');
let p_idextra_user_id = winurlparams.get('idextra_user_id')?.split(',') || [];;
winurlparams.delete('idextra_user_id');
let p_photo_curl_filename_prefix = winurlparams.get('photo_curl_filename_prefix')?.split(',') || ['photo_id'];
winurlparams.delete('photo_curl_filename_prefix');
function fdate(str,dateonly=false) {
str = str.replace(/t/i,' '); //replaces T (case insensitive) with a space
if (dateonly) { str = str.split(' ')[0]; }
else {
str = str.replace(/([+-]\d{2}\:?\d{2})/,' ($1)'); //puts parenthesis around time zone offset
str = str.replace(/z/i,' (+00:00)'); //replaces Z (case insensitve) with UTC
str = str.replace('+00:00','±00:00');
};
return str;
};
function furl(url,txt=url) { return `<a href="${url}">${txt}</a>`; };
function famp(str) { return str.replace(/&/g,'&'); };
function fcomnum(n) { return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g,',') };
function faddelem(etype,eparent=null,eattributes={}) {
let eobj = document.createElement(etype);
for (let [key,value] of Object.entries(eattributes)) {
if ( typeof value === 'object' && value !== null ) {
for (let [subkey,subvalue] of Object.entries(value)) { eobj[key][subkey] = subvalue; };
}
else { eobj[key] = value; };
};
if (eparent) { eparent.appendChild(eobj); };
return eobj;
};
function faddelems(etype,eparent=null,eattributes=[]) { for (let e of eattributes) { faddelem(etype,eparent,e); }; };
function fpageurl(urlbase,urlparams,per_page,page) {
let params = new URLSearchParams(urlparams);
let url_per_page = params.get('per_page');
let url_page = params.get('page');
(url_per_page===null) ? params.append('per_page',per_page) : params.set('per_page',per_page);
(url_page===null) ? params.append('page',page) : params.set('page',page);
if (p_options && p_options.length>0) { params.append('options',p_options); };
if (p_idextra_user_id && p_idextra_user_id.length>0) { params.append('idextra_user_id',p_idextra_user_id.join(',')); };
if (p_photo_curl_filename_prefix && p_photo_curl_filename_prefix.length>0 && !(p_photo_curl_filename_prefix.length==1 && p_photo_curl_filename_prefix[0]==='photo_id')) { params.append('photo_curl_filename_prefix',p_photo_curl_filename_prefix.join(',')); };
return urlbase+'?'+params;
};
function fpushifnew(ary,value) {
if(!ary.includes(value)) { ary.push(value) };
return ary.length;
};
function fidextra(obs) {
let taxon = obs.taxon;
let ids = obs.identifications;
if (!ids || !taxon) { return null; }
let taxa = {obs:[],ancestor:[],descendant:[],other:[]};
let idextracategory = '';
let idextrausercategory = [];
let idextrausertaxoncategory = [];
if (p_idextra_user_id && p_idextra_user_id.length > 0) {
for (u=0; u<p_idextra_user_id.length; u++) {
idextrausercategory.push('N/A');
idextrausertaxoncategory.push('N/A');
};
};
let countall = 0;
let countobs = 0;
for (let i of ids) {
if (i.current && !i.hidden) {
countall++;
let id = i.taxon.id;
if ( id===taxon.id ) {
countobs++;
idextracategory='obs';
}
else if ( taxon.ancestry && taxon.ancestry.split('/').map(s=>Number(s)).includes(id) ) { idextracategory='ancestor'; }
else if ( i.taxon.ancestry && i.taxon.ancestry.split('/').map(s=>Number(s)).includes(taxon.id) ) { idextracategory='descendant'; }
else { idextracategory='other'; };
fpushifnew(taxa[idextracategory],id);
if (p_idextra_user_id && p_idextra_user_id.length > 0) {
for (w=0; w<p_idextra_user_id.length; w++) {
if ( p_idextra_user_id[w]==i.user.id || p_idextra_user_id[w]==i.user.login ) {
idextrausertaxoncategory[w] = idextracategory;
idextrausercategory[w] = i.category;
};
};
};
};
};
return {obs_taxon_is_community:(taxon.id===obs.community_taxon_id)?true:false,count:{all:countall,by_others:obs.identifications_count,obs:countobs},taxa,idextrausertaxoncategory,idextrausercategory};
};
function fObsTaxonAncestors(obs) {
let ancestors = [];
let rankLevel_kingdom = 70 // this is the highest-level taxon stored in identification[i].ancestors
let rt, taxonId, rankLevel;
if ((rt = obs?.taxon) && (taxonId = rt?.id) && ((rankLevel = rt?.rank_level) < rankLevel_kingdom)) {
for (let id of obs.identifications) {
let idt, idta;
if (idt = id?.taxon) {
if (idt.id === taxonId) {
ancestors = idt.ancestors;
break;
};
if (idta = idt.ancestors) {
for (let [i, atid] of idta.map((a)=>a.id).entries()) {
if (atid === taxonId) {
ancestors = idta.slice(0,i); // add everything above this taxon (will add this taxon later below)
break;
};
};
};
if (ancestors?.length) { break; };
};
};
};
if (rt && rankLevel <= rankLevel_kingdom) {
ancestors.push(rt); // add self taxon
return ancestors;
};
};
function fresults(xobj) {
//faddelem('p',document.body,{innerHTML:furl(famp(apiurl))});
let results = xobj.results;
if (results) {
let total_results = xobj.total_results;
let per_page = xobj.per_page;
let page_curr = xobj.page;
let page_max = Math.ceil(total_results/per_page);
let page_prev = ((page_curr>1)?page_curr-1:null);
let page_next = ((page_curr<page_max)?page_curr+1:null);
faddelem('p',document.body,{innerHTML:'total observations: '+fcomnum(total_results)+'<br />'
+'per page: '+fcomnum(per_page)+'<br />'
+'page: '+fcomnum(page_curr)+' of '+fcomnum(page_max)+'<br />'
});
let table = faddelem('table',document.body,{id:'main'});
let thead = faddelem('thead',table);
let hrow = faddelem('tr',thead);
let labels = [
{innerText:'#'},
{innerText:'ID'},
{innerText:'Photo'},
{innerText:'Name'},
{innerText:'Common Name'},
{innerText:'Rank'},
{innerText:'Grade'},
{innerText:'User Photo'},
{innerText:'User Login'},
{innerText:'Observe Date'},
{innerText:'Submit Date'},
{innerText:'Update Date'},
{innerText:'Coordinates'},
{innerText:'Location Description'},
{innerText:'Description'},
];
if (p_options.includes('idextra')) {
let labels_id = [
{classList:'tar',innerText:'ID Count'},
{classList:'tar',innerText:'ID Count @ Obs'},
{classList:'tar',innerText:'ID Taxa @ Obs'},
{classList:'tar',innerText:'ID Taxa @ Ansc'},
{classList:'tar',innerText:'ID Taxa @ Desc'},
{classList:'tar',innerText:'ID Taxa @ Other'},
{innerText:'Obs Taxon = Community Taxon'},
];
if (p_idextra_user_id && p_idextra_user_id.length>0) {
for (u=0; u<p_idextra_user_id.length; u++) {
labels_id.push({innerText:'User ' +p_idextra_user_id[u]+ ' ID taxon category'});
labels_id.push({innerText:'User ' +p_idextra_user_id[u]+ ' ID category'});
};
};
labels = [...labels.slice(0,7),...labels_id,...labels.slice(7)];
};
if (p_options.includes('photourl')) { labels.push({innerText:'Photo URLs'}); };
if (p_options.includes('photocurl')) { labels.push({innerText:'Photo cURLs'}); };
if (p_options.includes('coreancestors')) {
let labels_ancestors = [
{innerText:'Kingdom'},
{innerText:'Phylum'},
{innerText:'Class'},
{innerText:'Order'},
{innerText:'Family'},
{innerText:'Genus'},
{innerText:'Species'},
];
labels = [...labels.slice(0,2),...labels_ancestors,...labels.slice(2)];
};
faddelems('th',hrow,labels);
let tbody = faddelem('tbody',table);
let inat_taxa = 'https://www.inaturalist.org/taxa/';
for (let i=0; i<results.length; i++) {
let brow = faddelem('tr',tbody);
let rec = results[i];
let values = [
{innerText:i+1},
{innerHTML:furl('https://www.inaturalist.org/observations/'+rec.id,rec.id)},
{innerHTML:'<img class="photo" src="'+((rec.photos&&rec.photos.length>0)?rec.photos[0].url:'')+'" />'},
{innerHTML:rec.taxon?furl(inat_taxa+rec.taxon.id,rec.taxon.name):''},
{innerText:rec.taxon?(rec.taxon.preferred_common_name||''):''},
{innerText:rec.taxon?rec.taxon.rank:''},
{innerText:rec.quality_grade},
{innerHTML:'<img class="icon" src="'+rec.user.icon+'" />'},
{innerHTML:furl('https://www.inaturalist.org/people/'+rec.user.login,rec.user.login)},
{innerText:(rec.time_observed_at?fdate(rec.time_observed_at):(rec.observed_on||''))},
{innerText:(fdate(rec.created_at||rec.created_at_details.date))},
{innerText:fdate(rec.updated_at)},
{innerText:rec.location?rec.location.replace(',',', '):''},
{innerText:rec.place_guess},
{innerText:rec.description},
];
if (p_options.includes('idextra')) {
let idextra = fidextra(rec);
let values_id = [
{classList:'tar',innerText:(idextra===null)?0:idextra.count.all},
{classList:'tar',innerText:(idextra===null)?0:idextra.count.obs},
{classList:'tar',innerText:(idextra===null)?'N/A':idextra.taxa.obs.length},
{classList:'tar',innerText:(idextra===null)?'N/A':idextra.taxa.ancestor.length},
{classList:'tar',innerText:(idextra===null)?'N/A':idextra.taxa.descendant.length},
{classList:'tar',innerText:(idextra===null)?'N/A':idextra.taxa.other.length},
{innerText:(idextra===null)?'N/A':idextra.obs_taxon_is_community,classList:`bin_${(idextra===null||idextra.obs_taxon_is_community)}`},
];
if (p_idextra_user_id && p_idextra_user_id.length>0) {
for (u=0; u<p_idextra_user_id.length; u++) {
values_id.push({innerText:(idextra===null)?'N/A':idextra.idextrausertaxoncategory[u]});
values_id.push({innerText:(idextra===null)?'N/A':idextra.idextrausercategory[u]});
};
};
values = [...values.slice(0,7),...values_id,...values.slice(7)];
};
if (p_options.includes('photourl') || p_options.includes('photocurl')) {
let photourls = [];
let photocurls = [];
if (rec.photos && rec.photos.length>0) {
for (let p=0; p<rec.photos.length; p++) {
let url = (!rec.photos[p].url) ? 'null' : new URL(rec.photos[p].url.split('?')[0]);
if (p_options.includes('photourl')) {
let purl = url.toString().replace('square','medium');
photourls.push(furl(purl));
};
if (p_options.includes('photocurl')) {
let pathname = url.pathname.split('/');
let filename = pathname[pathname.length-1];
filename = filename.replace('square','original');
let prefix = [];
for (n=0; n<p_photo_curl_filename_prefix.length; n++) {
if (p_photo_curl_filename_prefix[n]==='photo_id') { prefix.push(rec.photos[p].id); }
else if (p_photo_curl_filename_prefix[n]==='photo_license') { prefix.push(rec.photos[p].license_code||'unlicensed'); }
else if (p_photo_curl_filename_prefix[n]==='obs_id') { prefix.push(rec.id); }
else if (p_photo_curl_filename_prefix[n]==='obs_seq') { prefix.push(('00'+(p+1)).slice(-2)); }
else if (p_photo_curl_filename_prefix[n]==='obs_date') { prefix.push((rec.observed_on||'YYYYMMDD').replaceAll('-','')); }
else if (p_photo_curl_filename_prefix[n]==='taxon_id') { prefix.push(rec.taxon?.id||'unknown'); }
else if (p_photo_curl_filename_prefix[n]==='taxon_name') { prefix.push((rec.taxon?.name||'unknown').replaceAll(' ','_')); }
else if (p_photo_curl_filename_prefix[n]==='user_id') { prefix.push(rec.user.id); }
else if (p_photo_curl_filename_prefix[n]==='user_login') { prefix.push(rec.user.login); };
};
if (p===0) { photocurls.push('curl'); } // base command
let curl = `${url.toString().replace('square','original')} -o ${prefix.join('_')}_${filename}`;
photocurls.push(curl); // command parameters
};
};
};
if (p_options.includes('photourl')) { values.push({innerHTML:photourls.join(', ')}); };
if (p_options.includes('photocurl')) { values.push({innerText:photocurls.join(' ')}); };
};
if (p_options.includes('coreancestors')) {
let ancestors = fObsTaxonAncestors(rec);
let ancestor;
let values_ancestors = [
{innerHTML: (ancestor = ancestors?.find(a => a.rank === 'kingdom')) ? furl(inat_taxa+ancestor.id,ancestor.name) : null},
{innerHTML: (ancestor = ancestors?.find(a => a.rank === 'phylum')) ? furl(inat_taxa+ancestor.id,ancestor.name) : null},
{innerHTML: (ancestor = ancestors?.find(a => a.rank === 'class')) ? furl(inat_taxa+ancestor.id,ancestor.name) : null},
{innerHTML: (ancestor = ancestors?.find(a => a.rank === 'order')) ? furl(inat_taxa+ancestor.id,ancestor.name) : null},
{innerHTML: (ancestor = ancestors?.find(a => a.rank === 'family')) ? furl(inat_taxa+ancestor.id,ancestor.name) : null},
{innerHTML: (ancestor = ancestors?.find(a => a.rank === 'genus')) ? furl(inat_taxa+ancestor.id,ancestor.name) : null},
{innerHTML: (ancestor = ancestors?.find(a => a.rank === 'species')) ? furl(inat_taxa+ancestor.id,ancestor.name) : null},
];
values = [...values.slice(0,2),...values_ancestors,...values.slice(2)];
};
faddelems('td',brow,values);
};
// buttons to go to prev or next page
let nav = faddelem('div',document.body,{id:'nav'});
(page_curr<=1)?faddelem('span',nav,{classList:'button_inactive',title:'already on first page',innerHTML:'«'}):faddelem('a',nav,{classList:'button',title:'first page',id:'button_first',innerHTML:'«',href:fpageurl(winurlexsearchstr,winurlparams,per_page,1)});
(page_prev===null)?faddelem('span',nav,{classList:'button_inactive',title:'no previous page',innerHTML:'‹'}):faddelem('a',nav,{classList:'button',title:'previous page',id:'button_prev',innerHTML:'‹',href:fpageurl(winurlexsearchstr,winurlparams,per_page,page_prev)});
(page_next===null)?faddelem('span',nav,{classList:'button_inactive',title:'no next page',innerHTML:'›'}):faddelem('a',nav,{classList:'button',title:'next page',id:'button_next',innerHTML:'›',href:fpageurl(winurlexsearchstr,winurlparams,per_page,page_next)});
(page_curr>=page_max)?faddelem('span',nav,{classList:'button_inactive',title:'already on last page',innerHTML:'»'}):faddelem('a',nav,{classList:'button',title:'last page',id:'button_last',innerHTML:'»',href:fpageurl(winurlexsearchstr,winurlparams,per_page,page_max)});
}
else { faddelem('p',document.body,{innerText:'No results returned.'}); };
};
let apibase = 'https://api.inaturalist.org/v1/observations';
let apiurl = apibase+((winurlparams!='')?('?'+winurlparams):'');
let apirefurl = 'https://api.inaturalist.org/v1/docs/#!/Observations/get_observations';
let apirefname = 'iNaturalist Observations';
let apiref = furl(apirefurl,apirefname);
faddelem('h1',document.body,{innerText:apirefname});
if (winurlsearchstr==='') {
let instructions = [
{innerHTML:'This page displays the response from the '+apiref+' API endpoint in a human-readable format. To use this page, add at least one query parameter to the URL. See '+furl(apirefurl)+' for available query parameters.'},
{innerHTML:'Suppose the address of this page is '+winurlexsearchstr+', <br />and you want to see the results of '+furl(famp(apibase+'?user_id=bob&per_page=200'))+' in a friendly format, <br />then you would open '+furl(famp(winurlexsearchstr+'?user_id=bob&per_page=200'))+' in your browser.'},
{innerHTML:'The max records per page for this endpoint is 200. Note that the API will not return records beyond the 10,000th record for a given set of parameters, but you can work around this by using the id_above and id_below parameters.'},
{innerHTML:'This page can display extra columns based on a special options parameter. Adding &options=idextra to the parameter list will display some columns that provide extra information about IDs added to each observation. Adding &options=coreancestors will display some columns for kingdom, phylum, class, order, family, genus, and species. Adding &options=photourl to the parameter list will display a column that includes URLs for all photos in each observation. Adding &options=photourl to the parameter list will display a column that includes cURL commands to download all photos in each observation. All options can be invoked together like this: '+furl(famp(winurlexsearchstr+'?user_id=bob&per_page=200&options=idextra,coreancestors,photourl,photocurl'))+'. '},
{innerHTML:'When &options=idextra is invoked, an optional idextra_user_id parameter can also be used to get additional information about the IDs by a specific user (or lists of users, separated by commas). For example: '+furl(famp(winurlexsearchstr+'?user_id=bob&per_page=200&options=idextra&idextra_user_id=bob,jane'))+'. '},
{innerHTML:'When &options=photocurl is invoked, an optional photo_curl_filename_prefix parameter can also be set to one or more of 9 values -- photo_id, photo_license, obs_id, obs_seq, obs_date, taxon_id, taxon_name, user_id, user_login. By default, the destination filename in the curl commands will be prefixed with only photo id, but you can override this behavior by specifying the a comma-separated list of the values that you wish to include, in the order that you wish for them to be added. For example, this will prefix the destination filenames with obs id, obs seq, and photo id: '+furl(famp(winurlexsearchstr+'?user_id=bob&options=photocurl&photo_curl_filename_prefix=obs_id,obs_seq,photo_id'))+'. '},
];
faddelems('p',document.body,instructions);
}
else {
faddelem('p',document.body,{innerHTML:'This is the base query: '+furl(famp(apiurl))+'. (This page will accept most parameters from the '+apiref+' API endpoint.)'});
fetch(apiurl)
.then((response) => {
if (!response.ok) { throw new Error(response.status+' ('+response.statusText+') returned from '+response.url); };
return response.json();
})
.then((data) => { fresults(data); })
.catch((err) => {
console.error(err.message);
faddelem('p',document.body,{innerText:'There was a problem retrieving data. Error '+err.message+'.'});
});
};
</script>
</body>
</html>