index.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. 'use strict';
  2. var rbush = require('geojson-rbush');
  3. var square = require('@turf/square');
  4. var bbox = require('@turf/bbox');
  5. var truncate = require('@turf/truncate');
  6. var lineSegment = require('@turf/line-segment');
  7. var lineIntersect = require('@turf/line-intersect');
  8. var nearestPointOnLine = require('@turf/nearest-point-on-line');
  9. var invariant = require('@turf/invariant');
  10. var meta = require('@turf/meta');
  11. var helpers = require('@turf/helpers');
  12. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  13. var rbush__default = /*#__PURE__*/_interopDefaultLegacy(rbush);
  14. var square__default = /*#__PURE__*/_interopDefaultLegacy(square);
  15. var bbox__default = /*#__PURE__*/_interopDefaultLegacy(bbox);
  16. var truncate__default = /*#__PURE__*/_interopDefaultLegacy(truncate);
  17. var lineSegment__default = /*#__PURE__*/_interopDefaultLegacy(lineSegment);
  18. var lineIntersect__default = /*#__PURE__*/_interopDefaultLegacy(lineIntersect);
  19. var nearestPointOnLine__default = /*#__PURE__*/_interopDefaultLegacy(nearestPointOnLine);
  20. /**
  21. * Split a LineString by another GeoJSON Feature.
  22. *
  23. * @name lineSplit
  24. * @param {Feature<LineString>} line LineString Feature to split
  25. * @param {Feature<any>} splitter Feature used to split line
  26. * @returns {FeatureCollection<LineString>} Split LineStrings
  27. * @example
  28. * var line = turf.lineString([[120, -25], [145, -25]]);
  29. * var splitter = turf.lineString([[130, -15], [130, -35]]);
  30. *
  31. * var split = turf.lineSplit(line, splitter);
  32. *
  33. * //addToMap
  34. * var addToMap = [line, splitter]
  35. */
  36. function lineSplit(line, splitter) {
  37. if (!line) throw new Error("line is required");
  38. if (!splitter) throw new Error("splitter is required");
  39. var lineType = invariant.getType(line);
  40. var splitterType = invariant.getType(splitter);
  41. if (lineType !== "LineString") throw new Error("line must be LineString");
  42. if (splitterType === "FeatureCollection")
  43. throw new Error("splitter cannot be a FeatureCollection");
  44. if (splitterType === "GeometryCollection")
  45. throw new Error("splitter cannot be a GeometryCollection");
  46. // remove excessive decimals from splitter
  47. // to avoid possible approximation issues in rbush
  48. var truncatedSplitter = truncate__default['default'](splitter, { precision: 7 });
  49. switch (splitterType) {
  50. case "Point":
  51. return splitLineWithPoint(line, truncatedSplitter);
  52. case "MultiPoint":
  53. return splitLineWithPoints(line, truncatedSplitter);
  54. case "LineString":
  55. case "MultiLineString":
  56. case "Polygon":
  57. case "MultiPolygon":
  58. return splitLineWithPoints(line, lineIntersect__default['default'](line, truncatedSplitter));
  59. }
  60. }
  61. /**
  62. * Split LineString with MultiPoint
  63. *
  64. * @private
  65. * @param {Feature<LineString>} line LineString
  66. * @param {FeatureCollection<Point>} splitter Point
  67. * @returns {FeatureCollection<LineString>} split LineStrings
  68. */
  69. function splitLineWithPoints(line, splitter) {
  70. var results = [];
  71. var tree = rbush__default['default']();
  72. meta.flattenEach(splitter, function (point) {
  73. // Add index/id to features (needed for filter)
  74. results.forEach(function (feature, index) {
  75. feature.id = index;
  76. });
  77. // First Point - doesn't need to handle any previous line results
  78. if (!results.length) {
  79. results = splitLineWithPoint(line, point).features;
  80. // Add Square BBox to each feature for GeoJSON-RBush
  81. results.forEach(function (feature) {
  82. if (!feature.bbox) feature.bbox = square__default['default'](bbox__default['default'](feature));
  83. });
  84. tree.load(helpers.featureCollection(results));
  85. // Split with remaining points - lines might needed to be split multiple times
  86. } else {
  87. // Find all lines that are within the splitter's bbox
  88. var search = tree.search(point);
  89. if (search.features.length) {
  90. // RBush might return multiple lines - only process the closest line to splitter
  91. var closestLine = findClosestFeature(point, search);
  92. // Remove closest line from results since this will be split into two lines
  93. // This removes any duplicates inside the results & index
  94. results = results.filter(function (feature) {
  95. return feature.id !== closestLine.id;
  96. });
  97. tree.remove(closestLine);
  98. // Append the two newly split lines into the results
  99. meta.featureEach(splitLineWithPoint(closestLine, point), function (line) {
  100. results.push(line);
  101. tree.insert(line);
  102. });
  103. }
  104. }
  105. });
  106. return helpers.featureCollection(results);
  107. }
  108. /**
  109. * Split LineString with Point
  110. *
  111. * @private
  112. * @param {Feature<LineString>} line LineString
  113. * @param {Feature<Point>} splitter Point
  114. * @returns {FeatureCollection<LineString>} split LineStrings
  115. */
  116. function splitLineWithPoint(line, splitter) {
  117. var results = [];
  118. // handle endpoints
  119. var startPoint = invariant.getCoords(line)[0];
  120. var endPoint = invariant.getCoords(line)[line.geometry.coordinates.length - 1];
  121. if (
  122. pointsEquals(startPoint, invariant.getCoord(splitter)) ||
  123. pointsEquals(endPoint, invariant.getCoord(splitter))
  124. )
  125. return helpers.featureCollection([line]);
  126. // Create spatial index
  127. var tree = rbush__default['default']();
  128. var segments = lineSegment__default['default'](line);
  129. tree.load(segments);
  130. // Find all segments that are within bbox of splitter
  131. var search = tree.search(splitter);
  132. // Return itself if point is not within spatial index
  133. if (!search.features.length) return helpers.featureCollection([line]);
  134. // RBush might return multiple lines - only process the closest line to splitter
  135. var closestSegment = findClosestFeature(splitter, search);
  136. // Initial value is the first point of the first segments (beginning of line)
  137. var initialValue = [startPoint];
  138. var lastCoords = meta.featureReduce(
  139. segments,
  140. function (previous, current, index) {
  141. var currentCoords = invariant.getCoords(current)[1];
  142. var splitterCoords = invariant.getCoord(splitter);
  143. // Location where segment intersects with line
  144. if (index === closestSegment.id) {
  145. previous.push(splitterCoords);
  146. results.push(helpers.lineString(previous));
  147. // Don't duplicate splitter coordinate (Issue #688)
  148. if (pointsEquals(splitterCoords, currentCoords))
  149. return [splitterCoords];
  150. return [splitterCoords, currentCoords];
  151. // Keep iterating over coords until finished or intersection is found
  152. } else {
  153. previous.push(currentCoords);
  154. return previous;
  155. }
  156. },
  157. initialValue
  158. );
  159. // Append last line to final split results
  160. if (lastCoords.length > 1) {
  161. results.push(helpers.lineString(lastCoords));
  162. }
  163. return helpers.featureCollection(results);
  164. }
  165. /**
  166. * Find Closest Feature
  167. *
  168. * @private
  169. * @param {Feature<Point>} point Feature must be closest to this point
  170. * @param {FeatureCollection<LineString>} lines Collection of Features
  171. * @returns {Feature<LineString>} closest LineString
  172. */
  173. function findClosestFeature(point, lines) {
  174. if (!lines.features.length) throw new Error("lines must contain features");
  175. // Filter to one segment that is the closest to the line
  176. if (lines.features.length === 1) return lines.features[0];
  177. var closestFeature;
  178. var closestDistance = Infinity;
  179. meta.featureEach(lines, function (segment) {
  180. var pt = nearestPointOnLine__default['default'](segment, point);
  181. var dist = pt.properties.dist;
  182. if (dist < closestDistance) {
  183. closestFeature = segment;
  184. closestDistance = dist;
  185. }
  186. });
  187. return closestFeature;
  188. }
  189. /**
  190. * Compares two points and returns if they are equals
  191. *
  192. * @private
  193. * @param {Array<number>} pt1 point
  194. * @param {Array<number>} pt2 point
  195. * @returns {boolean} true if they are equals
  196. */
  197. function pointsEquals(pt1, pt2) {
  198. return pt1[0] === pt2[0] && pt1[1] === pt2[1];
  199. }
  200. module.exports = lineSplit;
  201. module.exports.default = lineSplit;