import { createSteppedArray } from "../helpers/createSteppedArray.js";
/**
* @function hexbin
* @summary Compute a hexbin grid.
* @description The `hexbin()` function allows to create a hexbin grid in SVG coordinates.
* @param {number} [step = 50] - Step of the grid.
* @param {array} [start = [0,0]] - Positioning coordinates [x,y].
* @param {number} [width = 1000] - Width of the grid
* @param {number} [height = 500] - Height of the grid
* @param {boolean} [overflow = true] - Depending on the step you choose, the grid may be smaller than the bounding box defined by with and height. With overflow = true, the grid is allowed to exceed the bounding box.
* @returns {object} - A GeoJSON FeatureCollection
* @example
* geogrid.hexbin({step:30})
*/
export function hexbin({
step = 50,
width = 1000,
height = 500,
start = [0, 0],
overflow = true,
} = {}) {
const w = step;
const size = w / Math.sqrt(3);
const h = size * 1.5;
const x0 = overflow ? start[0] - w / 2 : start[0];
//const x0 = start[0];
const y0 = overflow ? start[1] - size : start[1];
const yEnd = overflow ? height + y0 + size * 2 : height + y0 - size;
const y = createSteppedArray(y0 + size, yEnd, h);
const grid = [];
// Pour chaque ligne Y
y.forEach((yy, row) => {
const offset = (row % 2) * (w / 2);
let xEnd = overflow ? width + x0 : width + x0 - w - w / 2;
const x = createSteppedArray(x0 + offset + w / 2, xEnd, w);
x.forEach((xx) => {
if (xx <= width + x0) {
grid.push([xx, yy]);
}
});
if (x[x.length - 1] < width + x0) {
grid.push([x[x.length - 1] + w, yy]);
}
});
const features = grid.map(([cx, cy], i) => {
const hex = [];
for (let a = 0; a < 6; a++) {
const angle = (Math.PI / 180) * (60 * a - 30);
hex.push([cx + size * Math.cos(angle), cy + size * Math.sin(angle)]);
}
hex.push(hex[0]);
return {
type: "Feature",
geometry: {
type: "Polygon",
coordinates: [hex],
},
properties: {
index: i,
},
};
});
return {
type: "FeatureCollection",
grid: "hexbin",
geo: false,
features: features,
};
}