Public
Edited
May 4, 2023
1 star
Insert cell
Insert cell
Insert cell
Insert cell
config = ({
lat: 38.057,
lng: -122.635,
zoom: 14,
});
Insert cell
{
renderH3IndexesToMap(map, 'hexes', hexagons)
return md`*{map rendering logic}*`
}
Insert cell
hexagons = h3Indexes.map(({h3Index}) => h3Index)
Insert cell
h3Indexes = {
const {minLat, maxLat, minLng, maxLng} = bounds;
const height = maxLat - minLat;
const width = maxLng - minLng;
const rowCount = imageData.height;
const colCount = imageData.width;
const px2coord = (row, col) => ({
lat: maxLat - (row / rowCount) * height,
lng: (col / 4 / colCount) * width + minLng
});
const indexes = {};
for (let r = 0; r < rowCount; r++) {
for (let c = 0; c < colCount * 4; c += 4) {
const {lat, lng} = px2coord(r, c);
const h3Index = h3.geoToH3(lat, lng, h3Resolution);
if (!indexes[h3Index]) {
indexes[h3Index] = {sum: 0, count: 0, transparent: 0};
}
const rValue = imageData.data[r * colCount * 4 + c];
const aValue = imageData.data[r * colCount * 4 + c + 3];
indexes[h3Index].sum += rValue;
if (!aValue) indexes[h3Index].transparent++;
indexes[h3Index].count++;
}
}

for (const h3Index of Object.keys(indexes)) {
const neighbors = h3.kRing(h3Index, 1);
for (const n of neighbors) {
if (!indexes[n]) {
const nNeighbors = h3.kRing(n, 1);
const neighborCount = nNeighbors.reduce(
(count, nn) => count += indexes[nn] ? 1 : 0, 0
);
if (neighborCount > 5) {
const filler = indexes[n] = {sum: 0, count: 0, transparent: 0};
nNeighbors.forEach(nn => {
filler.sum += indexes[nn].sum;
filler.count += indexes[nn].count;
filler.transparent += indexes[nn].transparent;
});
}
}
}
}

const out = [];
Object.keys(indexes).forEach(h3Index => {
const {sum, count, transparent} = indexes[h3Index];
if (transparent / count < 0.5) {
out.push({h3Index, value: sum / count});
}
});
return out;
}
Insert cell
{
return Array.prototype.some.call(imageData.data, (el) => el !== 0 )
}
Insert cell
imageData = {
const offscreenCanvas = new OffscreenCanvas(240, 300);
const offscreenContext = offscreenCanvas.getContext('2d');
offscreenContext.drawImage(leia, 0, 0, 240, 300);
const imageData = offscreenContext.getImageData(0, 0, 240, 300);

return imageData;
}
Insert cell
Insert cell
imageBuffer = FileAttachment("leia2@2.png").arrayBuffer()
Insert cell
bounds = ({
minLat: 38.04883321082164,
maxLat: 38.06352515986603,
minLng: -122.64325157861433,
maxLng: -122.62784405398753,
})
Insert cell
csv = {
let csv = `h3Index,value`;
for (const {h3Index, value} of h3Indexes) {
csv += `\n${h3Index},${value}`;
}
return csv;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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