Public
Edited
Aug 7, 2024
2 forks
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
cells = geojson.features.flatMap(
feature => feature.geometry.coordinates.flatMap(
coordinates => h3.polygonToCells(coordinates, h3Resolution, true)
)
)
Insert cell
centroid = {
let min = Infinity;
let center = null;

for (const cell of cells) {
let total = 0;
for (const neighbor of cells) {
total += h3.gridDistance(cell, neighbor);
}
if (total < min) {
min = total;
center = cell;
}
}
return center;
}
Insert cell
centroid2 = {
// alternative approach:
// - average the i,j coords
// - find the cell nearest to the average
console.time("Calculating centroid, 2");
const cellsWithIJ = cells.map(cell => {
const {i, j} = h3.cellToLocalIj(cells[0], cell);
return {cell, i, j};
});
let avgI = 0;
let avgJ = 0;
for (const {i, j} of cellsWithIJ) {
avgI += i;
avgJ += j;
}
avgI /= cells.length;
avgJ /= cells.length;

let nearest = cells[0];
let nearestDist = Infinity;
for (const {cell, i, j} of cellsWithIJ) {
const dist = (i - avgI) ** 2 + (j - avgJ) ** 2;
if (dist < nearestDist) {
nearestDist = dist;
nearest = cell;
}
}

console.timeEnd("Calculating centroid, 2");
return nearest;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
geojson = geomChoice === 'SF' ? sf : hawaii;
Insert cell
Insert cell
Insert cell
Insert cell
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