-
Notifications
You must be signed in to change notification settings - Fork 6
/
iNat_top_observers_map.html
445 lines (411 loc) · 30.7 KB
/
iNat_top_observers_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
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="Map of Top iNaturalist Observers in an Area" />
<title>Map of Top iNaturalist Observers in an Area</title>
<style>
#map { width:100vw; height:100vh; }
p { font:10pt sans-serif; margin:0px; padding:10px 10px 0px 10px; }
body { font:10pt Sans-Serif; margin:0px; padding:0px; border:0px; background:white; }
a { text-decoration:none; }
.icon { border:none; background:none }
</style>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
<script>
// debug grid example from https://leafletjs.com/examples/extending/extending-2-layers.html
L.GridLayer.DebugCoords = L.GridLayer.extend({
createTile: function (coords) {
var tile = document.createElement('div');
tile.innerHTML = [coords.x, coords.y, coords.z].join(', ');
tile.style.outline = '1px solid red';
return tile;
}
});
L.gridLayer.debugCoords = function(opts) {
return new L.GridLayer.DebugCoords(opts);
};
// this allows a style filter to be applied to a basemap tile layer
L.TileLayer.StyleFilter = L.TileLayer.extend({
intialize: function (url, options) {
L.TileLayer.prototype.initialize.call(this, url, options);
},
styleFilter: function () {
var filters = this.options.filter || '';
return filters;
},
_initContainer: function () {
var tile = L.TileLayer.prototype._initContainer.call(this);
this._container.style.filter = this.styleFilter();
},
});
L.tileLayer.styleFilter = function (url, options) {
return new L.TileLayer.StyleFilter(url, options);
};
</script>
</head>
<body>
<script>
//this is generallly how the logic flows below:
//1. get parameters
//2. parameters must include a single place_id (allow multiple)
//3. do a top x observer query for observation set (store these in an array and also note top and bottom counts for later use)
//4. do a returns bounds query for observation set + top x observer ids
//5. create a map with just basemap and place polygon, fit to the bounds from #4.
//6. return 4 best fit UTFgrid X/Y coordinates for the bounds
//7. for each observer, parse through the appropriate UTFgrids, and find center of mass
//8. for each observer, add center of mass markers (use divIcon)
// get parameters from the url
//get parameters from the url
let winurlstr = window.location.href;
let winurlsearchstr = window.location.search;
let winurlexsearchstr = winurlstr.replace(winurlsearchstr,'');
let winurlparams = new URLSearchParams(winurlsearchstr.substring(1));
var place_id = winurlparams.get('place_id');
//place_id = (place_id===null?null:place_id.split(',')[0]);
var top_n = winurlparams.get('top_n') || 10;
winurlparams.delete('per_page'); //this will be used later
winurlparams.delete('top_n');
let inat_url = 'https://www.inaturalist.org/';
let inat_urlbase = 'https://api.inaturalist.org/v1/';
var apirefurl = furl(inat_urlbase+'docs/#!/UTFGrid/get_grid_zoom_x_y_grid_json','Grid Tiles UTFGrid');
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 fjson(url) {
return fetch(url)
.then((response) => {
if (!response.ok) { throw new Error(response.status+': '+response.statusText); };
return response.json();
})
.catch((err) => { console.error(err); });
};
function delay(time,value) {
return new Promise(function(resolve) {
setTimeout(resolve.bind(null, value), time)
console.log('Pausing '+time+'ms...')
});
}
if (!place_id) {
faddelem('p',document.body,null,null,'This page will create a map of the top observers in an area.');
faddelem('p',document.body,null,null,'This page expects you to input at least one place_id in the parameters. It will also accept most parameters from the iNaturalist '+apirefurl+' API endpoint. There is also a special top_n parameter that allows you to specify the number of top observers to display. (By default, it will bring back 10. If you try to pull back more than 10, the page will pause 2.5 seconds between each observer to avoid API request limits.)');
faddelem('p',document.body,null,null,'Suppose the address of this page is '+winurlexsearchstr+', <br />and you want to see the results a map for the top 12 observers in Australia, then you would open '+furl(famp(winurlexsearchstr+'?place_id=6744&top_n=12'))+' in your browser.');
faddelem('p',document.body,null,null,'Note that each observer is added individually as a layer. Each observer layer, as well as other layers, can be toggled on an off in the layer selection control in the top-right corner of the map.');
faddelem('p',document.body,null,null,'The process used to determine the center of mass for top users is approximate and relies on UTFgrids as an alternative to getting coordinates from huge sets of individual observations. The center of mass determination does not fully account for the curvature of the earth, but it should be close in most real-world situations.');
}
else {
var ftopobs = fjson(inat_urlbase+'observations/observers?'+winurlparams+'&per_page='+top_n);
ftopobs.then(async data=>{
if (data.total_results===0) {
faddelem('p',document.body,null,null,'These parameters returned no observations.');
return false;
};
var d = data.results.slice(0,top_n);
var topobs = [];
for (i=0;i<d.length;i++) {
topobs.push({
rank:i,
user_id:d[i].user_id,
user_login:d[i].user.login,
user_name:d[i].user.name,
icon:d[i].user.icon,
obs_count:d[i].observation_count
});
};
var map = await fcreatemap(topobs);
var mymap = map.obj;
var bbox = map.bbox;
//var layers = map.overlays;
var lyrctrl = map.lyrctrl;
var tiles = ffindtiles(bbox);
var iconpxmax = 75;
var countmax = topobs[0].obs_count;
for (j=0;j<topobs.length;j++) {
var obs = topobs[j];
var iconpx = Math.sqrt(obs.obs_count/countmax*Math.pow((iconpxmax/2),2))*2
var coords = await fcenterpoint(tiles,obs.user_id);
var html = "<div style='background-color:lightgray; height:"+iconpx+"px; width:"+iconpx+"; overflow:hidden; border:1px solid orange; border-radius:"+iconpx+"px;'>"
html += (!obs.icon)?"":"<img height='"+iconpx+"px' width='"+iconpx+"px' src='"+obs.icon+"' />"
html += "</div>";
var icon = L.divIcon({
className: 'icon',
html: html,
iconSize: [iconpx,iconpx],
popupAnchor: [0,-iconpx/2],
});
var marker = L.marker([coords[0],coords[1]],{icon:icon}).addTo(mymap);
marker.bindPopup('<a href="'+inat_url+'people/'+obs.user_login+'">'+obs.user_login+'</a>: <a href="'+inat_url+'observations?'+winurlparams+'&user_id='+obs.user_login+'">'+fcomnum(obs.obs_count)+' observations</a>');
//var pin = L.marker([coords[0],coords[1]]).addTo(mymap);
lyrctrl.addOverlay(marker,"Observer: "+obs.user_login+" ("+fcomnum(obs.obs_count)+")");
console.log(obs.user_login+': '+coords[0]+','+coords[1]);
if (top_n>10) {
await delay(2500);
};
};
});
};
async function fcreatemap(topobs) {
winurlparams.delete('user_id');
var users = topobs.map(o=>o.user_id);
var fbbox = fjson(inat_urlbase+'observations?return_bounds=true&per_page=0&'+winurlparams+'&user_id='+users);
var map = fbbox.then(data=>{
var bbox = data.total_bounds;
// other iNaturalist Observation Layers
let inat_points = {url:inat_urlbase+'points/{z}/{x}/{y}.png',description:'iNaturalist Observations (Points)',attribution:'<a href="https://api.inaturalist.org/v1/docs/#!/Observation_Tiles/get_points_zoom_x_y_png">iNaturalist observation data</a>'};
//let inat_circles = {url:inat_urlbase+'colored_heatmap/{z}/{x}/{y}.png',description:'iNaturalist Observations (Density Circles)',attribution:'<a href="https://api.inaturalist.org/v1/docs/#!/Observation_Tiles/get_colored_heatmap_zoom_x_y_png">iNaturalist observation data</a>'};
let inat_heat = {url:inat_urlbase+'heatmap/{z}/{x}/{y}.png',description:'iNaturalist Observations (Heatmap)',attribution:'<a href="https://api.inaturalist.org/v1/docs/#!/Observation_Tiles/get_heatmap_zoom_x_y_png">iNaturalist observation data</a>'};
let inat_grid = {url:inat_urlbase+'grid/{z}/{x}/{y}.png',description:'iNaturalist Observations (Grid)',attribution:'<a href="https://api.inaturalist.org/v1/docs/#!/Observation_Tiles/get_grid_zoom_x_y_png">iNaturalist observation data</a>'};
//let gbif_density_point_py = {url:'https://api.gbif.org/v2/map/occurrence/density/{z}/{x}/{y}@1x.png?srs=EPSG:3857&style=purpleYellow.point&publishingOrg=28eb1a3f-1c15-4a95-931a-4af90ecb574d',description:'iNaturalist Observations in GBIF',attribution:'<a href="https://www.gbif.org/developer/maps">GBIF occurrence data</a>'};
var l_inat_points = L.tileLayer(inat_points.url+'?'+winurlparams+'&user_id='+users,{maxZoom:20, attribution:inat_points.attribution});
//var l_inat_circles = L.tileLayer(inat_circles.url+'?'+winurlparams+'&user_id='+users,{maxZoom:20, attribution:inat_circles.attribution});
var l_inat_heat = L.tileLayer(inat_heat.url+'?'+winurlparams+'&user_id='+users,{maxZoom:20, attribution:inat_heat.attribution});
var l_inat_grid = L.tileLayer(inat_grid.url+'?'+winurlparams+'&user_id='+users,{maxZoom:20, attribution:inat_grid.attribution});
//var l_gbif = L.tileLayer(gbif_density_point_py.url,{maxZoom:20, attribution:gbif_density_point_py.attribution});
// Other iNaturalist Layers
var l_inat_place = L.tileLayer(inat_urlbase+'places/'+place_id+'/{z}/{x}/{y}.png',{maxZoom:20, attribution:'<a href="'+inat_urlbase+'docs/#!/Polygon_Tiles/get_places_place_id_zoom_x_y_png">iNaturalist place polygon</a>'});
// iNaturalist Taxon Places Checklist and Range Layers
//var l_inat_taxonplace = L.tileLayer(inat_urlbase+'taxon_places/'+taxon_id+'/{z}/{x}/{y}.png',{maxZoom:20, attribution:'<a href="'+inat_urlbase+'docs/#!/Polygon_Tiles/get_taxon_places_taxon_id_zoom_x_y_png">iNaturalist taxon place checklist data</a>'});
//var l_inat_taxonrange = L.tileLayer(inat_urlbase+'taxon_ranges/'+taxon_id+'/{z}/{x}/{y}.png',{maxZoom:20, attribution:'<a href="'+inat_urlbase+'docs/#!/Polygon_Tiles/get_taxon_ranges_taxon_id_zoom_x_y_png">iNaturalist taxon range data</a>'});
// Stamen Watercolor (now housed at Smithsonian)
let s_watercolor = {url:'https://watercolormaps.collection.cooperhewitt.org/tile/watercolor/{z}/{x}/{y}.jpg', attribution:'Map <a href="https://watercolormaps.collection.cooperhewitt.org">tiles</a> by <a href="http://stamen.com">Stamen Design</a>, under <a href="https://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="https://openstreetmap.org">OpenStreetMap</a>, under <a href="https://creativecommons.org/licenses/by-sa/3.0">CC BY SA</a>.'};
var l_stamen_watercolor = L.tileLayer(s_watercolor.url,{minZoom:0, maxZoom:20, attribution:s_watercolor.attribution});
var l_stamen_watercolor_mod_muted = L.tileLayer.styleFilter(s_watercolor.url,{minZoom:0, maxZoom:20, attribution:s_watercolor.attribution, filter:'grayscale(85%)'});
var l_stamen_watercolor_mod_gray = L.tileLayer.styleFilter(s_watercolor.url,{minZoom:0, maxZoom:20, attribution:s_watercolor.attribution, filter:'grayscale(100%)'});
var l_stamen_watercolor_mod_darkgray = L.tileLayer.styleFilter(s_watercolor.url,{minZoom:0, maxZoom:20, attribution:s_watercolor.attribution, filter:'grayscale(100%) brightness(50%)'});
// OpenStreetMaps & OpenTopoMap
let s_osm_std = {url:'https://tile.openstreetmap.org/{z}/{x}/{y}.png', attribution:'© <a href="https://osm.org/copyright">OpenStreetMap</a>/ODbL - tiles from <a href="https://osm.org/">OpenStreetMap</a>'};
var l_osm_std = L.tileLayer(s_osm_std.url, {minZoom:0, maxNativeZoom:19, maxZoom:20, attribution:s_osm_std.attribution});
var l_osm_de = L.tileLayer('https://tile.openstreetmap.de/{z}/{x}/{y}.png', {minZoom:0, maxZoom:20, attribution:'© <a href="https://osm.org/copyright">OpenStreetMap</a>/ODbL - tiles <a href="https://openstreetmap.de/">OpenStreetMap Deutschland</a>'});
var l_osm_fr = L.tileLayer('https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png', {minZoom:0, maxZoom:20, attribution:'données © <a href="https://osm.org/copyright">OpenStreetMap</a>/ODbL - rendu <a href="https://openstreetmap.fr">OSM France</a>'});
var l_osm_hot = L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {minZoom:0, maxNativeZoom:19, maxZoom:20, attribution:'données © <a href="https://osm.org/copyright">OpenStreetMap</a>/ODbL - Tiles courtesy of <a href="https://hot.openstreetmap.org/">Humanitarian OpenStreetMap Team</a>'});
let s_otm = {url:'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', attribution:'Kartendaten: © <a href="https://openstreetmap.org/copyright">OpenStreetMap</a>-Mitwirkende, SRTM | Kartendarstellung: © <a href="http://opentopomap.org/">OpenTopoMap</a> (<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)'};
var l_otm = L.tileLayer(s_otm.url,{minZoom:0, maxNativeZoom:17, maxZoom:20, attribution:s_otm.attribution});
// mods
var l_otm_mod_muted = L.tileLayer.styleFilter(s_otm.url,{minZoom:0, maxNativeZoom:17, maxZoom:20, attribution:s_otm.attribution, filter:'grayscale(60%)'});
var l_osm_std_mod_lightgray = L.tileLayer.styleFilter(s_osm_std.url, {minZoom:0, maxZoom:20, attribution:s_osm_std.attribution, filter:'grayscale(100%)'});
var l_osm_std_mod_medgray = L.tileLayer.styleFilter(s_osm_std.url, {minZoom:0, maxZoom:20, attribution:s_osm_std.attribution, filter:'grayscale(100%) brightness(50%) contrast(150%)'});
var l_osm_std_mod_medgray2 = L.tileLayer.styleFilter(s_osm_std.url, {minZoom:0, maxZoom:20, attribution:s_osm_std.attribution, filter:'grayscale(100%) brightness(50%) contrast(150%) invert(100%) contrast(125%)'});
var l_osm_std_mod_darkgray = L.tileLayer.styleFilter(s_osm_std.url, {minZoom:0, maxZoom:20, attribution:s_osm_std.attribution, filter:'grayscale(100%) invert(100%)'});
var l_osm_std_mod_darkest = L.tileLayer.styleFilter(s_osm_std.url, {minZoom:0, maxZoom:20, attribution:s_osm_std.attribution, filter:'grayscale(100%) invert(100%) brightness(80%) contrast(125%)'});
// EOX -- http://maps.eox.at/
// capabilities (including attribution) -- https://tiles.maps.eox.at/wmts/1.0.0/WMTSCapabilities.xml
function f_eox_url(tileset,format) { return `https://tiles.maps.eox.at/wmts/1.0.0/${tileset}/default/g/{z}/{y}/{x}.${format}`; };
// basemaps
var l_eox_osm = L.tileLayer(f_eox_url('osm_3857','jpg'),{minZoom:0, maxNativeZoom:18, maxZoom:20, attribution:'<a href="https://maps.eox.at">OpenStreetMap</a> { Data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Rendering © <a href="https://eox.at">EOX</a> and <a href="https://github.com/mapserver/basemaps">MapServer</a> }'});
var l_eox_blackmarble = L.tileLayer(f_eox_url('blackmarble_3857','jpg'),{minZoom:0, maxNativeZoom:18, maxZoom:20, attribution:'<a href="https://maps.eox.at">Black Marble</a> { © <a href="http://nasa.gov">NASA</a> }'});
var l_eox_bluemarble = L.tileLayer(f_eox_url('bluemarble_3857','jpg'),{minZoom:0, maxNativeZoom:18, maxZoom:20, attribution:'<a href="https://maps.eox.at">Blue Marble</a> { © <a href="http://nasa.gov">NASA</a> }'});
var l_eox_terrain = L.tileLayer(f_eox_url('terrain_3857','jpg'),{minZoom:0, maxNativeZoom:18, maxZoom:20, attribution:'<a href="https://maps.eox.at">Terrain</a> { Data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors and <a href="https://maps.eox.at/#data">others</a>, Rendering © <a href="https://eox.at">EOX</a> }'});
var l_eox_terrain_light = L.tileLayer(f_eox_url('terrain-light_3857','jpg'),{minZoom:0, maxNativeZoom:18, maxZoom:20, attribution:'<a href="https://maps.eox.at">Terrain Light</a> { Data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors and <a href="https://maps.eox.at/#data">others</a>, Rendering © <a href="https://eox.at">EOX</a> }'});
var l_eox_sentinel2_2020 = L.tileLayer(f_eox_url('s2cloudless-2020_3857','jpg'),{minZoom:0, maxZoom:20, attribution:'<a xmlns:dct="http://purl.org/dc/terms/" href="https://s2maps.eu" property="dct:title">Sentinel-2 cloudless - https://s2maps.eu</a> by <a xmlns:cc="http://creativecommons.org/ns#" href="https://eox.at" property="cc:attributionName" rel="cc:attributionURL">EOX IT Services GmbH</a> (Contains modified Copernicus Sentinel data 2020) released under <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>. For commercial usage please see <a href="https://cloudless.eox.at">https://cloudless.eox.at</a>'});
var l_eox_sentinel2_2019 = L.tileLayer(f_eox_url('s2cloudless-2019_3857','jpg'),{minZoom:0, maxZoom:20, attribution:'<a xmlns:dct="http://purl.org/dc/terms/" href="https://s2maps.eu" property="dct:title">Sentinel-2 cloudless - https://s2maps.eu</a> by <a xmlns:cc="http://creativecommons.org/ns#" href="https://eox.at" property="cc:attributionName" rel="cc:attributionURL">EOX IT Services GmbH</a> (Contains modified Copernicus Sentinel data 2019) released under <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>. For commercial usage please see <a href="https://cloudless.eox.at">https://cloudless.eox.at</a>'});
var l_eox_sentinel2_2018 = L.tileLayer(f_eox_url('s2cloudless-2018_3857','jpg'),{minZoom:0, maxZoom:20, attribution:'<a xmlns:dct="http://purl.org/dc/terms/" href="https://s2maps.eu" property="dct:title">Sentinel-2 cloudless - https://s2maps.eu</a> by <a xmlns:cc="http://creativecommons.org/ns#" href="https://eox.at" property="cc:attributionName" rel="cc:attributionURL">EOX IT Services GmbH</a> (Contains modified Copernicus Sentinel data 2019) released under <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>. For commercial usage please see <a href="https://cloudless.eox.at">https://cloudless.eox.at</a>'});
// overlays
var l_eox_hydrography = L.tileLayer(f_eox_url('hydrography_3857','png'),{minZoom:0, maxZoom:20, attribution:'<a href="https://maps.eox.at">Hydrography overlay</a> { Data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Rendering © <a href="https://eox.at">EOX</a> and <a href="https://github.com/mapserver/basemaps">MapServer</a> }'});
var l_eox_coastline = L.tileLayer(f_eox_url('coastline_3857','png'),{minZoom:0, maxZoom:20, attribution:'<a href="https://maps.eox.at">Coastline overlay</a> { Rendering © <a href="https://eox.at">EOX</a> }'});
var l_eox_streets = L.tileLayer(f_eox_url('streets_3857','png'),{minZoom:0, maxZoom:20, attribution:'<a href="https://maps.eox.at">Streets overlay</a> { Data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Rendering © <a href="https://eox.at">EOX</a> and <a href="https://github.com/mapserver/basemaps">MapServer</a> }'});
var l_eox_overlay = L.tileLayer(f_eox_url('overlay_3857','png'),{minZoom:0, maxZoom:20, attribution:'<a href="https://maps.eox.at">Overlay</a> { Data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Rendering © <a href="https://eox.at">EOX</a> and <a href="https://github.com/mapserver/basemaps">MapServer</a> }'});
var l_eox_overlay_bright = L.tileLayer(f_eox_url('overlay_bright_3857','png'),{minZoom:0, maxZoom:20, attribution:'<a href="https://maps.eox.at">Overlay bright</a> { Data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Rendering © <a href="https://eox.at">EOX</a> and <a href="https://github.com/mapserver/basemaps">MapServer</a> }'});
//debug layer
var l_debug = L.gridLayer.debugCoords();
var defaultlayers = [l_otm_mod_muted,l_inat_place];
//if (taxon_id!==null) {
// if (showtaxonplace==='true') {defaultlayers.push(l_inat_taxonplace)};
// if (showtaxonrange==='true') {defaultlayers.push(l_inat_taxonrange)};
//};
faddelem('div',document.body,null,'map');
// create map, and set default center coordinates, zoom level, and layers
var mymap = L.map('map', {
// center: [0,0],
// zoom: 2,
layers: defaultlayers,
doubleClickZoom: false
});
// define available basemaps (can view only one at a time)
var basemaps = {
"Stamen Watercolor": l_stamen_watercolor,
"Stamen Watercolor Mod (Muted)": l_stamen_watercolor_mod_muted,
"Stamen Watercolor Mod (Gray)": l_stamen_watercolor_mod_gray,
"Stamen Watercolor Mod (Dark Gray)": l_stamen_watercolor_mod_darkgray,
"OpenTopoMap": l_otm,
"OpenTopoMap Mod (Muted)": l_otm_mod_muted,
"OpenStreetMap Standard": l_osm_std,
"OpenStreetMap Std Mod (Light Gray)": l_osm_std_mod_lightgray,
"OpenStreetMap Std Mod (Gray 1)": l_osm_std_mod_medgray,
"OpenStreetMap Std Mod (Gray 2)": l_osm_std_mod_medgray2,
"OpenStreetMap Std Mod (Dark Gray)": l_osm_std_mod_darkgray,
"OpenStreetMap Std Mod (Near Black)": l_osm_std_mod_darkest,
"OpenStreetMap Deutschland": l_osm_de,
"OpenStreetMap France": l_osm_fr,
"OpenStreetMap Humanitarian": l_osm_hot,
"EOX OSM": l_eox_osm,
"EOX Black Marble": l_eox_blackmarble,
"EOX Blue Marble": l_eox_bluemarble,
"EOX Sentinel-2 2020": l_eox_sentinel2_2020,
"EOX Sentinel-2 2019": l_eox_sentinel2_2019,
"EOX Sentinel-2 2018": l_eox_sentinel2_2018,
"EOX Terrain": l_eox_terrain,
"EOX Terrain (Light)": l_eox_terrain_light,
};
// define available overlay maps (can view more than one at a time, arranged in order from lowest to highest)
var overlaymaps = {
"EOX Overlay": l_eox_overlay,
"EOX Overlay (Bright)": l_eox_overlay_bright,
// "iNaturalist Taxon Range": l_inat_taxonrange,
// "iNaturalist Taxon Places": l_inat_taxonplace,
"iNaturalist Place": l_inat_place,
// "iNaturalist Observations Density in GBIF (no filters)": l_gbif,
"iNaturalist Observations Heatmap": l_inat_heat,
// "iNaturalist Observations Circles": l_inat_circles,
"iNaturalist Observations Grid": l_inat_grid,
"iNaturalist Observations Points": l_inat_points,
"Debug Grid":l_debug,
};
// add a layer selector control and scale bar
var lyrctrl = L.control.layers(basemaps, overlaymaps).addTo(mymap);
L.control.scale().addTo(mymap);
mymap.fitBounds([[bbox.nelat,(bbox.swlng<bbox.nelng?bbox.nelng:bbox.nelng+360)],[bbox.swlat,bbox.swlng]]);
console.log('bounding box nelat='+bbox.nelat+' nelng='+bbox.nelng+' swlat='+bbox.swlat+' swlng='+bbox.swlng);
return {obj:mymap,bbox:bbox,lyrctrl:lyrctrl};
});
return map;
};
function faddelem(etype,eparent=null,eclass=null,eid=null,ehtml=null,etext=null) {
var eobj = document.createElement(etype);
if (eclass!==null) { eobj.classList = eclass };
if (eid!==null) { eobj.id = eid };
if (ehtml!==null) { eobj.innerHTML = ehtml };
if (etext!==null) { eobj.innerText = etext };
if (eparent!==null) { eparent.appendChild(eobj); };
return eobj;
};
//need to do some geometry to figure out the vertical position of a point at given lattitude on a Mercator projection
//this is not necessary for longitudes
function latidx(lat) { return (1-Math.log(Math.tan(lat*Math.PI/180)+1/Math.cos(lat*Math.PI/180))/Math.PI)/2; };
//function to identify the right tiles to pull, given a bounding box defined by a SW point and NE point in GPS coordinates
//this is only somewhat tested, but it seems to help pull in the right tiles (most of the time?).
//the goal of this is to find the best-fit 4 map tiles which will encompass the bounds of the observations.
function ffindtiles(bbox={swlat:-90,swlng:0,nelat:89.999999,nelng:-0.00001}) {
var w = bbox.swlng;
var e = bbox.nelng;
var n = bbox.nelat;
var s = bbox.swlat;
// get the height and width of the bounding box as proportions (0.0 to 1.0) of the height and width of the total world map, respectively
var dw = ((e>=w)?(e-w):(360-w+e))/360;
var dh = latidx(s)-latidx(n);
//start to set some basic variables to create layers, tiles, and cells
//each tile may contain up to 4096 4px x 4px cells (in 64 columns and 64 rows).
//we want 4 tiles. because maps at zoom 0 will contain only 1 tile, we will set the default (lowest) zoom level 1 for simplicity.
var zoom = 1;
var txmax = Math.pow(2,zoom)-1;
var tymax = Math.pow(2,zoom)-1;
var txnstart = 0;
var tynstart = 0;
let txnum = tynum = 2;
// estimate the maximum zoom level needed to get the entire bounding box in the map, with min zoom 1 and max zoom 20
// once zoom is determined, calculate tile x and y ranges for that zoom level
zoom = (dw<=0 && dh<=0) ? 20
: (dw<dh) ? Math.round( (Math.log(tynum/dh)/Math.log(2))-0.25 ) - 1
: Math.round( (Math.log(txnum/dw)/Math.log(2))-0.25 ) - 1
zoom = (zoom>20)?20:(zoom<1)?1:zoom;
txmax = Math.pow(2,zoom)-1;
tymax = Math.pow(2,zoom)-1;
// at this zoom level, determine the number of tiles high and wide are needed to contain the bounding box
var txw = Math.floor((180+(w<180?w:-180))/360*(txmax+1))%(txmax+1);
var txe = Math.floor((180+(e<180?e:-180))/360*(txmax+1))%(txmax+1);
var tyn = Math.floor(latidx(n)*(tymax+1));
var tys = Math.floor(latidx(s)*(tymax+1));
tyn = (tyn>tymax)?tymax:tyn;
tys = (tys>tymax)?tymax:tys;
var tw = ((e>=w)?(txe-txw):(txmax+1-txw+txe))+1;
var th = tys-tyn+1;
// determine the top-left corner tile for this tileset.
// this will try to center the bounding box tiles in the tileset as much as possible, unless:
// 1. it makes more sense to display the whole world map
// 2. or the bounding box is near the N or S poles
txnstart = (tw===(txmax+1))?0:(tw===txnum)?txw:txw-Math.floor((txnum/2-tw/2));
txnstart = (txnstart>=0)?txnstart:txmax+txnstart+1;
tynstart = (th===(tymax+1))?0:(th===tynum)?tyn:tyn-Math.floor((tynum/2-th/2));
tynstart = (tynstart<0)?0:(tynstart+tynum-1>=tymax)?(tymax-tynum+1):tynstart;
tileary = [];
for (ty=0;ty<tynum;ty++) {
var tya = tynstart+ty;
for (tx=0;tx<txnum;tx++) {
var txa = txnstart+tx;
txa = (txa>txmax)?txa-txmax-1:txa;
tileary.push({id:[tx,ty],zoom:zoom,tid:[txa,tya]});
};
};
return tileary;
};
//function to return the correct x, y, and zoom values to a given map tile or UTFgrid url
function freplacexyz(url,x,y,z) {
url = url.replace('{x}',x);
url = url.replace('{y}',y);
url = url.replace('{z}',z);
return url;
};
function fgettile(ary,key) {
var obj = ary.find(o=>(o.id[0]===key[0]&&o.id[1]===key[1]));
return obj.tid;
};
async function fcenterpoint(tiles,user_id) {
//get UTFgrids
var promiseary = [];
for (t=0;t<tiles.length;t++) {
var url = freplacexyz((inat_urlbase+'heatmap/{z}/{x}/{y}.grid.json?'+winurlparams+'&user_id='+user_id),tiles[t].tid[0],tiles[t].tid[1],tiles[t].zoom);
promiseary.push(Promise.resolve(tiles[t]));
promiseary.push(fjson(url));
};
var coords = await Promise.all(promiseary)
.then(data=>{
//parse through the UTFgrids
var cellnum = 32;
var cellary = [];
var tileary = [];
for (p=0;p<data.length;p=p+2) {
tileary.push(data[p]);
var id = data[p].id;
var utfgrid = data[p+1];
// note that although the UTFgrids are 64x64, these particular UTFGrids are effectively only 32x32 (where 2x2 sets of cells are combined into a single cell)
// we will use the bottom-right cell in each 2x2 set of cells
// since the UTFgrids are *effectively* 32x32, and we have a 2x2 set of UTFgrids, we'll consolidate everything into a single 64x64 set of cells.
for (cy=0;cy<cellnum;cy++) {
for (cx=0;cx<cellnum;cx++) {
//for details about decoding the UTFgrid, see https://github.com/mapbox/utfgrid-spec/blob/master/1.2/utfgrid.md
var idx = utfgrid.grid[(cy*2+1)].charCodeAt(cx*2+1);
idx = idx-((idx>=93)?34:(idx>=35)?33:32);
var d = utfgrid.data[utfgrid.keys[idx]];
if (d!=null) {
cellary.push({x:(id[0]*cellnum)+cx+1,y:(id[1]*cellnum)+cy+1,count:d.cellCount});
};
};
};
};
//here, we'll do a very simple average to get the density midpoint along each of the X and Y axes. we'll round to the nearest cell (whole number).
//note that this doesn't account for things like the shaped of the Earth, but it should be fine for quick high-level visualization.
var cax = 0;
var cay = 0;
var cat = 0;
for (ca=0;ca<cellary.length;ca++) {
cax = cax + cellary[ca].x*cellary[ca].count;
cay = cay + cellary[ca].y*cellary[ca].count;
cat = cat + cellary[ca].count;
};
var zoom = data[0].zoom;
var avgx = Math.round(cax/cat);
var avgy = Math.round(cay/cat);
//now we'll relate the average cell in the set to one of the 32x32 effective cells in the original set of XYZ tiles / UTFgrids
var avgid = [Math.floor((avgx-1)/cellnum),Math.floor((avgy-1)/cellnum)];
var avgt = fgettile(tileary,avgid);
var avgc = [(avgx-1)%cellnum,(avgy-1)%cellnum];
//finally, we'll translate the centerpoint of the cell to a latitude and longitude
var avglat = Math.atan(Math.sinh( Math.PI*(1-( 2*(avgt[1]+((avgc[1]+0.5)/cellnum))/Math.pow(2,zoom) )) )) * 180 / Math.PI;
var avglng = ( (avgt[0]+((avgc[0]+0.5)/cellnum)) / Math.pow(2,zoom) * 360 ) - 180;
return [avglat,avglng];
});
return coords;
};
</script>
</body>
</html>