Skip to content

Commit

Permalink
Merge pull request Turfjs#1405 from Turfjs/rectangleGrid
Browse files Browse the repository at this point in the history
New module: rectangleGrid

Thanks for all your work on this @stevage - much appreciated!
  • Loading branch information
rowanwins authored Jun 24, 2018
2 parents 332063c + ffcf795 commit 17002cc
Show file tree
Hide file tree
Showing 22 changed files with 31,308 additions and 89 deletions.
20 changes: 20 additions & 0 deletions packages/turf-rectangle-grid/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2017 TurfJS

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
60 changes: 60 additions & 0 deletions packages/turf-rectangle-grid/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# @turf/rectangle-grid

<!-- Generated by documentation.js. Update this documentation by updating the source code. -->

## rectangleGrid

Creates a grid of rectangles from a bounding box, [Feature](https://tools.ietf.org/html/rfc7946#section-3.2) or [FeatureCollection](https://tools.ietf.org/html/rfc7946#section-3.3).

**Parameters**

- `bbox` **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)>** extent in [minX, minY, maxX, maxY] order
- `cellWidth` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** of each cell, in units
- `cellHeight` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** of each cell, in units
- `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** Optional parameters (optional, default `{}`)
- `options.units` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** units ("degrees", "radians", "miles", "kilometers") that the given cellWidth
and cellHeight are expressed in. Converted at the southern border. (optional, default `'kilometers'`)
- `options.mask` **[Feature](https://tools.ietf.org/html/rfc7946#section-3.2)&lt;([Polygon](https://tools.ietf.org/html/rfc7946#section-3.1.6) \| [MultiPolygon](https://tools.ietf.org/html/rfc7946#section-3.1.7))>?** if passed a Polygon or MultiPolygon,
the grid Points will be created only inside it
- `options.properties` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** passed to each point of the grid (optional, default `{}`)

**Examples**

```javascript
var bbox = [-95, 30 ,-85, 40];
var cellWidth = 50;
var cellHeight = 20;
var options = {units: 'miles'};

var rectangleGrid = turf.rectangleGrid(bbox, cellWidth, cellHeight, options);

