Geometry.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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/BaseTypes/Class.js
  7. */
  8. /**
  9. * Class: OpenLayers.Geometry
  10. * A Geometry is a description of a geographic object. Create an instance of
  11. * this class with the <OpenLayers.Geometry> constructor. This is a base class,
  12. * typical geometry types are described by subclasses of this class.
  13. *
  14. * Note that if you use the <OpenLayers.Geometry.fromWKT> method, you must
  15. * explicitly include the OpenLayers.Format.WKT in your build.
  16. */
  17. OpenLayers.Geometry = OpenLayers.Class({
  18. /**
  19. * Property: id
  20. * {String} A unique identifier for this geometry.
  21. */
  22. id: null,
  23. /**
  24. * Property: parent
  25. * {<OpenLayers.Geometry>}This is set when a Geometry is added as component
  26. * of another geometry
  27. */
  28. parent: null,
  29. /**
  30. * Property: bounds
  31. * {<OpenLayers.Bounds>} The bounds of this geometry
  32. */
  33. bounds: null,
  34. /**
  35. * Constructor: OpenLayers.Geometry
  36. * Creates a geometry object.
  37. */
  38. initialize: function() {
  39. this.id = OpenLayers.Util.createUniqueID(this.CLASS_NAME+ "_");
  40. },
  41. /**
  42. * Method: destroy
  43. * Destroy this geometry.
  44. */
  45. destroy: function() {
  46. this.id = null;
  47. this.bounds = null;
  48. },
  49. /**
  50. * APIMethod: clone
  51. * Create a clone of this geometry. Does not set any non-standard
  52. * properties of the cloned geometry.
  53. *
  54. * Returns:
  55. * {<OpenLayers.Geometry>} An exact clone of this geometry.
  56. */
  57. clone: function() {
  58. return new OpenLayers.Geometry();
  59. },
  60. /**
  61. * Method: setBounds
  62. * Set the bounds for this Geometry.
  63. *
  64. * Parameters:
  65. * bounds - {<OpenLayers.Bounds>}
  66. */
  67. setBounds: function(bounds) {
  68. if (bounds) {
  69. this.bounds = bounds.clone();
  70. }
  71. },
  72. /**
  73. * Method: clearBounds
  74. * Nullify this components bounds and that of its parent as well.
  75. */
  76. clearBounds: function() {
  77. this.bounds = null;
  78. if (this.parent) {
  79. this.parent.clearBounds();
  80. }
  81. },
  82. /**
  83. * Method: extendBounds
  84. * Extend the existing bounds to include the new bounds.
  85. * If geometry's bounds is not yet set, then set a new Bounds.
  86. *
  87. * Parameters:
  88. * newBounds - {<OpenLayers.Bounds>}
  89. */
  90. extendBounds: function(newBounds){
  91. var bounds = this.getBounds();
  92. if (!bounds) {
  93. this.setBounds(newBounds);
  94. } else {
  95. this.bounds.extend(newBounds);
  96. }
  97. },
  98. /**
  99. * APIMethod: getBounds
  100. * Get the bounds for this Geometry. If bounds is not set, it
  101. * is calculated again, this makes queries faster.
  102. *
  103. * Returns:
  104. * {<OpenLayers.Bounds>}
  105. */
  106. getBounds: function() {
  107. if (this.bounds == null) {
  108. this.calculateBounds();
  109. }
  110. return this.bounds;
  111. },
  112. /**
  113. * APIMethod: calculateBounds
  114. * Recalculate the bounds for the geometry.
  115. */
  116. calculateBounds: function() {
  117. //
  118. // This should be overridden by subclasses.
  119. //
  120. },
  121. /**
  122. * APIMethod: distanceTo
  123. * Calculate the closest distance between two geometries (on the x-y plane).
  124. *
  125. * Parameters:
  126. * geometry - {<OpenLayers.Geometry>} The target geometry.
  127. * options - {Object} Optional properties for configuring the distance
  128. * calculation.
  129. *
  130. * Valid options depend on the specific geometry type.
  131. *
  132. * Returns:
  133. * {Number | Object} The distance between this geometry and the target.
  134. * If details is true, the return will be an object with distance,
  135. * x0, y0, x1, and x2 properties. The x0 and y0 properties represent
  136. * the coordinates of the closest point on this geometry. The x1 and y1
  137. * properties represent the coordinates of the closest point on the
  138. * target geometry.
  139. */
  140. distanceTo: function(geometry, options) {
  141. },
  142. /**
  143. * APIMethod: getVertices
  144. * Return a list of all points in this geometry.
  145. *
  146. * Parameters:
  147. * nodes - {Boolean} For lines, only return vertices that are
  148. * endpoints. If false, for lines, only vertices that are not
  149. * endpoints will be returned. If not provided, all vertices will
  150. * be returned.
  151. *
  152. * Returns:
  153. * {Array} A list of all vertices in the geometry.
  154. */
  155. getVertices: function(nodes) {
  156. },
  157. /**
  158. * Method: atPoint
  159. * Note - This is only an approximation based on the bounds of the
  160. * geometry.
  161. *
  162. * Parameters:
  163. * lonlat - {<OpenLayers.LonLat>|Object} OpenLayers.LonLat or an
  164. * object with a 'lon' and 'lat' properties.
  165. * toleranceLon - {float} Optional tolerance in Geometric Coords
  166. * toleranceLat - {float} Optional tolerance in Geographic Coords
  167. *
  168. * Returns:
  169. * {Boolean} Whether or not the geometry is at the specified location
  170. */
  171. atPoint: function(lonlat, toleranceLon, toleranceLat) {
  172. var atPoint = false;
  173. var bounds = this.getBounds();
  174. if ((bounds != null) && (lonlat != null)) {
  175. var dX = (toleranceLon != null) ? toleranceLon : 0;
  176. var dY = (toleranceLat != null) ? toleranceLat : 0;
  177. var toleranceBounds =
  178. new OpenLayers.Bounds(this.bounds.left - dX,
  179. this.bounds.bottom - dY,
  180. this.bounds.right + dX,
  181. this.bounds.top + dY);
  182. atPoint = toleranceBounds.containsLonLat(lonlat);
  183. }
  184. return atPoint;
  185. },
  186. /**
  187. * Method: getLength
  188. * Calculate the length of this geometry. This method is defined in
  189. * subclasses.
  190. *
  191. * Returns:
  192. * {Float} The length of the collection by summing its parts
  193. */
  194. getLength: function() {
  195. //to be overridden by geometries that actually have a length
  196. //
  197. return 0.0;
  198. },
  199. /**
  200. * Method: getArea
  201. * Calculate the area of this geometry. This method is defined in subclasses.
  202. *
  203. * Returns:
  204. * {Float} The area of the collection by summing its parts
  205. */
  206. getArea: function() {
  207. //to be overridden by geometries that actually have an area
  208. //
  209. return 0.0;
  210. },
  211. /**
  212. * APIMethod: getCentroid
  213. * Calculate the centroid of this geometry. This method is defined in subclasses.
  214. *
  215. * Returns:
  216. * {<OpenLayers.Geometry.Point>} The centroid of the collection
  217. */
  218. getCentroid: function() {
  219. return null;
  220. },
  221. /**
  222. * Method: toString
  223. * Returns a text representation of the geometry. If the WKT format is
  224. * included in a build, this will be the Well-Known Text
  225. * representation.
  226. *
  227. * Returns:
  228. * {String} String representation of this geometry.
  229. */
  230. toString: function() {
  231. var string;
  232. if (OpenLayers.Format && OpenLayers.Format.WKT) {
  233. string = OpenLayers.Format.WKT.prototype.write(
  234. new OpenLayers.Feature.Vector(this)
  235. );
  236. } else {
  237. string = Object.prototype.toString.call(this);
  238. }
  239. return string;
  240. },
  241. CLASS_NAME: "OpenLayers.Geometry"
  242. });
  243. /**
  244. * Function: OpenLayers.Geometry.fromWKT
  245. * Generate a geometry given a Well-Known Text string. For this method to
  246. * work, you must include the OpenLayers.Format.WKT in your build
  247. * explicitly.
  248. *
  249. * Parameters:
  250. * wkt - {String} A string representing the geometry in Well-Known Text.
  251. *
  252. * Returns:
  253. * {<OpenLayers.Geometry>} A geometry of the appropriate class.
  254. */
  255. OpenLayers.Geometry.fromWKT = function(wkt) {
  256. var geom;
  257. if (OpenLayers.Format && OpenLayers.Format.WKT) {
  258. var format = OpenLayers.Geometry.fromWKT.format;
  259. if (!format) {
  260. format = new OpenLayers.Format.WKT();
  261. OpenLayers.Geometry.fromWKT.format = format;
  262. }
  263. var result = format.read(wkt);
  264. if (result instanceof OpenLayers.Feature.Vector) {
  265. geom = result.geometry;
  266. } else if (OpenLayers.Util.isArray(result)) {
  267. var len = result.length;
  268. var components = new Array(len);
  269. for (var i=0; i<len; ++i) {
  270. components[i] = result[i].geometry;
  271. }
  272. geom = new OpenLayers.Geometry.Collection(components);
  273. }
  274. }
  275. return geom;
  276. };
  277. /**
  278. * Method: OpenLayers.Geometry.segmentsIntersect
  279. * Determine whether two line segments intersect. Optionally calculates
  280. * and returns the intersection point. This function is optimized for
  281. * cases where seg1.x2 >= seg2.x1 || seg2.x2 >= seg1.x1. In those
  282. * obvious cases where there is no intersection, the function should
  283. * not be called.
  284. *
  285. * Parameters:
  286. * seg1 - {Object} Object representing a segment with properties x1, y1, x2,
  287. * and y2. The start point is represented by x1 and y1. The end point
  288. * is represented by x2 and y2. Start and end are ordered so that x1 < x2.
  289. * seg2 - {Object} Object representing a segment with properties x1, y1, x2,
  290. * and y2. The start point is represented by x1 and y1. The end point
  291. * is represented by x2 and y2. Start and end are ordered so that x1 < x2.
  292. * options - {Object} Optional properties for calculating the intersection.
  293. *
  294. * Valid options:
  295. * point - {Boolean} Return the intersection point. If false, the actual
  296. * intersection point will not be calculated. If true and the segments
  297. * intersect, the intersection point will be returned. If true and
  298. * the segments do not intersect, false will be returned. If true and
  299. * the segments are coincident, true will be returned.
  300. * tolerance - {Number} If a non-null value is provided, if the segments are
  301. * within the tolerance distance, this will be considered an intersection.
  302. * In addition, if the point option is true and the calculated intersection
  303. * is within the tolerance distance of an end point, the endpoint will be
  304. * returned instead of the calculated intersection. Further, if the
  305. * intersection is within the tolerance of endpoints on both segments, or
  306. * if two segment endpoints are within the tolerance distance of eachother
  307. * (but no intersection is otherwise calculated), an endpoint on the
  308. * first segment provided will be returned.
  309. *
  310. * Returns:
  311. * {Boolean | <OpenLayers.Geometry.Point>} The two segments intersect.
  312. * If the point argument is true, the return will be the intersection
  313. * point or false if none exists. If point is true and the segments
  314. * are coincident, return will be true (and the instersection is equal
  315. * to the shorter segment).
  316. */
  317. OpenLayers.Geometry.segmentsIntersect = function(seg1, seg2, options) {
  318. var point = options && options.point;
  319. var tolerance = options && options.tolerance;
  320. var intersection = false;
  321. var x11_21 = seg1.x1 - seg2.x1;
  322. var y11_21 = seg1.y1 - seg2.y1;
  323. var x12_11 = seg1.x2 - seg1.x1;
  324. var y12_11 = seg1.y2 - seg1.y1;
  325. var y22_21 = seg2.y2 - seg2.y1;
  326. var x22_21 = seg2.x2 - seg2.x1;
  327. var d = (y22_21 * x12_11) - (x22_21 * y12_11);
  328. var n1 = (x22_21 * y11_21) - (y22_21 * x11_21);
  329. var n2 = (x12_11 * y11_21) - (y12_11 * x11_21);
  330. if(d == 0) {
  331. // parallel
  332. if(n1 == 0 && n2 == 0) {
  333. // coincident
  334. intersection = true;
  335. }
  336. } else {
  337. var along1 = n1 / d;
  338. var along2 = n2 / d;
  339. if(along1 >= 0 && along1 <= 1 && along2 >=0 && along2 <= 1) {
  340. // intersect
  341. if(!point) {
  342. intersection = true;
  343. } else {
  344. // calculate the intersection point
  345. var x = seg1.x1 + (along1 * x12_11);
  346. var y = seg1.y1 + (along1 * y12_11);
  347. intersection = new OpenLayers.Geometry.Point(x, y);
  348. }
  349. }
  350. }
  351. if(tolerance) {
  352. var dist;
  353. if(intersection) {
  354. if(point) {
  355. var segs = [seg1, seg2];
  356. var seg, x, y;
  357. // check segment endpoints for proximity to intersection
  358. // set intersection to first endpoint within the tolerance
  359. outer: for(var i=0; i<2; ++i) {
  360. seg = segs[i];
  361. for(var j=1; j<3; ++j) {
  362. x = seg["x" + j];
  363. y = seg["y" + j];
  364. dist = Math.sqrt(
  365. Math.pow(x - intersection.x, 2) +
  366. Math.pow(y - intersection.y, 2)
  367. );
  368. if(dist < tolerance) {
  369. intersection.x = x;
  370. intersection.y = y;
  371. break outer;
  372. }
  373. }
  374. }
  375. }
  376. } else {
  377. // no calculated intersection, but segments could be within
  378. // the tolerance of one another
  379. var segs = [seg1, seg2];
  380. var source, target, x, y, p, result;
  381. // check segment endpoints for proximity to intersection
  382. // set intersection to first endpoint within the tolerance
  383. outer: for(var i=0; i<2; ++i) {
  384. source = segs[i];
  385. target = segs[(i+1)%2];
  386. for(var j=1; j<3; ++j) {
  387. p = {x: source["x"+j], y: source["y"+j]};
  388. result = OpenLayers.Geometry.distanceToSegment(p, target);
  389. if(result.distance < tolerance) {
  390. if(point) {
  391. intersection = new OpenLayers.Geometry.Point(p.x, p.y);
  392. } else {
  393. intersection = true;
  394. }
  395. break outer;
  396. }
  397. }
  398. }
  399. }
  400. }
  401. return intersection;
  402. };
  403. /**
  404. * Function: OpenLayers.Geometry.distanceToSegment
  405. *
  406. * Parameters:
  407. * point - {Object} An object with x and y properties representing the
  408. * point coordinates.
  409. * segment - {Object} An object with x1, y1, x2, and y2 properties
  410. * representing endpoint coordinates.
  411. *
  412. * Returns:
  413. * {Object} An object with distance, along, x, and y properties. The distance
  414. * will be the shortest distance between the input point and segment.
  415. * The x and y properties represent the coordinates along the segment
  416. * where the shortest distance meets the segment. The along attribute
  417. * describes how far between the two segment points the given point is.
  418. */
  419. OpenLayers.Geometry.distanceToSegment = function(point, segment) {
  420. var result = OpenLayers.Geometry.distanceSquaredToSegment(point, segment);
  421. result.distance = Math.sqrt(result.distance);
  422. return result;
  423. };
  424. /**
  425. * Function: OpenLayers.Geometry.distanceSquaredToSegment
  426. *
  427. * Usually the distanceToSegment function should be used. This variant however
  428. * can be used for comparisons where the exact distance is not important.
  429. *
  430. * Parameters:
  431. * point - {Object} An object with x and y properties representing the
  432. * point coordinates.
  433. * segment - {Object} An object with x1, y1, x2, and y2 properties
  434. * representing endpoint coordinates.
  435. *
  436. * Returns:
  437. * {Object} An object with squared distance, along, x, and y properties.
  438. * The distance will be the shortest distance between the input point and
  439. * segment. The x and y properties represent the coordinates along the
  440. * segment where the shortest distance meets the segment. The along
  441. * attribute describes how far between the two segment points the given
  442. * point is.
  443. */
  444. OpenLayers.Geometry.distanceSquaredToSegment = function(point, segment) {
  445. var x0 = point.x;
  446. var y0 = point.y;
  447. var x1 = segment.x1;
  448. var y1 = segment.y1;
  449. var x2 = segment.x2;
  450. var y2 = segment.y2;
  451. var dx = x2 - x1;
  452. var dy = y2 - y1;
  453. var along = ((dx * (x0 - x1)) + (dy * (y0 - y1))) /
  454. (Math.pow(dx, 2) + Math.pow(dy, 2));
  455. var x, y;
  456. if(along <= 0.0) {
  457. x = x1;
  458. y = y1;
  459. } else if(along >= 1.0) {
  460. x = x2;
  461. y = y2;
  462. } else {
  463. x = x1 + along * dx;
  464. y = y1 + along * dy;
  465. }
  466. return {
  467. distance: Math.pow(x - x0, 2) + Math.pow(y - y0, 2),
  468. x: x, y: y,
  469. along: along
  470. };
  471. };