Skip to content

Instantly share code, notes, and snippets.

@awoodruff
Created January 15, 2015 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awoodruff/b2300981a28bfa00c94c to your computer and use it in GitHub Desktop.
Save awoodruff/b2300981a28bfa00c94c to your computer and use it in GitHub Desktop.
Square grid (Mercator) for Turfjs
// creates GeoJSON features (using Turfjs) for square grid cells in the Mercator projection
function grid(minX,minY,maxX,maxY,size){ // arguments are in projected mercator units; conversion functions below
var x = minX,
y = minY,
cells = [],
x0,
y0,
x1,
y1;
while ( x < maxX ){
y = minY;
x0 = rad2deg( x );
x1 = rad2deg( x + size );
while ( y < maxY ){
y0 = rad2deg( mercator_invert_y( y ) );
y1 = rad2deg( mercator_invert_y( y + size ) );
cells[ cells.length ] = turf.polygon([[
[x0,y0],
[x0,y1],
[x1,y1],
[x1,y0]
]]);
y += size;
}
x += size;
}
return turf.featurecollection( cells );
}
var halfpi = Math.PI/2,
pi = Math.PI;
function mercator(lon, lat) {
lon = deg2rad(lon);
lat = deg2rad(lat);
return [lon, Math.log(Math.tan(pi / 4 + lat / 2))];
}
function mercator_invert(x, y) {
return [x, 2 * Math.atan(Math.exp(y)) - halfpi];
}
function mercator_invert_y(y) {
return 2 * Math.atan(Math.exp(y)) - halfpi;
}
function deg2rad(angle){
return angle * .017453292519943295;
}
function rad2deg(angle){
return angle * 57.29577951308232
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment