-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
76 lines (61 loc) · 2.29 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'use strict';
var extent = require('turf-extent');
var featurecollection = require('turf-featurecollection');
var inside = require('turf-inside');
var random = require('turf-random');
/**
* Takes a number and a feature and {@link Polygon} or {@link MultiPolygon} and returns {@link Points} that reside inside the polygon. The polygon can
* be convex or concave. The function accounts for holes.
*
* * Given a {Number}, the number of points to be randomly generated.
* * Given a {@link Polygon} or {@link MultiPolygon}, the boundary of the random points
*
*
* @module turf-random-points-on-polygon
* @category measurement
* @param {Number} number of points to be generated
* @param {Feature<(Polygon|MultiPolygon)>} polygon input polygon or multipolygon
* @param {Object} [properties={}] properties to be appended to the point features
* @param {Boolean} [fc=false] if true returns points as a {@link FeatureCollection}
* @return {Array} || {FeatureCollection<Points>} an array or feature collection of the random points inside the polygon
**/
function randomPointsOnPolygon(number, polygon, properties, fc) {
if (typeof properties === 'boolean') {
fc = properties;
properties = {};
}
if (number < 1) {
return new Error('Number must be >= 1');
}
if(polygon.type !== 'Feature') {
return new Error('Polygon parameter must be a Feature<(Polygon|MultiPolygon)>');
if (polygon.geomtry.type !== 'Polygon' || polygon.geomtry.type !== 'MutliPolygon') {
return new Error('Polygon parameter must be a Feature<(Polygon|MultiPolygon)>')
}
}
if (this instanceof randomPointsOnPolygon) {
return new randomPointsOnPolygon(number, polygon, properties);
}
properties = properties || {};
fc = fc || false;
var points = [];
var bbox = extent(polygon);
var count = Math.round(parseFloat(number));
for (var i = 0; i <= count; i++) {
if (i === count) {
if (fc) {
return featurecollection(points);
}
return points;
}
var point = random('point', 1, { bbox: bbox });
if (inside(point.features[0], polygon) === false) {
i = --i;
}
if (inside(point.features[0], polygon) === true) {
point.features[0].properties = properties;
points.push(point.features[0]);
}
}
}
module.exports = randomPointsOnPolygon;