-
-
Notifications
You must be signed in to change notification settings - Fork 35.7k
/
Copy pathgpw-data-viewer.html
120 lines (85 loc) · 2.26 KB
/
gpw-data-viewer.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
<!doctype html>
<html>
<meta charset="utf-8">
<head>
<title>gpw data viewer</title>
<style>
canvas {
max-width: calc(100% - 16px);
}
</style>
</head>
<body>
<canvas></canvas>
</body>
<script type="module">
async function loadFile( url ) {
const req = await fetch( url );
return req.text();
}
function parseData( text ) {
const data = [];
const settings = { data };
let max;
let min;
// split into lines
text.split( '\n' ).forEach( ( line ) => {
// split the line by whitespace
const parts = line.trim().split( /\s+/ );
if ( parts.length === 2 ) {
// only 2 parts, must be a key/value pair
settings[ parts[ 0 ] ] = parseFloat( parts[ 1 ] );
} else if ( parts.length > 2 ) {
// more than 2 parts, must be data
const values = parts.map( ( v ) => {
const value = parseFloat( v );
if ( value === settings.NODATA_value ) {
return undefined;
}
max = Math.max( max === undefined ? value : max, value );
min = Math.min( min === undefined ? value : min, value );
return value;
} );
data.push( values );
}
} );
return Object.assign( settings, { min, max } );
}
function drawData( file ) {
const { min, max, ncols, nrows, data } = file;
const range = max - min;
const ctx = document.querySelector( 'canvas' ).getContext( '2d' );
// make the canvas the same size as the data
ctx.canvas.width = ncols;
ctx.canvas.height = nrows;
// but display it double size so it's not too small
ctx.canvas.style.width = px( ncols * 2 );
// fill the canvas to dark gray
ctx.fillStyle = '#444';
ctx.fillRect( 0, 0, ctx.canvas.width, ctx.canvas.height );
// draw each data point
data.forEach( ( row, latNdx ) => {
row.forEach( ( value, lonNdx ) => {
if ( value === undefined ) {
return;
}
const amount = ( value - min ) / range;
const hue = 1;
const saturation = 1;
const lightness = amount;
ctx.fillStyle = hsl( hue, saturation, lightness );
ctx.fillRect( lonNdx, latNdx, 1, 1 );
} );
} );
}
function px( v ) {
return `${v | 0}px`;
}
function hsl( h, s, l ) {
return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;
}
loadFile( 'resources/data/gpw/gpw_v4_basic_demographic_characteristics_rev10_a000_014mt_2010_cntm_1_deg.asc' )
.then( parseData )
.then( drawData );
</script>
</html>