gpw-data-viewer.html 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <!doctype html>
  2. <html>
  3. <meta charset="utf-8">
  4. <head>
  5. <title>gpw data viewer</title>
  6. </head>
  7. <body>
  8. <canvas></canvas>
  9. </body>
  10. <script>
  11. 'use strict';
  12. async function loadFile(url) {
  13. const req = await fetch(url);
  14. return req.text();
  15. }
  16. function parseData(text) {
  17. const data = [];
  18. const settings = {data};
  19. let max;
  20. let min;
  21. // split into lines
  22. text.split('\n').forEach((line) => {
  23. // split the line by whitespace
  24. const parts = line.trim().split(/\s+/);
  25. if (parts.length === 2) {
  26. // only 2 parts, must be a key/value pair
  27. settings[parts[0]] = parseFloat(parts[1]);
  28. } else if (parts.length > 2) {
  29. // more than 2 parts, must be data
  30. const values = parts.map((v) => {
  31. const value = parseFloat(v);
  32. if (value === settings.NODATA_value) {
  33. return undefined;
  34. }
  35. max = Math.max(max === undefined ? value : max, value);
  36. min = Math.min(min === undefined ? value : min, value);
  37. return value;
  38. });
  39. data.push(values);
  40. }
  41. });
  42. return Object.assign(settings, {min, max});
  43. }
  44. function drawData(file) {
  45. const {min, max, ncols, nrows, data} = file;
  46. const range = max - min;
  47. const ctx = document.querySelector('canvas').getContext('2d');
  48. // make the canvas the same size as the data
  49. ctx.canvas.width = ncols;
  50. ctx.canvas.height = nrows;
  51. // but display it double size so it's not too small
  52. ctx.canvas.style.width = px(ncols * 2);
  53. ctx.canvas.style.height = px(nrows * 2);
  54. // fill the canvas to dark gray
  55. ctx.fillStyle = '#444';
  56. ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  57. // draw each data point
  58. data.forEach((row, latNdx) => {
  59. row.forEach((value, lonNdx) => {
  60. if (value === undefined) {
  61. return;
  62. }
  63. const amount = (value - min) / range;
  64. const hue = 1;
  65. const saturation = 1;
  66. const lightness = amount;
  67. ctx.fillStyle = hsl(hue, saturation, lightness);
  68. ctx.fillRect(lonNdx, latNdx, 1, 1);
  69. });
  70. });
  71. }
  72. function px(v) {
  73. return `${v | 0}px`;
  74. }
  75. function hsl(h, s, l) {
  76. return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;
  77. }
  78. loadFile('resources/data/gpw/gpw-v4-basic-demographic-characteristics-rev10_a000_014_2010_1_deg_asc/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc')
  79. .then(parseData)
  80. .then(drawData);
  81. </script>
  82. </html>