-
Notifications
You must be signed in to change notification settings - Fork 951
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
New module @turf/linestring-to-polygon (#672)
* Initial module publish turf-linestring-to-polygon * Update description * Add line colors to tests * Convert FeatureCollection to MultiPolygon Changes based on #672 (comment) - Convert FeatureCollection & GeometryCollection to MultiPolygon - Colorize test fixtures (easier to visualize) - Update Typescript defintion & tests CC: @stebogit * Add `orderCoords` param to place outer ring in 1st position - Add Test fixture with outer ring in middle position (must be placed in first position) - Update Typescript definition - Update benchmark results (2-3x peformance loss, not significant enough to complain) CC: @stebogit
- Loading branch information
1 parent
9305807
commit 4ad8852
Showing
24 changed files
with
1,429 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
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. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
# @turf/linestring-to-polygon | ||
|
||
# lineStringToPolygon | ||
|
||
Converts (Multi)LineString(s) to Polygon(s). | ||
|
||
**Parameters** | ||
|
||
- `lines` **([FeatureCollection](http://geojson.org/geojson-spec.html#feature-collection-objects) \| [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))>)** Features to convert | ||
- `autoComplete` **\[[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)]** auto complete linestrings (optional, default `true`) | ||
|
||
**Examples** | ||
|
||
```javascript | ||
var line = { | ||
'type': 'Feature', | ||
'properties': {}, | ||
'geometry': { | ||
'type': 'LineString', | ||
'coordinates': [[125, -30], [145, -30], [145, -20], [125, -20], [125, -30]] | ||
} | ||
} | ||
var polygon = turf.lineStringToPolygon(line); | ||
|
||
//addToMap | ||
var addToMap = [polygon]; | ||
``` | ||
|
||
Returns **([FeatureCollection](http://geojson.org/geojson-spec.html#feature-collection-objects) \| [Feature](http://geojson.org/geojson-spec.html#feature-objects)<[Polygon](http://geojson.org/geojson-spec.html#polygon)>)** converted to 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/linestring-to-polygon | ||
``` | ||
|
||
Or install the Turf module that includes it as a function: | ||
|
||
```sh | ||
$ npm install @turf/turf | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
const Benchmark = require('benchmark'); | ||
const path = require('path'); | ||
const fs = require('fs'); | ||
const load = require('load-json-file'); | ||
const lineStringToPolygon = require('./'); | ||
|
||
const directory = path.join(__dirname, 'test', 'in') + path.sep; | ||
let fixtures = fs.readdirSync(directory).map(filename => { | ||
return { | ||
filename, | ||
name: path.parse(filename).name, | ||
geojson: load.sync(directory + filename) | ||
}; | ||
}); | ||
// fixtures = fixtures.filter(fixture => fixture.name === 'multi-linestrings-with-holes'); | ||
|
||
/** | ||
* Benchmark Results | ||
* | ||
* collection-linestring x 2,337,816 ops/sec ±3.08% (86 runs sampled) | ||
* geometry-linestring x 6,574,088 ops/sec ±3.62% (83 runs sampled) | ||
* linestring-incomplete x 6,768,527 ops/sec ±3.60% (84 runs sampled) | ||
* linestring x 6,752,969 ops/sec ±1.94% (84 runs sampled) | ||
* multi-linestring-incomplete x 808,779 ops/sec ±8.86% (80 runs sampled) | ||
* multi-linestring-outer-ring-middle-position x 664,121 ops/sec ±1.52% (83 runs sampled) | ||
* multi-linestring-with-hole x 1,018,657 ops/sec ±1.35% (86 runs sampled) | ||
* multi-linestrings-with-holes x 421,758 ops/sec ±0.92% (88 runs sampled) | ||
*/ | ||
const suite = new Benchmark.Suite('turf-linestring-to-polygon'); | ||
for (const {name, geojson} of fixtures) { | ||
suite.add(name, () => lineStringToPolygon(geojson)); | ||
} | ||
|
||
suite | ||
.on('cycle', e => console.log(String(e.target))) | ||
.on('complete', () => {}) | ||
.run(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
/// <reference types="geojson" /> | ||
|
||
// Geometry Types | ||
type MultiLineString = GeoJSON.MultiLineString | ||
type LineString = GeoJSON.LineString | ||
type Polygon = GeoJSON.Polygon | ||
type MultiPolygon = GeoJSON.MultiPolygon | ||
|
||
// Inputs | ||
type Feature = GeoJSON.Feature<LineString | MultiLineString> | LineString | MultiLineString | ||
type FeatureCollection = GeoJSON.FeatureCollection<LineString | MultiLineString> | GeoJSON.GeometryCollection | ||
|
||
/** | ||
* Output type changes based on input type | ||
* | ||
* Feature => Polygon | ||
* FeatureCollection => MultiPolygon | ||
*/ | ||
interface LineStringToPolygon { | ||
(lines: Feature, properties?: any, autoComplete?: boolean, orderCoords?: boolean): GeoJSON.Feature<Polygon> | ||
(lines: FeatureCollection, properties?: any, autoComplete?: boolean, orderCoords?: boolean): GeoJSON.Feature<MultiPolygon> | ||
} | ||
declare const lineStringToPolygon: LineStringToPolygon; | ||
export = lineStringToPolygon; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,134 @@ | ||
var bbox = require('@turf/bbox'); | ||
var getCoords = require('@turf/invariant').getCoords; | ||
var helpers = require('@turf/helpers'); | ||
var polygon = helpers.polygon; | ||
var multiPolygon = helpers.multiPolygon; | ||
var lineString = helpers.lineString; | ||
|
||
/** | ||
* Converts (Multi)LineString(s) to Polygon(s). | ||
* | ||
* @name lineStringToPolygon | ||
* @param {FeatureCollection|Feature<LineString|MultiLineString>} lines Features to convert | ||
* @param {Object} [properties] translates GeoJSON properties to Feature | ||
* @param {boolean} [autoComplete=true] auto complete linestrings (matches first & last coordinates) | ||
* @param {boolean} [orderCoords=true] sorts linestrings to place outer ring at the first position of the coordinates | ||
* @returns {Feature<Polygon|MultiPolygon>} converted to Polygons | ||
* @example | ||
* var line = { | ||
* 'type': 'Feature', | ||
* 'properties': {}, | ||
* 'geometry': { | ||
* 'type': 'LineString', | ||
* 'coordinates': [[125, -30], [145, -30], [145, -20], [125, -20], [125, -30]] | ||
* } | ||
* } | ||
* var polygon = turf.lineStringToPolygon(line); | ||
* | ||
* //addToMap | ||
* var addToMap = [polygon]; | ||
*/ | ||
module.exports = function (lines, properties, autoComplete, orderCoords) { | ||
// validation | ||
if (!lines) throw new Error('lines is required'); | ||
|
||
// default params | ||
autoComplete = (autoComplete !== undefined) ? autoComplete : true; | ||
orderCoords = (orderCoords !== undefined) ? orderCoords : true; | ||
var type = geomType(lines); | ||
|
||
switch (type) { | ||
case 'FeatureCollection': | ||
case 'GeometryCollection': | ||
var coords = []; | ||
var features = (lines.features) ? lines.features : lines.geometries; | ||
features.forEach(function (line) { | ||
coords.push(getCoords(lineStringToPolygon(line, {}, autoComplete, orderCoords))); | ||
}); | ||
return multiPolygon(coords, properties); | ||
} | ||
return lineStringToPolygon(lines, properties, autoComplete, orderCoords); | ||
}; | ||
|
||
/** | ||
* LineString to Polygon | ||
* | ||
* @private | ||
* @param {Feature<LineString|MultiLineString>} line line | ||
* @param {Object} [properties] translates GeoJSON properties to Feature | ||
* @param {boolean} [autoComplete=true] auto complete linestrings | ||
* @param {boolean} [orderCoords=true] sorts linestrings to place outer ring at the first position of the coordinates | ||
* @returns {Feature<Polygon>} line converted to Polygon | ||
*/ | ||
function lineStringToPolygon(line, properties, autoComplete, orderCoords) { | ||
properties = properties || line.properties || {}; | ||
var coords = getCoords(line); | ||
var type = geomType(line); | ||
|
||
if (!coords.length) throw new Error('line must contain coordinates'); | ||
|
||
switch (type) { | ||
case 'LineString': | ||
if (autoComplete) coords = autoCompleteCoords(coords); | ||
return polygon([coords], properties); | ||
case 'MultiLineString': | ||
var multiCoords = []; | ||
var largestArea = 0; | ||
|
||
coords.forEach(function (coord) { | ||
if (autoComplete) coord = autoCompleteCoords(coord); | ||
|
||
// Largest LineString to be placed in the first position of the coordinates array | ||
if (orderCoords) { | ||
var area = calculateArea(bbox(lineString(coord))); | ||
if (area > largestArea) { | ||
multiCoords.unshift(coord); | ||
largestArea = area; | ||
} else multiCoords.push(coord); | ||
} else { | ||
multiCoords.push(coord); | ||
} | ||
}); | ||
return polygon(multiCoords, properties); | ||
default: | ||
throw new Error('geometry type ' + type + ' is not supported'); | ||
} | ||
} | ||
|
||
function geomType(feature) { | ||
return (feature.geometry) ? feature.geometry.type : feature.type; | ||
} | ||
|
||
/** | ||
* Auto Complete Coords - matches first & last coordinates | ||
* | ||
* @param {Array<Array<number>>} coords Coordinates | ||
* @returns {Array<Array<number>>} auto completed coordinates | ||
*/ | ||
function autoCompleteCoords(coords) { | ||
var first = coords[0]; | ||
var x1 = first[0]; | ||
var y1 = first[1]; | ||
var last = coords[coords.length - 1]; | ||
var x2 = last[0]; | ||
var y2 = last[1]; | ||
if (x1 !== x2 || y1 !== y2) { | ||
coords.push(first); | ||
} | ||
return coords; | ||
} | ||
|
||
/** | ||
* area - quick approximate area calculation (used to sort) | ||
* | ||
* @private | ||
* @param {[number, number, number, number]} bbox BBox [west, south, east, north] | ||
* @returns {number} very quick area calculation | ||
*/ | ||
function calculateArea(bbox) { | ||
var west = bbox[0]; | ||
var south = bbox[1]; | ||
var east = bbox[2]; | ||
var north = bbox[3]; | ||
return Math.abs(west - east) * Math.abs(south - north); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
{ | ||
"name": "@turf/linestring-to-polygon", | ||
"version": "4.0.0", | ||
"description": "turf linestring-to-polygon 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", | ||
"gis" | ||
], | ||
"author": "Turf Authors", | ||
"contributors": [ | ||
"Denis Carriere <@DenisCarriere>" | ||
], | ||
"license": "MIT", | ||
"bugs": { | ||
"url": "https://github.com/Turfjs/turf/issues" | ||
}, | ||
"homepage": "https://github.com/Turfjs/turf", | ||
"devDependencies": { | ||
"benchmark": "^2.1.3", | ||
"load-json-file": "^2.0.0", | ||
"tape": "^4.6.3", | ||
"write-json-file": "^2.0.0" | ||
}, | ||
"dependencies": { | ||
"@turf/bbox": "^4.1.0", | ||
"@turf/helpers": "^4.1.0", | ||
"@turf/invariant": "^4.1.0" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
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 {point, lineString} = require('@turf/helpers'); | ||
const lineStringToPolygon = require('./'); | ||
|
||
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, | ||
geojson: load.sync(directories.in + filename) | ||
}; | ||
}); | ||
// fixtures = fixtures.filter(fixture => fixture.name === 'multi-linestrings-with-holes'); | ||
|
||
test('turf-linestring-to-polygon', t => { | ||
for (const {name, filename, geojson} of fixtures) { | ||
let {autoComplete, properties, orderCoords} = geojson.properties || {}; | ||
properties = properties || {stroke: '#F0F', 'stroke-width': 6}; | ||
const results = lineStringToPolygon(geojson, properties, autoComplete, orderCoords); | ||
|
||
if (process.env.REGEN) write.sync(directories.out + filename, results); | ||
t.deepEqual(load.sync(directories.out + filename), results, name); | ||
} | ||
// Handle Errors | ||
t.throws(() => lineStringToPolygon(point([10, 5])), 'throws - invalid geometry'); | ||
t.throws(() => lineStringToPolygon(lineString([])), 'throws - empty coordinates'); | ||
t.throws(() => lineStringToPolygon(lineString([[10, 5], [20, 10], [30, 20]]), {}, false), 'throws - autoComplete=false'); | ||
t.end(); | ||
}); |
Oops, something went wrong.