Published
Edited
Jul 28, 2019
2 forks
Importers
5 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
getElevationData = (boundingBox, width, height) => {
function floor(k) {
return Math.pow(2, Math.floor(Math.log(k) / Math.LN2));
}
function convertToHeight(rgbdata) {
const heightData = new Array(width*height);

// Convert RGB-terrain values into height value
// Calculation found here: https://docs.mapbox.com/help/troubleshooting/access-elevation-data/#decode-data
for (var n = 0, l = rgbdata.length; n < l/4; n++) {
const height = -10000 + ((rgbdata[n*4] * 256 * 256 + rgbdata[n*4 + 1] * 256 + rgbdata[n*4 + 2]) * 0.1);
heightData[n] = height;
}
return heightData;
}
var pi = Math.PI,
tau = 2 * pi;
var projection = d3.geoMercator()
.scale(1 / tau)
.translate([0, 0]);
var bounds = [[boundingBox[0], boundingBox[3]], [boundingBox[2], boundingBox[1]]],
p0 = projection([bounds[0][0], bounds[1][1]]),
p1 = projection([bounds[1][0], bounds[0][1]]);

// Convert this to a scale k and translate tx, ty for the projection.
// For crisp image tiles, clamp to the nearest power of two.
var k = floor(0.95 / Math.max((p1[0] - p0[0]) / width, (p1[1] - p0[1]) / height)),
tx = (width - k * (p1[0] + p0[0])) / 2,
ty = (height - k * (p1[1] + p0[1])) / 2;

projection
.scale(k / tau)
.translate([tx, ty]);
const tiles = d3.tile()
.size([width, height])
.scale(projection.scale()*2*Math.PI)
.translate(projection.translate())
();
const tileSize = 256
const scale = tiles.scale / 256;
const tileDim = Math.ceil(256 * scale);
console.log('lll', tileDim)
const canvas = DOM.canvas(width, height);
const context = canvas.getContext('2d');
return Promise.all(tiles.map(async t => {
t.data = await getDemData(t)
return t
})).then(demData => {
demData.map(d => {
const dx = (d.x + tiles.translate[0]) * tiles.scale;
const dy = (d.y + tiles.translate[1]) * tiles.scale;

const imageData = new ImageData(d.data, tileSize, tileSize);

context.putImageData(imageData, dx, dy, 0, 0, tileDim, tileDim)
});
const rawData = context.getImageData(0, 0, width, height).data
console.log('RAW', rawData)
const heightData = convertToHeight(rawData)

const outData = [];
while(heightData.length) outData.push(heightData.splice(0, width));


return outData;

})
}

Insert cell
getElevationData([-73.5041203153,44.3521027977,-73.0734383547,44.6269391853], 200, 200)
Insert cell
d3 = require('d3', "d3-tile@0.0")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more