Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New module @turf/bbox-clip 🎉 #652

Merged
merged 4 commits into from
Apr 9, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions packages/turf-bbox-clip/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.
56 changes: 56 additions & 0 deletions packages/turf-bbox-clip/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# @turf/bbox-clip

# bbox-clip

Takes a [Feature](http://geojson.org/geojson-spec.html#feature-objects) and a bbox and clips the feature to the bbox using [lineclip](https://github.com/mapbox/lineclip).
May result in degenerate edges when clipping Polygons.

**Parameters**

- `feature` **[Feature](http://geojson.org/geojson-spec.html#feature-objects)<([LineString](http://geojson.org/geojson-spec.html#linestring) \| [MultiLineString](http://geojson.org/geojson-spec.html#multilinestring) \| [Polygon](http://geojson.org/geojson-spec.html#polygon) \| [MultiPolygon](http://geojson.org/geojson-spec.html#multipolygon))>** feature to clip to the bbox
- `bbox` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<[number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)>** extent in [minX, minY, maxX, maxY] order

**Examples**

```javascript
var bbox = [0, 0, 10, 10];
var poly = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [[[2, 2], [8, 4], [12, 8], [3, 7], [2, 2]]]
}
}

var clipped = turf.bboxClip(poly, bbox);

//=clipped
```

Returns **[Feature](http://geojson.org/geojson-spec.html#feature-objects)<([LineString](http://geojson.org/geojson-spec.html#linestring) \| [MultiLineString](http://geojson.org/geojson-spec.html#multilinestring) \| [Polygon](http://geojson.org/geojson-spec.html#polygon) \| [MultiPolygon](http://geojson.org/geojson-spec.html#multipolygon))>** clipped Feature

<!-- 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/bbox-clip
```

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

```sh
$ npm install @turf/turf
```
36 changes: 36 additions & 0 deletions packages/turf-bbox-clip/bench.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const Benchmark = require('benchmark');
const path = require('path');
const fs = require('fs');
const load = require('load-json-file');
const bbox = require('@turf/bbox');
const bboxClip = require('./');

const directory = path.join(__dirname, 'test', 'in') + path.sep;
const fixtures = fs.readdirSync(directory).map(filename => {
return {
filename,
name: path.parse(filename).name,
geojson: load.sync(directory + filename)
};
});

/**
* Benchmark Results
*
* linestring-single-line x 1,065,073 ops/sec ±1.11% (90 runs sampled)
* linestring x 56,599 ops/sec ±1.17% (90 runs sampled)
* multi-linestring x 859,048 ops/sec ±1.01% (91 runs sampled)
* multi-polygon x 26,991 ops/sec ±0.87% (94 runs sampled)
* polygon-crossing-hole x 25,277 ops/sec ±0.72% (92 runs sampled)
* polygon-holes x 27,233 ops/sec ±0.89% (91 runs sampled)
* polygon x 21,339 ops/sec ±1.19% (89 runs sampled)
*/
const suite = new Benchmark.Suite('turf-bbox-clip');
for (const {name, geojson} of fixtures) {
suite.add(name, () => bboxClip(geojson.features[0], bbox(geojson.features[1])));
}

suite
.on('cycle', e => console.log(String(e.target)))
.on('complete', () => {})
.run();
13 changes: 13 additions & 0 deletions packages/turf-bbox-clip/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/// <reference types="geojson" />

import {BBox, LineString, MultiLineString, Polygon, MultiPolygon} from '@turf/helpers'

interface BBoxClip {
/**
* http://turfjs.org/docs/#bboxclip
*/
(feature: LineString | MultiLineString, bbox: BBox): LineString | MultiLineString
(feature: Polygon | MultiPolygon, bbox: BBox): Polygon | MultiPolygon
}
declare const bboxClip: BBoxClip;
export = bboxClip;
74 changes: 74 additions & 0 deletions packages/turf-bbox-clip/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
var helpers = require('@turf/helpers');
var lineclip = require('lineclip');
var getCoords = require('@turf/invariant').getCoords;
var lineString = helpers.lineString;
var multiLineString = helpers.multiLineString;
var polygon = helpers.polygon;
var multiPolygon = helpers.multiPolygon;

/**
* Takes a {@link Feature} and a bbox and clips the feature to the bbox using [lineclip](https://github.com/mapbox/lineclip).
* May result in degenerate edges when clipping Polygons.
*
* @name bbox-clip
* @param {Feature<LineString|MultiLineString|Polygon|MultiPolygon>} feature feature to clip to the bbox
* @param {Array<number>} bbox extent in [minX, minY, maxX, maxY] order
* @returns {Feature<LineString|MultiLineString|Polygon|MultiPolygon>} clipped Feature
* @example
* var bbox = [0, 0, 10, 10];
* var poly = {
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "Polygon",
* "coordinates": [[[2, 2], [8, 4], [12, 8], [3, 7], [2, 2]]]
* }
* }
*
* var clipped = turf.bboxClip(poly, bbox);
*
* //=clipped
*/
module.exports = function (feature, bbox) {
var geom = getGeom(feature);
var coords = getCoords(feature);
var properties = feature.properties;

switch (geom) {
case 'LineString':
case 'MultiLineString':
var lines = [];
if (geom === 'LineString') coords = [coords];
coords.forEach(function (line) {
lineclip(line, bbox, lines);
});
if (lines.length === 1) return lineString(lines[0], properties);
return multiLineString(lines, properties);
case 'Polygon':
return polygon(clipPolygon(coords, bbox), properties);
case 'MultiPolygon':
return multiPolygon(coords.map(function (polygon) {
return clipPolygon(polygon, bbox);
}), properties);
default:
throw new Error('geometry ' + geom + ' not supported');
}
};

function clipPolygon(rings, bbox) {
var outRings = [];
for (var i = 0; i < rings.length; i++) {
var clipped = lineclip.polygon(rings[i], bbox);
if (clipped.length > 0) {
if (clipped[0][0] !== clipped[clipped.length - 1][0] || clipped[0][1] !== clipped[clipped.length - 1][1]) {
clipped.push(clipped[0]);
}
outRings.push(clipped);
}
}
return outRings;
}

function getGeom(feature) {
return (feature.geometry) ? feature.geometry.type : feature.type;
}
49 changes: 49 additions & 0 deletions packages/turf-bbox-clip/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
{
"name": "@turf/bbox-clip",
"version": "4.0.0",
"description": "turf bbox-clip module",
"main": "index.js",
"types": "index.d.ts",
"files": [
"index.js",
"index.d.ts"
],
"scripts": {
"test": "node test.js",
"bench": "node bench.js"
},
"repository": {
"type": "git",
"url": "git://github.com/Turfjs/turf.git"
},
"keywords": [
"turf",
"geojson",
"gis",
"bbox",
"clip"
],
"author": "Tim Channell <@tcql>",
"contributors": [
"Tim Channell <@tcql>",
"Vladimir Agafonkin <@mourner>",
"Denis Carriere <@DenisCarriere>"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/Turfjs/turf/issues"
},
"homepage": "https://github.com/Turfjs/turf",
"devDependencies": {
"@turf/bbox": "^4.0.2",
"benchmark": "^2.1.3",
"load-json-file": "^2.0.0",
"tape": "^3.5.0",
"write-json-file": "^2.0.0"
},
"dependencies": {
"@turf/helpers": "^4.0.1",
"@turf/invariant": "^4.0.1",
"lineclip": "^1.1.5"
}
}
50 changes: 50 additions & 0 deletions packages/turf-bbox-clip/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
const test = require('tape');
const fs = require('fs');
const path = require('path');
const load = require('load-json-file');
const write = require('write-json-file');
const turfBBox = require('@turf/bbox');
const featureCollection = require('@turf/helpers').featureCollection;
const point = require('@turf/helpers').point;
const bboxClip = require('./');

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

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

test('turf-bbox-clip', t => {
for (const {filename, name, geojson} of fixtures) {
const feature = geojson.features[0];
const bbox = turfBBox(geojson.features[1]);
const clipped = bboxClip(feature, bbox);
const results = featureCollection([colorize(feature, '#080'), colorize(clipped, '#F00'), colorize(geojson.features[1], '#00F', 3)]);

if (process.env.REGEN) write.sync(directories.out + filename, results);
t.deepEquals(results, load.sync(directories.out + filename), name);
}
t.end();
});

test('turf-bbox-clip errors', t => {
t.throws(() => bboxClip(point([5, 10]), [-180, -90, 180, 90]));
t.end();
});

function colorize(feature, color = '#F00', width = 6) {
feature.properties = {
stroke: color,
fill: color,
'stroke-width': width,
'fill-opacity': 0.1
};
return feature;
}
57 changes: 57 additions & 0 deletions packages/turf-bbox-clip/test/in/linestring-single-line.geojson
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"coordinates": [
[
-77.1240234375,
39.51251701659638
],
[
-77.618408203125,
39.24927084622338
],
[
-77.0855712890625,
38.886757140695906
]
]
}
},
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-77.72552490234374,
39.095962936305476
],
[
-77.0361328125,
39.095962936305476
],
[
-77.0361328125,
39.59722324495565
],
[
-77.72552490234374,
39.59722324495565
],
[
-77.72552490234374,
39.095962936305476
]
]
]
}
}
]
}
Loading