UNPKG

2.4 kBJavaScriptView Raw
1var each = require('turf-meta').coordEach,
2 convexHull = require('convex-hull'),
3 polygon = require('turf-helpers').polygon;
4
5/**
6 * Takes a set of {@link Point|points} and returns a
7 * [convex hull](http://en.wikipedia.org/wiki/Convex_hull) polygon.
8 *
9 * Internally this uses
10 * the [convex-hull](https://github.com/mikolalysenko/convex-hull) module that
11 * implements a [monotone chain hull](http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain).
12 *
13 * @name convex
14 * @param {FeatureCollection<Point>} input input points
15 * @returns {Feature<Polygon>} a convex hull
16 * @example
17 * var points = {
18 * "type": "FeatureCollection",
19 * "features": [
20 * {
21 * "type": "Feature",
22 * "properties": {},
23 * "geometry": {
24 * "type": "Point",
25 * "coordinates": [10.195312, 43.755225]
26 * }
27 * }, {
28 * "type": "Feature",
29 * "properties": {},
30 * "geometry": {
31 * "type": "Point",
32 * "coordinates": [10.404052, 43.8424511]
33 * }
34 * }, {
35 * "type": "Feature",
36 * "properties": {},
37 * "geometry": {
38 * "type": "Point",
39 * "coordinates": [10.579833, 43.659924]
40 * }
41 * }, {
42 * "type": "Feature",
43 * "properties": {},
44 * "geometry": {
45 * "type": "Point",
46 * "coordinates": [10.360107, 43.516688]
47 * }
48 * }, {
49 * "type": "Feature",
50 * "properties": {},
51 * "geometry": {
52 * "type": "Point",
53 * "coordinates": [10.14038, 43.588348]
54 * }
55 * }, {
56 * "type": "Feature",
57 * "properties": {},
58 * "geometry": {
59 * "type": "Point",
60 * "coordinates": [10.195312, 43.755225]
61 * }
62 * }
63 * ]
64 * };
65 *
66 * var hull = turf.convex(points);
67 *
68 * var resultFeatures = points.features.concat(hull);
69 * var result = {
70 * "type": "FeatureCollection",
71 * "features": resultFeatures
72 * };
73 *
74 * //=result
75 */
76module.exports = function (fc) {
77 var points = [];
78 each(fc, function (coord) { points.push(coord); });
79 var hull = convexHull(points);
80 if (hull.length > 0) {
81 var ring = [];
82 for (var i = 0; i < hull.length; i++) {
83 ring.push(points[hull[i][0]]);
84 }
85 ring.push(points[hull[hull.length - 1][1]]);
86 return polygon([ring]);
87 }
88 return undefined;
89};