RegularPolygon.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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/Handler/Drag.js
  7. */
  8. /**
  9. * Class: OpenLayers.Handler.RegularPolygon
  10. * Handler to draw a regular polygon on the map. Polygon is displayed on mouse
  11. * down, moves or is modified on mouse move, and is finished on mouse up.
  12. * The handler triggers callbacks for 'done' and 'cancel'. Create a new
  13. * instance with the <OpenLayers.Handler.RegularPolygon> constructor.
  14. *
  15. * Inherits from:
  16. * - <OpenLayers.Handler.Drag>
  17. */
  18. OpenLayers.Handler.RegularPolygon = OpenLayers.Class(OpenLayers.Handler.Drag, {
  19. /**
  20. * APIProperty: sides
  21. * {Integer} Number of sides for the regular polygon. Needs to be greater
  22. * than 2. Defaults to 4.
  23. */
  24. sides: 4,
  25. /**
  26. * APIProperty: radius
  27. * {Float} Optional radius in map units of the regular polygon. If this is
  28. * set to some non-zero value, a polygon with a fixed radius will be
  29. * drawn and dragged with mose movements. If this property is not
  30. * set, dragging changes the radius of the polygon. Set to null by
  31. * default.
  32. */
  33. radius: null,
  34. /**
  35. * APIProperty: snapAngle
  36. * {Float} If set to a non-zero value, the handler will snap the polygon
  37. * rotation to multiples of the snapAngle. Value is an angle measured
  38. * in degrees counterclockwise from the positive x-axis.
  39. */
  40. snapAngle: null,
  41. /**
  42. * APIProperty: snapToggle
  43. * {String} If set, snapToggle is checked on mouse events and will set
  44. * the snap mode to the opposite of what it currently is. To disallow
  45. * toggling between snap and non-snap mode, set freehandToggle to
  46. * null. Acceptable toggle values are 'shiftKey', 'ctrlKey', and
  47. * 'altKey'. Snap mode is only possible if this.snapAngle is set to a
  48. * non-zero value.
  49. */
  50. snapToggle: 'shiftKey',
  51. /**
  52. * Property: layerOptions
  53. * {Object} Any optional properties to be set on the sketch layer.
  54. */
  55. layerOptions: null,
  56. /**
  57. * APIProperty: persist
  58. * {Boolean} Leave the feature rendered until clear is called. Default
  59. * is false. If set to true, the feature remains rendered until
  60. * clear is called, typically by deactivating the handler or starting
  61. * another drawing.
  62. */
  63. persist: false,
  64. /**
  65. * APIProperty: irregular
  66. * {Boolean} Draw an irregular polygon instead of a regular polygon.
  67. * Default is false. If true, the initial mouse down will represent
  68. * one corner of the polygon bounds and with each mouse movement, the
  69. * polygon will be stretched so the opposite corner of its bounds
  70. * follows the mouse position. This property takes precedence over
  71. * the radius property. If set to true, the radius property will
  72. * be ignored.
  73. */
  74. irregular: false,
  75. /**
  76. * APIProperty: citeCompliant
  77. * {Boolean} If set to true, coordinates of features drawn in a map extent
  78. * crossing the date line won't exceed the world bounds. Default is false.
  79. */
  80. citeCompliant: false,
  81. /**
  82. * Property: angle
  83. * {Float} The angle from the origin (mouse down) to the current mouse
  84. * position, in radians. This is measured counterclockwise from the
  85. * positive x-axis.
  86. */
  87. angle: null,
  88. /**
  89. * Property: fixedRadius
  90. * {Boolean} The polygon has a fixed radius. True if a radius is set before
  91. * drawing begins. False otherwise.
  92. */
  93. fixedRadius: false,
  94. /**
  95. * Property: feature
  96. * {<OpenLayers.Feature.Vector>} The currently drawn polygon feature
  97. */
  98. feature: null,
  99. /**
  100. * Property: layer
  101. * {<OpenLayers.Layer.Vector>} The temporary drawing layer
  102. */
  103. layer: null,
  104. /**
  105. * Property: origin
  106. * {<OpenLayers.Geometry.Point>} Location of the first mouse down
  107. */
  108. origin: null,
  109. /**
  110. * Constructor: OpenLayers.Handler.RegularPolygon
  111. * Create a new regular polygon handler.
  112. *
  113. * Parameters:
  114. * control - {<OpenLayers.Control>} The control that owns this handler
  115. * callbacks - {Object} An object with a properties whose values are
  116. * functions. Various callbacks described below.
  117. * options - {Object} An object with properties to be set on the handler.
  118. * If the options.sides property is not specified, the number of sides
  119. * will default to 4.
  120. *
  121. * Named callbacks:
  122. * create - Called when a sketch is first created. Callback called with
  123. * the creation point geometry and sketch feature.
  124. * done - Called when the sketch drawing is finished. The callback will
  125. * recieve a single argument, the sketch geometry.
  126. * cancel - Called when the handler is deactivated while drawing. The
  127. * cancel callback will receive a geometry.
  128. */
  129. initialize: function(control, callbacks, options) {
  130. if(!(options && options.layerOptions && options.layerOptions.styleMap)) {
  131. this.style = OpenLayers.Util.extend(OpenLayers.Feature.Vector.style['default'], {});
  132. }
  133. OpenLayers.Handler.Drag.prototype.initialize.apply(this,
  134. [control, callbacks, options]);
  135. this.options = (options) ? options : {};
  136. },
  137. /**
  138. * APIMethod: setOptions
  139. *
  140. * Parameters:
  141. * newOptions - {Object}
  142. */
  143. setOptions: function (newOptions) {
  144. OpenLayers.Util.extend(this.options, newOptions);
  145. OpenLayers.Util.extend(this, newOptions);
  146. },
  147. /**
  148. * APIMethod: activate
  149. * Turn on the handler.
  150. *
  151. * Returns:
  152. * {Boolean} The handler was successfully activated
  153. */
  154. activate: function() {
  155. var activated = false;
  156. if(OpenLayers.Handler.Drag.prototype.activate.apply(this, arguments)) {
  157. // create temporary vector layer for rendering geometry sketch
  158. var options = OpenLayers.Util.extend({
  159. displayInLayerSwitcher: false,
  160. // indicate that the temp vector layer will never be out of range
  161. // without this, resolution properties must be specified at the
  162. // map-level for this temporary layer to init its resolutions
  163. // correctly
  164. calculateInRange: OpenLayers.Function.True,
  165. wrapDateLine: this.citeCompliant
  166. }, this.layerOptions);
  167. this.layer = new OpenLayers.Layer.Vector(this.CLASS_NAME, options);
  168. this.map.addLayer(this.layer);
  169. activated = true;
  170. }
  171. return activated;
  172. },
  173. /**
  174. * APIMethod: deactivate
  175. * Turn off the handler.
  176. *
  177. * Returns:
  178. * {Boolean} The handler was successfully deactivated
  179. */
  180. deactivate: function() {
  181. var deactivated = false;
  182. if(OpenLayers.Handler.Drag.prototype.deactivate.apply(this, arguments)) {
  183. // call the cancel callback if mid-drawing
  184. if(this.dragging) {
  185. this.cancel();
  186. }
  187. // If a layer's map property is set to null, it means that that
  188. // layer isn't added to the map. Since we ourself added the layer
  189. // to the map in activate(), we can assume that if this.layer.map
  190. // is null it means that the layer has been destroyed (as a result
  191. // of map.destroy() for example.
  192. if (this.layer.map != null) {
  193. this.layer.destroy(false);
  194. if (this.feature) {
  195. this.feature.destroy();
  196. }
  197. }
  198. this.layer = null;
  199. this.feature = null;
  200. deactivated = true;
  201. }
  202. return deactivated;
  203. },
  204. /**
  205. * Method: down
  206. * Start drawing a new feature
  207. *
  208. * Parameters:
  209. * evt - {Event} The drag start event
  210. */
  211. down: function(evt) {
  212. this.fixedRadius = !!(this.radius);
  213. var maploc = this.layer.getLonLatFromViewPortPx(evt.xy);
  214. this.origin = new OpenLayers.Geometry.Point(maploc.lon, maploc.lat);
  215. // create the new polygon
  216. if(!this.fixedRadius || this.irregular) {
  217. // smallest radius should not be less one pixel in map units
  218. // VML doesn't behave well with smaller
  219. this.radius = this.map.getResolution();
  220. }
  221. if(this.persist) {
  222. this.clear();
  223. }
  224. this.feature = new OpenLayers.Feature.Vector();
  225. this.createGeometry();
  226. this.callback("create", [this.origin, this.feature]);
  227. this.layer.addFeatures([this.feature], {silent: true});
  228. this.layer.drawFeature(this.feature, this.style);
  229. },
  230. /**
  231. * Method: move
  232. * Respond to drag move events
  233. *
  234. * Parameters:
  235. * evt - {Evt} The move event
  236. */
  237. move: function(evt) {
  238. var maploc = this.layer.getLonLatFromViewPortPx(evt.xy);
  239. var point = new OpenLayers.Geometry.Point(maploc.lon, maploc.lat);
  240. if(this.irregular) {
  241. var ry = Math.sqrt(2) * Math.abs(point.y - this.origin.y) / 2;
  242. this.radius = Math.max(this.map.getResolution() / 2, ry);
  243. } else if(this.fixedRadius) {
  244. this.origin = point;
  245. } else {
  246. this.calculateAngle(point, evt);
  247. this.radius = Math.max(this.map.getResolution() / 2,
  248. point.distanceTo(this.origin));
  249. }
  250. this.modifyGeometry();
  251. if(this.irregular) {
  252. var dx = point.x - this.origin.x;
  253. var dy = point.y - this.origin.y;
  254. var ratio;
  255. if(dy == 0) {
  256. ratio = dx / (this.radius * Math.sqrt(2));
  257. } else {
  258. ratio = dx / dy;
  259. }
  260. this.feature.geometry.resize(1, this.origin, ratio);
  261. this.feature.geometry.move(dx / 2, dy / 2);
  262. }
  263. this.layer.drawFeature(this.feature, this.style);
  264. },
  265. /**
  266. * Method: up
  267. * Finish drawing the feature
  268. *
  269. * Parameters:
  270. * evt - {Event} The mouse up event
  271. */
  272. up: function(evt) {
  273. this.finalize();
  274. // the mouseup method of superclass doesn't call the
  275. // "done" callback if there's been no move between
  276. // down and up
  277. if (this.start == this.last) {
  278. this.callback("done", [evt.xy]);
  279. }
  280. },
  281. /**
  282. * Method: out
  283. * Finish drawing the feature.
  284. *
  285. * Parameters:
  286. * evt - {Event} The mouse out event
  287. */
  288. out: function(evt) {
  289. this.finalize();
  290. },
  291. /**
  292. * Method: createGeometry
  293. * Create the new polygon geometry. This is called at the start of the
  294. * drag and at any point during the drag if the number of sides
  295. * changes.
  296. */
  297. createGeometry: function() {
  298. this.angle = Math.PI * ((1/this.sides) - (1/2));
  299. if(this.snapAngle) {
  300. this.angle += this.snapAngle * (Math.PI / 180);
  301. }
  302. this.feature.geometry = OpenLayers.Geometry.Polygon.createRegularPolygon(
  303. this.origin, this.radius, this.sides, this.snapAngle
  304. );
  305. },
  306. /**
  307. * Method: modifyGeometry
  308. * Modify the polygon geometry in place.
  309. */
  310. modifyGeometry: function() {
  311. var angle, point;
  312. var ring = this.feature.geometry.components[0];
  313. // if the number of sides ever changes, create a new geometry
  314. if(ring.components.length != (this.sides + 1)) {
  315. this.createGeometry();
  316. ring = this.feature.geometry.components[0];
  317. }
  318. for(var i=0; i<this.sides; ++i) {
  319. point = ring.components[i];
  320. angle = this.angle + (i * 2 * Math.PI / this.sides);
  321. point.x = this.origin.x + (this.radius * Math.cos(angle));
  322. point.y = this.origin.y + (this.radius * Math.sin(angle));
  323. point.clearBounds();
  324. }
  325. },
  326. /**
  327. * Method: calculateAngle
  328. * Calculate the angle based on settings.
  329. *
  330. * Parameters:
  331. * point - {<OpenLayers.Geometry.Point>}
  332. * evt - {Event}
  333. */
  334. calculateAngle: function(point, evt) {
  335. var alpha = Math.atan2(point.y - this.origin.y,
  336. point.x - this.origin.x);
  337. if(this.snapAngle && (this.snapToggle && !evt[this.snapToggle])) {
  338. var snapAngleRad = (Math.PI / 180) * this.snapAngle;
  339. this.angle = Math.round(alpha / snapAngleRad) * snapAngleRad;
  340. } else {
  341. this.angle = alpha;
  342. }
  343. },
  344. /**
  345. * APIMethod: cancel
  346. * Finish the geometry and call the "cancel" callback.
  347. */
  348. cancel: function() {
  349. // the polygon geometry gets cloned in the callback method
  350. this.callback("cancel", null);
  351. this.finalize();
  352. },
  353. /**
  354. * Method: finalize
  355. * Finish the geometry and call the "done" callback.
  356. */
  357. finalize: function() {
  358. this.origin = null;
  359. this.radius = this.options.radius;
  360. },
  361. /**
  362. * APIMethod: clear
  363. * Clear any rendered features on the temporary layer. This is called
  364. * when the handler is deactivated, canceled, or done (unless persist
  365. * is true).
  366. */
  367. clear: function() {
  368. if (this.layer) {
  369. this.layer.renderer.clear();
  370. this.layer.destroyFeatures();
  371. }
  372. },
  373. /**
  374. * Method: callback
  375. * Trigger the control's named callback with the given arguments
  376. *
  377. * Parameters:
  378. * name - {String} The key for the callback that is one of the properties
  379. * of the handler's callbacks object.
  380. * args - {Array} An array of arguments with which to call the callback
  381. * (defined by the control).
  382. */
  383. callback: function (name, args) {
  384. // override the callback method to always send the polygon geometry
  385. if (this.callbacks[name]) {
  386. this.callbacks[name].apply(this.control,
  387. [this.feature.geometry.clone()]);
  388. }
  389. // since sketch features are added to the temporary layer
  390. // they must be cleared here if done or cancel
  391. if(!this.persist && (name == "done" || name == "cancel")) {
  392. this.clear();
  393. }
  394. },
  395. CLASS_NAME: "OpenLayers.Handler.RegularPolygon"
  396. });