I am trying to create a square grid of map coordinates with a gridOrder
count that starts counting in the top left corner, left to right, top to bottom. Desired output:
1 | 2 | 3
---+---+---
4 | 5 | 6
---+---+---
7 | 8 | 9
Currently, my code produces the following output:
3 | 6 | 9
---+---+---
2 | 5 | 8
---+---+---
1 | 4 | 7
How can I adjust the code to assign a gridOrder
count in the desired pattern?
import bbox from "@turf/bbox";
import { Units, point } from "@turf/helpers";
import pointGrid from "@turf/point-grid";
import buffer from "@turf/buffer";
const createGridCoordinates = (
centerCoordinates: google.maps.LatLngLiteral,
numPointsPerSide: number,
gridDimension: number,
unitOfMeasure: Units
) => {
// Calculate the cell size
const cellSize = gridDimension / (numPointsPerSide - 1);
// Calculate half the grid size to find the distance from center to edges of bounding box
const halfGridSize = gridDimension / 2;
// Make the bounding box around a center point and a circle buffer radius
// Radius is extended by 10% of a cellSize (cellSize / 10) to include
// east and north edges when gridDimension is an exact multiple of the grid spacing
const boundingBox = bbox(
buffer(
point([centerCoordinates.lng, centerCoordinates.lat]),
halfGridSize + cellSize / 10,
{
units: unitOfMeasure,
}
)
);
// Make the grid. This is an array of grid coordinates.
const grid = pointGrid(boundingBox, cellSize, {
units: unitOfMeasure,
});
// Extract the coordinates from the grid and add gridOrder
const coordinatesGrid = grid.features.map((feature, index) => {
const [longitude, latitude] = feature.geometry.coordinates;
const coordinatesGridItem = {
coordinates: { lat: latitude, lng: longitude },
// Adjust the gridOrder pattern here
gridOrder: numPointsPerSide * Math.floor(index / numPointsPerSide) + (index % numPointsPerSide) + 1,
};
return coordinatesGridItem;
});
return coordinatesGrid;
};