//addToMap
var addToMap = [rectangleGrid]
```

Returns **[FeatureCollection](https://tools.ietf.org/html/rfc7946#section-3.3)&lt;[Polygon](https://tools.ietf.org/html/rfc7946#section-3.1.6)>** a grid of polygons

<!-- This file is automatically generated. Please don't edit it directly:
if you find an error, edit the source file (likely index.js), and re-run
./scripts/generate-readmes in the turf project. -->

---

This module is part of the [Turfjs project](http://turfjs.org/), an open source
module collection dedicated to geographic algorithms. It is maintained in the
[Turfjs/turf](https://github.com/Turfjs/turf) repository, where you can create
PRs and issues.

### Installation

Install this module individually:

```sh
$ npm install @turf/rectangle-grid
```

Or install the Turf module that includes it as a function:

```sh
$ npm install @turf/turf
```
25 changes: 25 additions & 0 deletions packages/turf-rectangle-grid/bench.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

const Benchmark = require('benchmark');
const rectangleGrid = require('./').default;

var bbox = [-95, 30, -85, 40];

/**
* Benchmark Results
*
* highres -- 206310 cells x 5.99 ops/sec ±13.42% (19 runs sampled)
* midres -- 2006 cells x 3,388 ops/sec ±10.03% (85 runs sampled)
* lowres -- 15 cells x 466,370 ops/sec ±1.14% (88 runs sampled)
*/

const lowres = () => rectangleGrid(bbox, 100, 200, { units: 'miles' });
const midres = () => rectangleGrid(bbox, 10, 20, { units: 'miles' });
const highres = () => rectangleGrid(bbox, 1, 2, { units: 'miles' });
var suite = new Benchmark.Suite('turf-rectangle-grid');
suite
.add('highres -- ' + highres().features.length + ' cells', highres)
.add('midres -- ' + midres().features.length + ' cells', midres)
.add('lowres -- ' + lowres().features.length + ' cells', lowres)
.on('cycle', e => console.log(String(e.target)))
.on('complete', () => {})
.run();
11 changes: 11 additions & 0 deletions packages/turf-rectangle-grid/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { BBox, Feature, FeatureCollection, MultiPolygon, Polygon, Properties, Units } from "@turf/helpers";

/**
* http://turfjs.org/docs/#rectanglegrid
*/

export default function rectangleGrid<P = Properties>(bbox: BBox, cellWidth: number, cellHeight: number, options?: {
units?: Units;
properties?: P;
mask?: Feature<Polygon | MultiPolygon> | Polygon | MultiPolygon;
}): FeatureCollection<Polygon, P>;
77 changes: 77 additions & 0 deletions packages/turf-rectangle-grid/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var boolean_intersects_1 = require("@turf/boolean-intersects");
var distance_1 = require("@turf/distance");
var helpers_1 = require("@turf/helpers");
/**
* Creates a grid of rectangles from a bounding box, {@link Feature} or {@link FeatureCollection}.
*
* @name rectangleGrid
* @param {Array<number>} bbox extent in [minX, minY, maxX, maxY] order
* @param {number} cellWidth of each cell, in units
* @param {number} cellHeight of each cell, in units
* @param {Object} [options={}] Optional parameters
* @param {string} [options.units='kilometers'] units ("degrees", "radians", "miles", "kilometers") that the given cellWidth
* and cellHeight are expressed in. Converted at the southern border.
* @param {Feature<Polygon|MultiPolygon>} [options.mask] if passed a Polygon or MultiPolygon,
* the grid Points will be created only inside it
* @param {Object} [options.properties={}] passed to each point of the grid
* @returns {FeatureCollection<Polygon>} a grid of polygons
* @example
* var bbox = [-95, 30 ,-85, 40];
* var cellWidth = 50;
* var cellHeight = 20;
* var options = {units: 'miles'};
*
* var rectangleGrid = turf.rectangleGrid(bbox, cellWidth, cellHeight, options);
*
* //addToMap
* var addToMap = [rectangleGrid]
*/
function rectangleGrid(bbox, cellWidth, cellHeight, options) {
if (options === void 0) { options = {}; }
// Containers
var results = [];
var west = bbox[0];
var south = bbox[1];
var east = bbox[2];
var north = bbox[3];
var xFraction = cellWidth / (distance_1.default([west, south], [east, south], options));
var cellWidthDeg = xFraction * (east - west);
var yFraction = cellHeight / (distance_1.default([west, south], [west, north], options));
var cellHeightDeg = yFraction * (north - south);
// rows & columns
var bboxWidth = (east - west);
var bboxHeight = (north - south);
var columns = Math.floor(bboxWidth / cellWidthDeg);
var rows = Math.floor(bboxHeight / cellHeightDeg);
// if the grid does not fill the bbox perfectly, center it.
var deltaX = (bboxWidth - columns * cellWidthDeg) / 2;
var deltaY = (bboxHeight - rows * cellHeightDeg) / 2;
// iterate over columns & rows
var currentX = west + deltaX;
for (var column = 0; column < columns; column++) {
var currentY = south + deltaY;
for (var row = 0; row < rows; row++) {
var cellPoly = helpers_1.polygon([[
[currentX, currentY],
[currentX, currentY + cellHeightDeg],
[currentX + cellWidthDeg, currentY + cellHeightDeg],
[currentX + cellWidthDeg, currentY],
[currentX, currentY],
]], options.properties);
if (options.mask) {
if (boolean_intersects_1.default(options.mask, cellPoly)) {
results.push(cellPoly);
}
}
else {
results.push(cellPoly);
}
currentY += cellHeightDeg;
}
currentX += cellWidthDeg;
}
return helpers_1.featureCollection(results);
}
exports.default = rectangleGrid;
86 changes: 86 additions & 0 deletions packages/turf-rectangle-grid/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import intersect from "@turf/boolean-intersects";
import distance from "@turf/distance";
import {
BBox, Feature, featureCollection,
FeatureCollection, isNumber, MultiPolygon, polygon, Polygon, Properties, Units,
} from "@turf/helpers";
import {getType} from "@turf/invariant";

/**
* Creates a grid of rectangles from a bounding box, {@link Feature} or {@link FeatureCollection}.
*
* @name rectangleGrid
* @param {Array<number>} bbox extent in [minX, minY, maxX, maxY] order
* @param {number} cellWidth of each cell, in units
* @param {number} cellHeight of each cell, in units
* @param {Object} [options={}] Optional parameters
* @param {string} [options.units='kilometers'] units ("degrees", "radians", "miles", "kilometers") that the given cellWidth
* and cellHeight are expressed in. Converted at the southern border.
* @param {Feature<Polygon|MultiPolygon>} [options.mask] if passed a Polygon or MultiPolygon,
* the grid Points will be created only inside it
* @param {Object} [options.properties={}] passed to each point of the grid
* @returns {FeatureCollection<Polygon>} a grid of polygons
* @example
* var bbox = [-95, 30 ,-85, 40];
* var cellWidth = 50;
* var cellHeight = 20;
* var options = {units: 'miles'};
*
* var rectangleGrid = turf.rectangleGrid(bbox, cellWidth, cellHeight, options);
*
* //addToMap
* var addToMap = [rectangleGrid]
*/
function rectangleGrid<P = Properties>(bbox: BBox, cellWidth: number, cellHeight: number, options: {
units?: Units,
properties?: P,
mask?: Feature<Polygon | MultiPolygon> | Polygon | MultiPolygon,
} = {}): FeatureCollection<Polygon, P> {
// Containers
const results = [];
const west = bbox[0];
const south = bbox[1];
const east = bbox[2];
const north = bbox[3];

const xFraction = cellWidth / (distance([west, south], [east, south], options));
const cellWidthDeg = xFraction * (east - west);
const yFraction = cellHeight / (distance([west, south], [west, north], options));
const cellHeightDeg = yFraction * (north - south);

// rows & columns
const bboxWidth = (east - west);
const bboxHeight = (north - south);
const columns = Math.floor(bboxWidth / cellWidthDeg);
const rows = Math.floor(bboxHeight / cellHeightDeg);

// if the grid does not fill the bbox perfectly, center it.
const deltaX = (bboxWidth - columns * cellWidthDeg) / 2;
const deltaY = (bboxHeight - rows * cellHeightDeg) / 2;

// 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 = 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 featureCollection(results);
}

export default rectangleGrid;
54 changes: 54 additions & 0 deletions packages/turf-rectangle-grid/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"name": "@turf/rectangle-grid",
"version": "6.0.2",
"description": "turf rectangle-grid module",
"main": "index",
"types": "index.d.ts",
"files": [
"index.js",
"index.d.ts"
],
"scripts": {
"prepare": "tsc",
"pretest": "tsc",
"test": "node test.js",
"bench": "node bench.js",
"docs": "node ../../scripts/generate-readmes"
},
"repository": {
"type": "git",
"url": "git://github.com/Turfjs/turf.git"
},
"keywords": [
"turf",
"grid",
"regular",
"cartesian"
],
"author": "Turf Authors",
"contributors": [
"Steve Bennett <@stevage>",
"Adam Michaleski <@adam3039>"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/Turfjs/turf/issues"
},
"homepage": "https://github.com/Turfjs/turf",
"devDependencies": {
"@turf/bbox-polygon": "*",
"@turf/truncate": "*",
"@std/esm": "*",
"benchmark": "*",
"rollup": "*",
"write-json-file": "*",
"load-json-file": "*",
"tape": "*"
},
"dependencies": {
"@turf/distance": "6.x",
"@turf/helpers": "6.x",
"@turf/invariant": "6.x",
"@turf/boolean-intersects": "6.x"
}
}
55 changes: 55 additions & 0 deletions packages/turf-rectangle-grid/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@

const fs = require('fs');
const test = require('tape');
const path = require('path');
const load = require('load-json-file');
const write = require('write-json-file');
const bboxPoly = require('@turf/bbox-polygon').default;
const truncate = require('@turf/truncate').default;
const rectangleGrid = require('./').default;

const directories = {
in: path.join(__dirname, 'test', 'in') + path.sep,
out: path.join(__dirname, 'test', 'out') + path.sep
};

let fixtures = fs.readdirSync(directories.in).map(filename => {
return {
filename,
name: path.parse(filename).name,
json: load.sync(directories.in + filename)
};
});

test('rectangle-grid', t => {
for (const {name, json} of fixtures) {
const {bbox, cellWidth, cellHeight, units, properties, mask} = json;
const options = {
mask,
units,
properties,
}
const result = truncate(rectangleGrid(bbox, cellWidth, cellHeight, options));

// Add styled GeoJSON to the result
const poly = bboxPoly(bbox);
poly.properties = {
stroke: '#F00',
'stroke-width': 6,
'fill-opacity': 0
};
result.features.push(poly);
if (options.mask) {
options.mask.properties = {
"stroke": "#00F",
"stroke-width": 6,
"fill-opacity": 0
};
result.features.push(options.mask);
}

if (process.env.REGEN) write.sync(directories.out + name + '.geojson', result);
t.deepEqual(result, load.sync(directories.out + name + '.geojson'), name);
}
t.end();
});
Loading

0 comments on commit 17002cc

Please sign in to comment.