RegularPolygon.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for
  2. * full list of contributors). Published under the Clear BSD license.
  3. * See http://svn.openlayers.org/trunk/openlayers/license.txt 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. * Property: angle
  77. * {Float} The angle from the origin (mouse down) to the current mouse
  78. * position, in radians. This is measured counterclockwise from the
  79. * positive x-axis.
  80. */
  81. angle: null,
  82. /**
  83. * Property: fixedRadius
  84. * {Boolean} The polygon has a fixed radius. True if a radius is set before
  85. * drawing begins. False otherwise.
  86. */
  87. fixedRadius: false,
  88. /**
  89. * Property: feature
  90. * {<OpenLayers.Feature.Vector>} The currently drawn polygon feature
  91. */
  92. feature: null,
  93. /**
  94. * Property: layer
  95. * {<OpenLayers.Layer.Vector>} The temporary drawing layer
  96. */
  97. layer: null,
  98. /**
  99. * Property: origin
  100. * {<OpenLayers.Geometry.Point>} Location of the first mouse down
  101. */
  102. origin: null,
  103. /**
  104. * Constructor: OpenLayers.Handler.RegularPolygon
  105. * Create a new regular polygon handler.
  106. *
  107. * Parameters:
  108. * control - {<OpenLayers.Control>} The control that owns this handler
  109. * callbacks - {Object} An object with a properties whose values are
  110. * functions. Various callbacks described below.
  111. * options - {Object} An object with properties to be set on the handler.
  112. * If the options.sides property is not specified, the number of sides
  113. * will default to 4.
  114. *
  115. * Named callbacks:
  116. * create - Called when a sketch is first created. Callback called with
  117. * the creation point geometry and sketch feature.
  118. * done - Called when the sketch drawing is finished. The callback will
  119. * recieve a single argument, the sketch geometry.
  120. * cancel - Called when the handler is deactivated while drawing. The
  121. * cancel callback will receive a geometry.
  122. */
  123. initialize: function(control, callbacks, options) {
  124. if(!(options && options.layerOptions && options.layerOptions.styleMap)) {
  125. this.style = OpenLayers.Util.extend(OpenLayers.Feature.Vector.style['default'], {});
  126. }
  127. OpenLayers.Handler.Drag.prototype.initialize.apply(this,
  128. [control, callbacks, options]);
  129. this.options = (options) ? options : {};
  130. },
  131. /**
  132. * APIMethod: setOptions
  133. *
  134. * Parameters:
  135. * newOptions - {Object}
  136. */
  137. setOptions: function (newOptions) {
  138. OpenLayers.Util.extend(this.options, newOptions);
  139. OpenLayers.Util.extend(this, newOptions);
  140. },
  141. /**
  142. * APIMethod: activate
  143. * Turn on the handler.
  144. *
  145. * Return:
  146. * {Boolean} The handler was successfully activated
  147. */
  148. activate: function() {
  149. var activated = false;
  150. if(OpenLayers.Handler.Drag.prototype.activate.apply(this, arguments)) {
  151. // create temporary vector layer for rendering geometry sketch
  152. var options = OpenLayers.Util.extend({
  153. displayInLayerSwitcher: false,
  154. // indicate that the temp vector layer will never be out of range
  155. // without this, resolution properties must be specified at the
  156. // map-level for this temporary layer to init its resolutions
  157. // correctly
  158. calculateInRange: OpenLayers.Function.True
  159. }, this.layerOptions);
  160. this.layer = new OpenLayers.Layer.Vector(this.CLASS_NAME, options);
  161. this.map.addLayer(this.layer);
  162. activated = true;
  163. }
  164. return activated;
  165. },
  166. /**
  167. * APIMethod: deactivate
  168. * Turn off the handler.
  169. *
  170. * Return:
  171. * {Boolean} The handler was successfully deactivated
  172. */
  173. deactivate: function() {
  174. var deactivated = false;
  175. if(OpenLayers.Handler.Drag.prototype.deactivate.apply(this, arguments)) {
  176. // call the cancel callback if mid-drawing
  177. if(this.dragging) {
  178. this.cancel();
  179. }
  180. // If a layer's map property is set to null, it means that that
  181. // layer isn't added to the map. Since we ourself added the layer
  182. // to the map in activate(), we can assume that if this.layer.map
  183. // is null it means that the layer has been destroyed (as a result
  184. // of map.destroy() for example.
  185. if (this.layer.map != null) {
  186. this.layer.destroy(false);
  187. if (this.feature) {
  188. this.feature.destroy();
  189. }
  190. }
  191. this.layer = null;
  192. this.feature = null;
  193. deactivated = true;
  194. }
  195. return deactivated;
  196. },
  197. /**
  198. * Method: down
  199. * Start drawing a new feature
  200. *
  201. * Parameters:
  202. * evt - {Event} The drag start event
  203. */
  204. down: function(evt) {
  205. this.fixedRadius = !!(this.radius);
  206. var maploc = this.map.getLonLatFromPixel(evt.xy);
  207. this.origin = new OpenLayers.Geometry.Point(maploc.lon, maploc.lat);
  208. // create the new polygon
  209. if(!this.fixedRadius || this.irregular) {
  210. // smallest radius should not be less one pixel in map units
  211. // VML doesn't behave well with smaller
  212. this.radius = this.map.getResolution();
  213. }
  214. if(this.persist) {
  215. this.clear();
  216. }
  217. this.feature = new OpenLayers.Feature.Vector();
  218. this.createGeometry();
  219. this.callback("create", [this.origin, this.feature]);
  220. this.layer.addFeatures([this.feature], {silent: true});
  221. this.layer.drawFeature(this.feature, this.style);
  222. },
  223. /**
  224. * Method: move
  225. * Respond to drag move events
  226. *
  227. * Parameters:
  228. * evt - {Evt} The move event
  229. */
  230. move: function(evt) {
  231. var maploc = this.map.getLonLatFromPixel(evt.xy);
  232. var point = new OpenLayers.Geometry.Point(maploc.lon, maploc.lat);
  233. if(this.irregular) {
  234. var ry = Math.sqrt(2) * Math.abs(point.y - this.origin.y) / 2;
  235. this.radius = Math.max(this.map.getResolution() / 2, ry);
  236. } else if(this.fixedRadius) {
  237. this.origin = point;
  238. } else {
  239. this.calculateAngle(point, evt);
  240. this.radius = Math.max(this.map.getResolution() / 2,
  241. point.distanceTo(this.origin));
  242. }
  243. this.modifyGeometry();
  244. if(this.irregular) {
  245. var dx = point.x - this.origin.x;
  246. var dy = point.y - this.origin.y;
  247. var ratio;
  248. if(dy == 0) {
  249. ratio = dx / (this.radius * Math.sqrt(2));
  250. } else {
  251. ratio = dx / dy;
  252. }
  253. this.feature.geometry.resize(1, this.origin, ratio);
  254. this.feature.geometry.move(dx / 2, dy / 2);
  255. }
  256. this.layer.drawFeature(this.feature, this.style);
  257. },
  258. /**
  259. * Method: up
  260. * Finish drawing the feature
  261. *
  262. * Parameters:
  263. * evt - {Event} The mouse up event
  264. */
  265. up: function(evt) {
  266. this.finalize();
  267. // the mouseup method of superclass doesn't call the
  268. // "done" callback if there's been no move between
  269. // down and up
  270. if (this.start == this.last) {
  271. this.callback("done", [evt.xy]);
  272. }
  273. },
  274. /**
  275. * Method: out
  276. * Finish drawing the feature.
  277. *
  278. * Parameters:
  279. * evt - {Event} The mouse out event
  280. */
  281. out: function(evt) {
  282. this.finalize();
  283. },
  284. /**
  285. * Method: createGeometry
  286. * Create the new polygon geometry. This is called at the start of the
  287. * drag and at any point during the drag if the number of sides
  288. * changes.
  289. */
  290. createGeometry: function() {
  291. this.angle = Math.PI * ((1/this.sides) - (1/2));
  292. if(this.snapAngle) {
  293. this.angle += this.snapAngle * (Math.PI / 180);
  294. }
  295. this.feature.geometry = OpenLayers.Geometry.Polygon.createRegularPolygon(
  296. this.origin, this.radius, this.sides, this.snapAngle
  297. );
  298. },
  299. /**
  300. * Method: modifyGeometry
  301. * Modify the polygon geometry in place.
  302. */
  303. modifyGeometry: function() {
  304. var angle, point;
  305. var ring = this.feature.geometry.components[0];
  306. // if the number of sides ever changes, create a new geometry
  307. if(ring.components.length != (this.sides + 1)) {
  308. this.createGeometry();
  309. ring = this.feature.geometry.components[0];
  310. }
  311. for(var i=0; i<this.sides; ++i) {
  312. point = ring.components[i];
  313. angle = this.angle + (i * 2 * Math.PI / this.sides);
  314. point.x = this.origin.x + (this.radius * Math.cos(angle));
  315. point.y = this.origin.y + (this.radius * Math.sin(angle));
  316. point.clearBounds();
  317. }
  318. },
  319. /**
  320. * Method: calculateAngle
  321. * Calculate the angle based on settings.
  322. *
  323. * Parameters:
  324. * point - {<OpenLayers.Geometry.Point>}
  325. * evt - {Event}
  326. */
  327. calculateAngle: function(point, evt) {
  328. var alpha = Math.atan2(point.y - this.origin.y,
  329. point.x - this.origin.x);
  330. if(this.snapAngle && (this.snapToggle && !evt[this.snapToggle])) {
  331. var snapAngleRad = (Math.PI / 180) * this.snapAngle;
  332. this.angle = Math.round(alpha / snapAngleRad) * snapAngleRad;
  333. } else {
  334. this.angle = alpha;
  335. }
  336. },
  337. /**
  338. * APIMethod: cancel
  339. * Finish the geometry and call the "cancel" callback.
  340. */
  341. cancel: function() {
  342. // the polygon geometry gets cloned in the callback method
  343. this.callback("cancel", null);
  344. this.finalize();
  345. },
  346. /**
  347. * Method: finalize
  348. * Finish the geometry and call the "done" callback.
  349. */
  350. finalize: function() {
  351. this.origin = null;
  352. this.radius = this.options.radius;
  353. },
  354. /**
  355. * APIMethod: clear
  356. * Clear any rendered features on the temporary layer. This is called
  357. * when the handler is deactivated, canceled, or done (unless persist
  358. * is true).
  359. */
  360. clear: function() {
  361. if (this.layer) {
  362. this.layer.renderer.clear();
  363. this.layer.destroyFeatures();
  364. }
  365. },
  366. /**
  367. * Method: callback
  368. * Trigger the control's named callback with the given arguments
  369. *
  370. * Parameters:
  371. * name - {String} The key for the callback that is one of the properties
  372. * of the handler's callbacks object.
  373. * args - {Array} An array of arguments with which to call the callback
  374. * (defined by the control).
  375. */
  376. callback: function (name, args) {
  377. // override the callback method to always send the polygon geometry
  378. if (this.callbacks[name]) {
  379. this.callbacks[name].apply(this.control,
  380. [this.feature.geometry.clone()]);
  381. }
  382. // since sketch features are added to the temporary layer
  383. // they must be cleared here if done or cancel
  384. if(!this.persist && (name == "done" || name == "cancel")) {
  385. this.clear();
  386. }
  387. },
  388. CLASS_NAME: "OpenLayers.Handler.RegularPolygon"
  389. });