Skip to content

Instantly share code, notes, and snippets.

@twelch
Created June 28, 2024 05:44
Show Gist options
  • Save twelch/ac4d6ad29bec9d4eb965c9d2bb7b6252 to your computer and use it in GitHub Desktop.
Save twelch/ac4d6ad29bec9d4eb965c9d2bb7b6252 to your computer and use it in GitHub Desktop.
turf-sandbox snippet
const rectangleGrid = (
bbox,
cellWidth,
cellHeight,
options
) => {
// Containers
const results = [];
const west = bbox[0];
const south = bbox[1];
const east = bbox[2];
const north = bbox[3];
const bboxWidth = east - west;
const cellWidthDeg = turf.convertLength(cellWidth, options.units, "degrees");
console.log("cellWidthDeg", cellWidthDeg)
const bboxHeight = north - south;
const cellHeightDeg = turf.convertLength(cellHeight, options.units, "degrees");
console.log("cellHeightDeg", cellHeightDeg)
const columns = Math.floor(Math.abs(bboxWidth) / cellWidthDeg);
const rows = Math.floor(Math.abs(bboxHeight) / cellHeightDeg);
// if the grid does not fill the bbox perfectly, center it.
const deltaX = (bboxWidth - columns * cellWidthDeg) / 2;
console.log('deltaX', deltaX)
const deltaY = (bboxHeight - rows * cellHeightDeg) / 2;
console.log('deltaY', deltaY)
// iterate over columns & rows
let currentX = west + deltaX;
for (let column = 0; column < columns; column++) {
let currentY = south + deltaY;
for (let row = 0; row < rows; row++) {
const cellPoly = turf.polygon(
[
[
[currentX, currentY],
[currentX, currentY + cellHeightDeg],
[currentX + cellWidthDeg, currentY + cellHeightDeg],
[currentX + cellWidthDeg, currentY],
[currentX, currentY],
],
],
options.properties
);
if (options.mask) {
if (intersect(options.mask, cellPoly)) {
results.push(cellPoly);
}
} else {
results.push(cellPoly);
}
currentY += cellHeightDeg;
}
currentX += cellWidthDeg;
}
return turf.featureCollection(results);
}
//// EXAMPLE CODE ////
let squareGrid = rectangleGrid([-95, 30 ,-85, 40], 50, 50, {
units:'miles'
});
let arr = squareGrid.features[0].geometry.coordinates[0]
let from = turf.point(arr[0]);
let to = turf.point(arr[1]);
let options = {units: 'miles'};
let distance = turf.distance(from, to, options);
let from1 = turf.point(arr[1]);
let to1 = turf.point(arr[2]);
let distance1 = turf.distance(from1, to1, options);
console.log(distance,distance1);
return turf.featureCollection([squareGrid, from, to, from1, to1]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment