-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (82 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
var along = require('turf-along');
var lineDistance = require('turf-line-distance');
var linestring = require('turf-linestring');
var fc = require('turf-featurecollection');
/**
* Divides a {@link LineString} into chunks of a specified length.
*
* @module turf/line-chunk
* @category transformation
* @param {Feature<LineString>} line the line to split
* @param {Number} segment_length how long to make each segment
* @param {String} units can be degrees, radians, miles, or kilometers
* @return {FeatureCollection<LineString>} collection of line segments
* @example
* var line = {
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "LineString",
* "coordinates": [
* [
* -86.28524780273438,
* 40.250184183819854
* ],
* [
* -85.98587036132812,
* 40.17887331434696
* ],
* [
* -85.97213745117188,
* 40.08857859823707
* ],
* [
* -85.77987670898438,
* 40.15578608609647
* ]
* ]
* }
* };
*
* //=line
*
* var result = turf.lineChunk(line, 15, 'miles');
*
* result.features.forEach(function(ft, ind) {
* ft.properties.stroke = (ind % 2 === 0) ? '#f40' : '#389979';
* });
*
* //=result
*/
module.exports = function(line, segment_length, units) {
if (line.type == "LineString") {
line = {"type": "Feature", "properties": {}, "geometry": line};
}
if (lineDistance(line, units) <= segment_length) {
return fc([line]);
}
var coordinates = line.geometry.coordinates.slice();
var result = [];
while (coordinates.length > 1) {
var endpt = along(linestring(coordinates), segment_length, units);
var tempcoords = [];
for (var i = 0; i < coordinates.length; i++) {
tempcoords.push(coordinates[i]);
if (lineDistance(linestring(tempcoords), units) >= segment_length) {
tempcoords.pop();
tempcoords.push(endpt.geometry.coordinates);
coordinates = coordinates.slice(i);
coordinates.unshift(endpt.geometry.coordinates);
result.push(tempcoords);
break;
}
if (i == coordinates.length - 1) {
coordinates = [];
result.push(tempcoords);
}
}
}
return fc(result.map(function(coords) {
return linestring(coords);
}));
};