maptastik
12/1/2018 - 3:13 PM

Create a hex grid from another layer's bounding box

This function takes an input GeoJSON dataset and creates a generates a hex grid from the bounding box of that layer.

function hexGridFromLayerBBox(
  bboxJson,
  cellSide = 1,
  hexUnits = "miles",
  radius = 0,
  bufferUnits = "miles"
) {
  // requires turfjs
  let bbox = turf.bbox(
    turf.buffer(bboxJson, radius, {
      units: bufferUnits
    })
  );

  return turf.hexGrid(bbox, cellSide, {
    unit: hexUnits
  });
}

This function takes an input GeoJSON dataset and creates a generates a hex grid from the bounding box of that layer. Because of the way hex grids are created using turfjs, using the bounding box doesn't necessarily result in every area of the input GeoJSON being covered by a hex grid. As such you can also set buffer parameters, radius and bufferUnits, to expand the area for which the bounding box is created. You can define the size of the hexagons with the cellSide and hexUnits parameters.