-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
73 lines (66 loc) · 2.19 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
var lineclip = require('lineclip');
/**
* Takes a {@link Feature} and a bbox and clips the feature to the bbox using [lineclip](https://github.com/mapbox/lineclip).
*
* @module turf/bbox-clip
* @category transformation
* @param {Feature} feature feature to clip to the bbox
* @param {Array<number>} bbox an Array of bounding box coordinates in the form: ```[minLon, minLat, maxLon, maxLat]```
* @return {(Feature<Polygon>|Feature<MultiPolygon>|Feature<MultiLineString>)}
* @example
* var bbox = [0, 0, 10, 10];
* var poly = turf.polygon([[[2, 2], [8, 4], [12, 8], [3, 7], [2, 2]]]);
*
* var result = turf.bboxClip(poly, bbox);
*
* //=result
*/
module.exports = function(feature, bbox) {
var geom = feature;
var lineCoordinates;
if (feature.geometry) geom = feature.geometry;
if (geom.type === 'LineString') {
lineCoordinates = [geom.coordinates];
} else if (geom.type === 'MultiLineString') {
lineCoordinates = geom.coordinates;
}
if (lineCoordinates) {
var lines = [];
for (var i = 0; i < lineCoordinates.length; i++) {
lineclip(lineCoordinates[i], bbox, lines);
}
if (lines.length === 1) {
return buildFeature('LineString', lines[0], feature.properties);
}
return buildFeature('MultiLineString', lines, feature.properties);
} else if (geom.type === 'Polygon') {
return buildFeature('Polygon', clipPolygon(geom.coordinates, bbox), feature.properties);
} else if (geom.type === 'MultiPolygon') {
return buildFeature('MultiPolygon', geom.coordinates.map(function (polygon) {
return clipPolygon(polygon, bbox);
}), feature.properties);
}
};
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 buildFeature (type, lines, properties) {
return {
'type': 'Feature',
'properties': properties || {},
'geometry': {
'type': type,
'coordinates': lines
}
};
}