LineString.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. /* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for
  2. * full list of contributors). Published under the 2-clause BSD license.
  3. * See license.txt in the OpenLayers distribution or repository for the
  4. * full text of the license. */
  5. /**
  6. * @requires OpenLayers/Geometry/Curve.js
  7. */
  8. /**
  9. * Class: OpenLayers.Geometry.LineString
  10. * A LineString is a Curve which, once two points have been added to it, can
  11. * never be less than two points long.
  12. *
  13. * Inherits from:
  14. * - <OpenLayers.Geometry.Curve>
  15. */
  16. OpenLayers.Geometry.LineString = OpenLayers.Class(OpenLayers.Geometry.Curve, {
  17. /**
  18. * Constructor: OpenLayers.Geometry.LineString
  19. * Create a new LineString geometry
  20. *
  21. * Parameters:
  22. * points - {Array(<OpenLayers.Geometry.Point>)} An array of points used to
  23. * generate the linestring
  24. *
  25. */
  26. /**
  27. * APIMethod: removeComponent
  28. * Only allows removal of a point if there are three or more points in
  29. * the linestring. (otherwise the result would be just a single point)
  30. *
  31. * Parameters:
  32. * point - {<OpenLayers.Geometry.Point>} The point to be removed
  33. *
  34. * Returns:
  35. * {Boolean} The component was removed.
  36. */
  37. removeComponent: function(point) {
  38. var removed = this.components && (this.components.length > 2);
  39. if (removed) {
  40. OpenLayers.Geometry.Collection.prototype.removeComponent.apply(this,
  41. arguments);
  42. }
  43. return removed;
  44. },
  45. /**
  46. * APIMethod: intersects
  47. * Test for instersection between two geometries. This is a cheapo
  48. * implementation of the Bently-Ottmann algorigithm. It doesn't
  49. * really keep track of a sweep line data structure. It is closer
  50. * to the brute force method, except that segments are sorted and
  51. * potential intersections are only calculated when bounding boxes
  52. * intersect.
  53. *
  54. * Parameters:
  55. * geometry - {<OpenLayers.Geometry>}
  56. *
  57. * Returns:
  58. * {Boolean} The input geometry intersects this geometry.
  59. */
  60. intersects: function(geometry) {
  61. var intersect = false;
  62. var type = geometry.CLASS_NAME;
  63. if(type == "OpenLayers.Geometry.LineString" ||
  64. type == "OpenLayers.Geometry.LinearRing" ||
  65. type == "OpenLayers.Geometry.Point") {
  66. var segs1 = this.getSortedSegments();
  67. var segs2;
  68. if(type == "OpenLayers.Geometry.Point") {
  69. segs2 = [{
  70. x1: geometry.x, y1: geometry.y,
  71. x2: geometry.x, y2: geometry.y
  72. }];
  73. } else {
  74. segs2 = geometry.getSortedSegments();
  75. }
  76. var seg1, seg1x1, seg1x2, seg1y1, seg1y2,
  77. seg2, seg2y1, seg2y2;
  78. // sweep right
  79. outer: for(var i=0, len=segs1.length; i<len; ++i) {
  80. seg1 = segs1[i];
  81. seg1x1 = seg1.x1;
  82. seg1x2 = seg1.x2;
  83. seg1y1 = seg1.y1;
  84. seg1y2 = seg1.y2;
  85. inner: for(var j=0, jlen=segs2.length; j<jlen; ++j) {
  86. seg2 = segs2[j];
  87. if(seg2.x1 > seg1x2) {
  88. // seg1 still left of seg2
  89. break;
  90. }
  91. if(seg2.x2 < seg1x1) {
  92. // seg2 still left of seg1
  93. continue;
  94. }
  95. seg2y1 = seg2.y1;
  96. seg2y2 = seg2.y2;
  97. if(Math.min(seg2y1, seg2y2) > Math.max(seg1y1, seg1y2)) {
  98. // seg2 above seg1
  99. continue;
  100. }
  101. if(Math.max(seg2y1, seg2y2) < Math.min(seg1y1, seg1y2)) {
  102. // seg2 below seg1
  103. continue;
  104. }
  105. if(OpenLayers.Geometry.segmentsIntersect(seg1, seg2)) {
  106. intersect = true;
  107. break outer;
  108. }
  109. }
  110. }
  111. } else {
  112. intersect = geometry.intersects(this);
  113. }
  114. return intersect;
  115. },
  116. /**
  117. * Method: getSortedSegments
  118. *
  119. * Returns:
  120. * {Array} An array of segment objects. Segment objects have properties
  121. * x1, y1, x2, and y2. The start point is represented by x1 and y1.
  122. * The end point is represented by x2 and y2. Start and end are
  123. * ordered so that x1 < x2.
  124. */
  125. getSortedSegments: function() {
  126. var numSeg = this.components.length - 1;
  127. var segments = new Array(numSeg), point1, point2;
  128. for(var i=0; i<numSeg; ++i) {
  129. point1 = this.components[i];
  130. point2 = this.components[i + 1];
  131. if(point1.x < point2.x) {
  132. segments[i] = {
  133. x1: point1.x,
  134. y1: point1.y,
  135. x2: point2.x,
  136. y2: point2.y
  137. };
  138. } else {
  139. segments[i] = {
  140. x1: point2.x,
  141. y1: point2.y,
  142. x2: point1.x,
  143. y2: point1.y
  144. };
  145. }
  146. }
  147. // more efficient to define this somewhere static
  148. function byX1(seg1, seg2) {
  149. return seg1.x1 - seg2.x1;
  150. }
  151. return segments.sort(byX1);
  152. },
  153. /**
  154. * Method: splitWithSegment
  155. * Split this geometry with the given segment.
  156. *
  157. * Parameters:
  158. * seg - {Object} An object with x1, y1, x2, and y2 properties referencing
  159. * segment endpoint coordinates.
  160. * options - {Object} Properties of this object will be used to determine
  161. * how the split is conducted.
  162. *
  163. * Valid options:
  164. * edge - {Boolean} Allow splitting when only edges intersect. Default is
  165. * true. If false, a vertex on the source segment must be within the
  166. * tolerance distance of the intersection to be considered a split.
  167. * tolerance - {Number} If a non-null value is provided, intersections
  168. * within the tolerance distance of one of the source segment's
  169. * endpoints will be assumed to occur at the endpoint.
  170. *
  171. * Returns:
  172. * {Object} An object with *lines* and *points* properties. If the given
  173. * segment intersects this linestring, the lines array will reference
  174. * geometries that result from the split. The points array will contain
  175. * all intersection points. Intersection points are sorted along the
  176. * segment (in order from x1,y1 to x2,y2).
  177. */
  178. splitWithSegment: function(seg, options) {
  179. var edge = !(options && options.edge === false);
  180. var tolerance = options && options.tolerance;
  181. var lines = [];
  182. var verts = this.getVertices();
  183. var points = [];
  184. var intersections = [];
  185. var split = false;
  186. var vert1, vert2, point;
  187. var node, vertex, target;
  188. var interOptions = {point: true, tolerance: tolerance};
  189. var result = null;
  190. for(var i=0, stop=verts.length-2; i<=stop; ++i) {
  191. vert1 = verts[i];
  192. points.push(vert1.clone());
  193. vert2 = verts[i+1];
  194. target = {x1: vert1.x, y1: vert1.y, x2: vert2.x, y2: vert2.y};
  195. point = OpenLayers.Geometry.segmentsIntersect(
  196. seg, target, interOptions
  197. );
  198. if(point instanceof OpenLayers.Geometry.Point) {
  199. if((point.x === seg.x1 && point.y === seg.y1) ||
  200. (point.x === seg.x2 && point.y === seg.y2) ||
  201. point.equals(vert1) || point.equals(vert2)) {
  202. vertex = true;
  203. } else {
  204. vertex = false;
  205. }
  206. if(vertex || edge) {
  207. // push intersections different than the previous
  208. if(!point.equals(intersections[intersections.length-1])) {
  209. intersections.push(point.clone());
  210. }
  211. if(i === 0) {
  212. if(point.equals(vert1)) {
  213. continue;
  214. }
  215. }
  216. if(point.equals(vert2)) {
  217. continue;
  218. }
  219. split = true;
  220. if(!point.equals(vert1)) {
  221. points.push(point);
  222. }
  223. lines.push(new OpenLayers.Geometry.LineString(points));
  224. points = [point.clone()];
  225. }
  226. }
  227. }
  228. if(split) {
  229. points.push(vert2.clone());
  230. lines.push(new OpenLayers.Geometry.LineString(points));
  231. }
  232. if(intersections.length > 0) {
  233. // sort intersections along segment
  234. var xDir = seg.x1 < seg.x2 ? 1 : -1;
  235. var yDir = seg.y1 < seg.y2 ? 1 : -1;
  236. result = {
  237. lines: lines,
  238. points: intersections.sort(function(p1, p2) {
  239. return (xDir * p1.x - xDir * p2.x) || (yDir * p1.y - yDir * p2.y);
  240. })
  241. };
  242. }
  243. return result;
  244. },
  245. /**
  246. * Method: split
  247. * Use this geometry (the source) to attempt to split a target geometry.
  248. *
  249. * Parameters:
  250. * target - {<OpenLayers.Geometry>} The target geometry.
  251. * options - {Object} Properties of this object will be used to determine
  252. * how the split is conducted.
  253. *
  254. * Valid options:
  255. * mutual - {Boolean} Split the source geometry in addition to the target
  256. * geometry. Default is false.
  257. * edge - {Boolean} Allow splitting when only edges intersect. Default is
  258. * true. If false, a vertex on the source must be within the tolerance
  259. * distance of the intersection to be considered a split.
  260. * tolerance - {Number} If a non-null value is provided, intersections
  261. * within the tolerance distance of an existing vertex on the source
  262. * will be assumed to occur at the vertex.
  263. *
  264. * Returns:
  265. * {Array} A list of geometries (of this same type as the target) that
  266. * result from splitting the target with the source geometry. The
  267. * source and target geometry will remain unmodified. If no split
  268. * results, null will be returned. If mutual is true and a split
  269. * results, return will be an array of two arrays - the first will be
  270. * all geometries that result from splitting the source geometry and
  271. * the second will be all geometries that result from splitting the
  272. * target geometry.
  273. */
  274. split: function(target, options) {
  275. var results = null;
  276. var mutual = options && options.mutual;
  277. var sourceSplit, targetSplit, sourceParts, targetParts;
  278. if(target instanceof OpenLayers.Geometry.LineString) {
  279. var verts = this.getVertices();
  280. var vert1, vert2, seg, splits, lines, point;
  281. var points = [];
  282. sourceParts = [];
  283. for(var i=0, stop=verts.length-2; i<=stop; ++i) {
  284. vert1 = verts[i];
  285. vert2 = verts[i+1];
  286. seg = {
  287. x1: vert1.x, y1: vert1.y,
  288. x2: vert2.x, y2: vert2.y
  289. };
  290. targetParts = targetParts || [target];
  291. if(mutual) {
  292. points.push(vert1.clone());
  293. }
  294. for(var j=0; j<targetParts.length; ++j) {
  295. splits = targetParts[j].splitWithSegment(seg, options);
  296. if(splits) {
  297. // splice in new features
  298. lines = splits.lines;
  299. if(lines.length > 0) {
  300. lines.unshift(j, 1);
  301. Array.prototype.splice.apply(targetParts, lines);
  302. j += lines.length - 2;
  303. }
  304. if(mutual) {
  305. for(var k=0, len=splits.points.length; k<len; ++k) {
  306. point = splits.points[k];
  307. if(!point.equals(vert1)) {
  308. points.push(point);
  309. sourceParts.push(new OpenLayers.Geometry.LineString(points));
  310. if(point.equals(vert2)) {
  311. points = [];
  312. } else {
  313. points = [point.clone()];
  314. }
  315. }
  316. }
  317. }
  318. }
  319. }
  320. }
  321. if(mutual && sourceParts.length > 0 && points.length > 0) {
  322. points.push(vert2.clone());
  323. sourceParts.push(new OpenLayers.Geometry.LineString(points));
  324. }
  325. } else {
  326. results = target.splitWith(this, options);
  327. }
  328. if(targetParts && targetParts.length > 1) {
  329. targetSplit = true;
  330. } else {
  331. targetParts = [];
  332. }
  333. if(sourceParts && sourceParts.length > 1) {
  334. sourceSplit = true;
  335. } else {
  336. sourceParts = [];
  337. }
  338. if(targetSplit || sourceSplit) {
  339. if(mutual) {
  340. results = [sourceParts, targetParts];
  341. } else {
  342. results = targetParts;
  343. }
  344. }
  345. return results;
  346. },
  347. /**
  348. * Method: splitWith
  349. * Split this geometry (the target) with the given geometry (the source).
  350. *
  351. * Parameters:
  352. * geometry - {<OpenLayers.Geometry>} A geometry used to split this
  353. * geometry (the source).
  354. * options - {Object} Properties of this object will be used to determine
  355. * how the split is conducted.
  356. *
  357. * Valid options:
  358. * mutual - {Boolean} Split the source geometry in addition to the target
  359. * geometry. Default is false.
  360. * edge - {Boolean} Allow splitting when only edges intersect. Default is
  361. * true. If false, a vertex on the source must be within the tolerance
  362. * distance of the intersection to be considered a split.
  363. * tolerance - {Number} If a non-null value is provided, intersections
  364. * within the tolerance distance of an existing vertex on the source
  365. * will be assumed to occur at the vertex.
  366. *
  367. * Returns:
  368. * {Array} A list of geometries (of this same type as the target) that
  369. * result from splitting the target with the source geometry. The
  370. * source and target geometry will remain unmodified. If no split
  371. * results, null will be returned. If mutual is true and a split
  372. * results, return will be an array of two arrays - the first will be
  373. * all geometries that result from splitting the source geometry and
  374. * the second will be all geometries that result from splitting the
  375. * target geometry.
  376. */
  377. splitWith: function(geometry, options) {
  378. return geometry.split(this, options);
  379. },
  380. /**
  381. * APIMethod: getVertices
  382. * Return a list of all points in this geometry.
  383. *
  384. * Parameters:
  385. * nodes - {Boolean} For lines, only return vertices that are
  386. * endpoints. If false, for lines, only vertices that are not
  387. * endpoints will be returned. If not provided, all vertices will
  388. * be returned.
  389. *
  390. * Returns:
  391. * {Array} A list of all vertices in the geometry.
  392. */
  393. getVertices: function(nodes) {
  394. var vertices;
  395. if(nodes === true) {
  396. vertices = [
  397. this.components[0],
  398. this.components[this.components.length-1]
  399. ];
  400. } else if (nodes === false) {
  401. vertices = this.components.slice(1, this.components.length-1);
  402. } else {
  403. vertices = this.components.slice();
  404. }
  405. return vertices;
  406. },
  407. /**
  408. * APIMethod: distanceTo
  409. * Calculate the closest distance between two geometries (on the x-y plane).
  410. *
  411. * Parameters:
  412. * geometry - {<OpenLayers.Geometry>} The target geometry.
  413. * options - {Object} Optional properties for configuring the distance
  414. * calculation.
  415. *
  416. * Valid options:
  417. * details - {Boolean} Return details from the distance calculation.
  418. * Default is false.
  419. * edge - {Boolean} Calculate the distance from this geometry to the
  420. * nearest edge of the target geometry. Default is true. If true,
  421. * calling distanceTo from a geometry that is wholly contained within
  422. * the target will result in a non-zero distance. If false, whenever
  423. * geometries intersect, calling distanceTo will return 0. If false,
  424. * details cannot be returned.
  425. *
  426. * Returns:
  427. * {Number | Object} The distance between this geometry and the target.
  428. * If details is true, the return will be an object with distance,
  429. * x0, y0, x1, and x2 properties. The x0 and y0 properties represent
  430. * the coordinates of the closest point on this geometry. The x1 and y1
  431. * properties represent the coordinates of the closest point on the
  432. * target geometry.
  433. */
  434. distanceTo: function(geometry, options) {
  435. var edge = !(options && options.edge === false);
  436. var details = edge && options && options.details;
  437. var result, best = {};
  438. var min = Number.POSITIVE_INFINITY;
  439. if(geometry instanceof OpenLayers.Geometry.Point) {
  440. var segs = this.getSortedSegments();
  441. var x = geometry.x;
  442. var y = geometry.y;
  443. var seg;
  444. for(var i=0, len=segs.length; i<len; ++i) {
  445. seg = segs[i];
  446. result = OpenLayers.Geometry.distanceToSegment(geometry, seg);
  447. if(result.distance < min) {
  448. min = result.distance;
  449. best = result;
  450. if(min === 0) {
  451. break;
  452. }
  453. } else {
  454. // if distance increases and we cross y0 to the right of x0, no need to keep looking.
  455. if(seg.x2 > x && ((y > seg.y1 && y < seg.y2) || (y < seg.y1 && y > seg.y2))) {
  456. break;
  457. }
  458. }
  459. }
  460. if(details) {
  461. best = {
  462. distance: best.distance,
  463. x0: best.x, y0: best.y,
  464. x1: x, y1: y
  465. };
  466. } else {
  467. best = best.distance;
  468. }
  469. } else if(geometry instanceof OpenLayers.Geometry.LineString) {
  470. var segs0 = this.getSortedSegments();
  471. var segs1 = geometry.getSortedSegments();
  472. var seg0, seg1, intersection, x0, y0;
  473. var len1 = segs1.length;
  474. var interOptions = {point: true};
  475. outer: for(var i=0, len=segs0.length; i<len; ++i) {
  476. seg0 = segs0[i];
  477. x0 = seg0.x1;
  478. y0 = seg0.y1;
  479. for(var j=0; j<len1; ++j) {
  480. seg1 = segs1[j];
  481. intersection = OpenLayers.Geometry.segmentsIntersect(seg0, seg1, interOptions);
  482. if(intersection) {
  483. min = 0;
  484. best = {
  485. distance: 0,
  486. x0: intersection.x, y0: intersection.y,
  487. x1: intersection.x, y1: intersection.y
  488. };
  489. break outer;
  490. } else {
  491. result = OpenLayers.Geometry.distanceToSegment({x: x0, y: y0}, seg1);
  492. if(result.distance < min) {
  493. min = result.distance;
  494. best = {
  495. distance: min,
  496. x0: x0, y0: y0,
  497. x1: result.x, y1: result.y
  498. };
  499. }
  500. }
  501. }
  502. }
  503. if(!details) {
  504. best = best.distance;
  505. }
  506. if(min !== 0) {
  507. // check the final vertex in this line's sorted segments
  508. if(seg0) {
  509. result = geometry.distanceTo(
  510. new OpenLayers.Geometry.Point(seg0.x2, seg0.y2),
  511. options
  512. );
  513. var dist = details ? result.distance : result;
  514. if(dist < min) {
  515. if(details) {
  516. best = {
  517. distance: min,
  518. x0: result.x1, y0: result.y1,
  519. x1: result.x0, y1: result.y0
  520. };
  521. } else {
  522. best = dist;
  523. }
  524. }
  525. }
  526. }
  527. } else {
  528. best = geometry.distanceTo(this, options);
  529. // swap since target comes from this line
  530. if(details) {
  531. best = {
  532. distance: best.distance,
  533. x0: best.x1, y0: best.y1,
  534. x1: best.x0, y1: best.y0
  535. };
  536. }
  537. }
  538. return best;
  539. },
  540. /**
  541. * APIMethod: simplify
  542. * This function will return a simplified LineString.
  543. * Simplification is based on the Douglas-Peucker algorithm.
  544. *
  545. *
  546. * Parameters:
  547. * tolerance - {number} threshhold for simplification in map units
  548. *
  549. * Returns:
  550. * {OpenLayers.Geometry.LineString} the simplified LineString
  551. */
  552. simplify: function(tolerance){
  553. if (this && this !== null) {
  554. var points = this.getVertices();
  555. if (points.length < 3) {
  556. return this;
  557. }
  558. var compareNumbers = function(a, b){
  559. return (a-b);
  560. };
  561. /**
  562. * Private function doing the Douglas-Peucker reduction
  563. */
  564. var douglasPeuckerReduction = function(points, firstPoint, lastPoint, tolerance){
  565. var maxDistance = 0;
  566. var indexFarthest = 0;
  567. for (var index = firstPoint, distance; index < lastPoint; index++) {
  568. distance = perpendicularDistance(points[firstPoint], points[lastPoint], points[index]);
  569. if (distance > maxDistance) {
  570. maxDistance = distance;
  571. indexFarthest = index;
  572. }
  573. }
  574. if (maxDistance > tolerance && indexFarthest != firstPoint) {
  575. //Add the largest point that exceeds the tolerance
  576. pointIndexsToKeep.push(indexFarthest);
  577. douglasPeuckerReduction(points, firstPoint, indexFarthest, tolerance);
  578. douglasPeuckerReduction(points, indexFarthest, lastPoint, tolerance);
  579. }
  580. };
  581. /**
  582. * Private function calculating the perpendicular distance
  583. * TODO: check whether OpenLayers.Geometry.LineString::distanceTo() is faster or slower
  584. */
  585. var perpendicularDistance = function(point1, point2, point){
  586. //Area = |(1/2)(x1y2 + x2y3 + x3y1 - x2y1 - x3y2 - x1y3)| *Area of triangle
  587. //Base = v((x1-x2)²+(x1-x2)²) *Base of Triangle*
  588. //Area = .5*Base*H *Solve for height
  589. //Height = Area/.5/Base
  590. var area = Math.abs(0.5 * (point1.x * point2.y + point2.x * point.y + point.x * point1.y - point2.x * point1.y - point.x * point2.y - point1.x * point.y));
  591. var bottom = Math.sqrt(Math.pow(point1.x - point2.x, 2) + Math.pow(point1.y - point2.y, 2));
  592. var height = area / bottom * 2;
  593. return height;
  594. };
  595. var firstPoint = 0;
  596. var lastPoint = points.length - 1;
  597. var pointIndexsToKeep = [];
  598. //Add the first and last index to the keepers
  599. pointIndexsToKeep.push(firstPoint);
  600. pointIndexsToKeep.push(lastPoint);
  601. //The first and the last point cannot be the same
  602. while (points[firstPoint].equals(points[lastPoint])) {
  603. lastPoint--;
  604. //Addition: the first point not equal to first point in the LineString is kept as well
  605. pointIndexsToKeep.push(lastPoint);
  606. }
  607. douglasPeuckerReduction(points, firstPoint, lastPoint, tolerance);
  608. var returnPoints = [];
  609. pointIndexsToKeep.sort(compareNumbers);
  610. for (var index = 0; index < pointIndexsToKeep.length; index++) {
  611. returnPoints.push(points[pointIndexsToKeep[index]]);
  612. }
  613. return new OpenLayers.Geometry.LineString(returnPoints);
  614. }
  615. else {
  616. return this;
  617. }
  618. },
  619. CLASS_NAME: "OpenLayers.Geometry.LineString"
  620. });