Turfjs / turf

A modular geospatial engine written in JavaScript and TypeScript
https://turfjs.org/
MIT License
9.37k stars 942 forks source link

Aligning grids with different cellSides #2013

Open mrichar1 opened 3 years ago

mrichar1 commented 3 years ago

I am currently experimenting with scaling a grid on a map, applying different sized grids in the same bounding box.

However the grids don't neatly align. This means that it isn't possible to 'sub-divide' the larger grid cells.

A simple example of this is here - the smaller grid isn't aligned with the larger one, and looking at the coordinates neither aligns neatly with any bounding box edge - for example the 1st cell polygon has coordinates:

[
  [ -13.997847567809494, 48.49298963050195 ],
​​​​​​​  [ -13.997847567809494, 49.494158025418294 ],
​​​​​​​  [ -12.498206306507912, 49.494158025418294 ],
​​​​​​​  [ -12.498206306507912, 48.49298963050195 ],
​​​​​​​  [ -13.997847567809494, 48.49298963050195 ]
]

Is there a way to fix this?

let map = L.map('map', {
  center: [55, -4],
  zoomSnap: 0,
  zoom: 6,
})

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { maxZoom: 12, minZoom: 5 }).addTo(map)

const bbox = [-14, 48, 4, 61]
const options = {units: 'degrees'}

let grid1 = turf.squareGrid(bbox, 1, options)
let grid2 = turf.squareGrid(bbox, 0.5, options)

L.geoJson(grid1).addTo(map)
L.geoJson(grid2).addTo(map)

image

mrichar1 commented 3 years ago

It appears this is caused by rectangleGrid working with fractions of the edge, and centering within the bounding box if it overlaps:

https://github.com/Turfjs/turf/blob/master/packages/turf-rectangle-grid/index.ts#L57-L71

The solution in my case was to reimplement this method without the complexity - but with the caveat that it is only useful for grids where the cell edge fits evenly into the bounding box (e.g. using degrees).

Since this is probably just a side-effect of a making the grid method more generally useable, it might not be fixable. However I'm happy to share the simplified version I have if it would be useful as an alternative (exactGrid ?) method.