Project

General

Profile

Download (14.4 KB) Statistics
| Branch: | Tag: | Revision:
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

    
7
/**
8
 * @requires OpenLayers/Handler/Drag.js
9
 */
10

    
11
/**
12
 * Class: OpenLayers.Handler.RegularPolygon
13
 * Handler to draw a regular polygon on the map.  Polygon is displayed on mouse
14
 *     down, moves or is modified on mouse move, and is finished on mouse up.
15
 *     The handler triggers callbacks for 'done' and 'cancel'.  Create a new
16
 *     instance with the <OpenLayers.Handler.RegularPolygon> constructor.
17
 * 
18
 * Inherits from:
19
 *  - <OpenLayers.Handler.Drag>
20
 */
21
OpenLayers.Handler.RegularPolygon = OpenLayers.Class(OpenLayers.Handler.Drag, {
22
    
23
    /**
24
     * APIProperty: sides
25
     * {Integer} Number of sides for the regular polygon.  Needs to be greater
26
     *     than 2.  Defaults to 4.
27
     */
28
    sides: 4,
29

    
30
    /**
31
     * APIProperty: radius
32
     * {Float} Optional radius in map units of the regular polygon.  If this is
33
     *     set to some non-zero value, a polygon with a fixed radius will be
34
     *     drawn and dragged with mose movements.  If this property is not
35
     *     set, dragging changes the radius of the polygon.  Set to null by
36
     *     default.
37
     */
38
    radius: null,
39
    
40
    /**
41
     * APIProperty: snapAngle
42
     * {Float} If set to a non-zero value, the handler will snap the polygon
43
     *     rotation to multiples of the snapAngle.  Value is an angle measured
44
     *     in degrees counterclockwise from the positive x-axis.  
45
     */
46
    snapAngle: null,
47
    
48
    /**
49
     * APIProperty: snapToggle
50
     * {String} If set, snapToggle is checked on mouse events and will set
51
     *     the snap mode to the opposite of what it currently is.  To disallow
52
     *     toggling between snap and non-snap mode, set freehandToggle to
53
     *     null.  Acceptable toggle values are 'shiftKey', 'ctrlKey', and
54
     *     'altKey'. Snap mode is only possible if this.snapAngle is set to a
55
     *     non-zero value.
56
     */
57
    snapToggle: 'shiftKey',
58
    
59
    /**
60
     * Property: layerOptions
61
     * {Object} Any optional properties to be set on the sketch layer.
62
     */
63
    layerOptions: null,
64

    
65
    /**
66
     * APIProperty: persist
67
     * {Boolean} Leave the feature rendered until clear is called.  Default
68
     *     is false.  If set to true, the feature remains rendered until
69
     *     clear is called, typically by deactivating the handler or starting
70
     *     another drawing.
71
     */
72
    persist: false,
73

    
74
    /**
75
     * APIProperty: irregular
76
     * {Boolean} Draw an irregular polygon instead of a regular polygon.
77
     *     Default is false.  If true, the initial mouse down will represent
78
     *     one corner of the polygon bounds and with each mouse movement, the
79
     *     polygon will be stretched so the opposite corner of its bounds
80
     *     follows the mouse position.  This property takes precedence over
81
     *     the radius property.  If set to true, the radius property will
82
     *     be ignored.
83
     */
84
    irregular: false,
85

    
86
    /**
87
     * APIProperty: citeCompliant
88
     * {Boolean} If set to true, coordinates of features drawn in a map extent
89
     * crossing the date line won't exceed the world bounds. Default is false.
90
     */
91
    citeCompliant: false,
92

    
93
    /**
94
     * Property: angle
95
     * {Float} The angle from the origin (mouse down) to the current mouse
96
     *     position, in radians.  This is measured counterclockwise from the
97
     *     positive x-axis.
98
     */
99
    angle: null,
100

    
101
    /**
102
     * Property: fixedRadius
103
     * {Boolean} The polygon has a fixed radius.  True if a radius is set before
104
     *     drawing begins.  False otherwise.
105
     */
106
    fixedRadius: false,
107

    
108
    /**
109
     * Property: feature
110
     * {<OpenLayers.Feature.Vector>} The currently drawn polygon feature
111
     */
112
    feature: null,
113

    
114
    /**
115
     * Property: layer
116
     * {<OpenLayers.Layer.Vector>} The temporary drawing layer
117
     */
118
    layer: null,
119

    
120
    /**
121
     * Property: origin
122
     * {<OpenLayers.Geometry.Point>} Location of the first mouse down
123
     */
124
    origin: null,
125

    
126
    /**
127
     * Constructor: OpenLayers.Handler.RegularPolygon
128
     * Create a new regular polygon handler.
129
     *
130
     * Parameters:
131
     * control - {<OpenLayers.Control>} The control that owns this handler
132
     * callbacks - {Object} An object with a properties whose values are
133
     *     functions.  Various callbacks described below.
134
     * options - {Object} An object with properties to be set on the handler.
135
     *     If the options.sides property is not specified, the number of sides
136
     *     will default to 4.
137
     *
138
     * Named callbacks:
139
     * create - Called when a sketch is first created.  Callback called with
140
     *     the creation point geometry and sketch feature.
141
     * done - Called when the sketch drawing is finished.  The callback will
142
     *     recieve a single argument, the sketch geometry.
143
     * cancel - Called when the handler is deactivated while drawing.  The
144
     *     cancel callback will receive a geometry.
145
     */
146
    initialize: function(control, callbacks, options) {
147
        if(!(options && options.layerOptions && options.layerOptions.styleMap)) {
148
            this.style = OpenLayers.Util.extend(OpenLayers.Feature.Vector.style['default'], {});
149
        }
150

    
151
        OpenLayers.Handler.Drag.prototype.initialize.apply(this,
152
                                                [control, callbacks, options]);
153
        this.options = (options) ? options : {};
154
    },
155
    
156
    /**
157
     * APIMethod: setOptions
158
     * 
159
     * Parameters:
160
     * newOptions - {Object} 
161
     */
162
    setOptions: function (newOptions) {
163
        OpenLayers.Util.extend(this.options, newOptions);
164
        OpenLayers.Util.extend(this, newOptions);
165
    },
166
    
167
    /**
168
     * APIMethod: activate
169
     * Turn on the handler.
170
     *
171
     * Returns:
172
     * {Boolean} The handler was successfully activated
173
     */
174
    activate: function() {
175
        var activated = false;
176
        if(OpenLayers.Handler.Drag.prototype.activate.apply(this, arguments)) {
177
            // create temporary vector layer for rendering geometry sketch
178
            var options = OpenLayers.Util.extend({
179
                displayInLayerSwitcher: false,
180
                // indicate that the temp vector layer will never be out of range
181
                // without this, resolution properties must be specified at the
182
                // map-level for this temporary layer to init its resolutions
183
                // correctly
184
                calculateInRange: OpenLayers.Function.True,
185
                wrapDateLine: this.citeCompliant
186
            }, this.layerOptions);
187
            this.layer = new OpenLayers.Layer.Vector(this.CLASS_NAME, options);
188
            this.map.addLayer(this.layer);
189
            activated = true;
190
        }
191
        return activated;
192
    },
193

    
194
    /**
195
     * APIMethod: deactivate
196
     * Turn off the handler.
197
     *
198
     * Returns:
199
     * {Boolean} The handler was successfully deactivated
200
     */
201
    deactivate: function() {
202
        var deactivated = false;
203
        if(OpenLayers.Handler.Drag.prototype.deactivate.apply(this, arguments)) {
204
            // call the cancel callback if mid-drawing
205
            if(this.dragging) {
206
                this.cancel();
207
            }
208
            // If a layer's map property is set to null, it means that that
209
            // layer isn't added to the map. Since we ourself added the layer
210
            // to the map in activate(), we can assume that if this.layer.map
211
            // is null it means that the layer has been destroyed (as a result
212
            // of map.destroy() for example.
213
            if (this.layer.map != null) {
214
                this.layer.destroy(false);
215
                if (this.feature) {
216
                    this.feature.destroy();
217
                }
218
            }
219
            this.layer = null;
220
            this.feature = null;
221
            deactivated = true;
222
        }
223
        return deactivated;
224
    },
225
    
226
    /**
227
     * Method: down
228
     * Start drawing a new feature
229
     *
230
     * Parameters:
231
     * evt - {Event} The drag start event
232
     */
233
    down: function(evt) {
234
        this.fixedRadius = !!(this.radius);
235
        var maploc = this.layer.getLonLatFromViewPortPx(evt.xy); 
236
        this.origin = new OpenLayers.Geometry.Point(maploc.lon, maploc.lat);
237
        // create the new polygon
238
        if(!this.fixedRadius || this.irregular) {
239
            // smallest radius should not be less one pixel in map units
240
            // VML doesn't behave well with smaller
241
            this.radius = this.map.getResolution();
242
        }
243
        if(this.persist) {
244
            this.clear();
245
        }
246
        this.feature = new OpenLayers.Feature.Vector();
247
        this.createGeometry();
248
        this.callback("create", [this.origin, this.feature]);
249
        this.layer.addFeatures([this.feature], {silent: true});
250
        this.layer.drawFeature(this.feature, this.style);
251
    },
252
    
253
    /**
254
     * Method: move
255
     * Respond to drag move events
256
     *
257
     * Parameters:
258
     * evt - {Evt} The move event
259
     */
260
    move: function(evt) {
261
        var maploc = this.layer.getLonLatFromViewPortPx(evt.xy); 
262
        var point = new OpenLayers.Geometry.Point(maploc.lon, maploc.lat);
263
        if(this.irregular) {
264
            var ry = Math.sqrt(2) * Math.abs(point.y - this.origin.y) / 2;
265
            this.radius = Math.max(this.map.getResolution() / 2, ry);
266
        } else if(this.fixedRadius) {
267
            this.origin = point;
268
        } else {
269
            this.calculateAngle(point, evt);
270
            this.radius = Math.max(this.map.getResolution() / 2,
271
                                   point.distanceTo(this.origin));
272
        }
273
        this.modifyGeometry();
274
        if(this.irregular) {
275
            var dx = point.x - this.origin.x;
276
            var dy = point.y - this.origin.y;
277
            var ratio;
278
            if(dy == 0) {
279
                ratio = dx / (this.radius * Math.sqrt(2));
280
            } else {
281
                ratio = dx / dy;
282
            }
283
            this.feature.geometry.resize(1, this.origin, ratio);
284
            this.feature.geometry.move(dx / 2, dy / 2);
285
        }
286
        this.layer.drawFeature(this.feature, this.style);
287
    },
288

    
289
    /**
290
     * Method: up
291
     * Finish drawing the feature
292
     *
293
     * Parameters:
294
     * evt - {Event} The mouse up event
295
     */
296
    up: function(evt) {
297
        this.finalize();
298
        // the mouseup method of superclass doesn't call the
299
        // "done" callback if there's been no move between
300
        // down and up
301
        if (this.start == this.last) {
302
            this.callback("done", [evt.xy]);
303
        }
304
    },
305

    
306
    /**
307
     * Method: out
308
     * Finish drawing the feature.
309
     *
310
     * Parameters:
311
     * evt - {Event} The mouse out event
312
     */
313
    out: function(evt) {
314
        this.finalize();
315
    },
316

    
317
    /**
318
     * Method: createGeometry
319
     * Create the new polygon geometry.  This is called at the start of the
320
     *     drag and at any point during the drag if the number of sides
321
     *     changes.
322
     */
323
    createGeometry: function() {
324
        this.angle = Math.PI * ((1/this.sides) - (1/2));
325
        if(this.snapAngle) {
326
            this.angle += this.snapAngle * (Math.PI / 180);
327
        }
328
        this.feature.geometry = OpenLayers.Geometry.Polygon.createRegularPolygon(
329
            this.origin, this.radius, this.sides, this.snapAngle
330
        );
331
    },
332
    
333
    /**
334
     * Method: modifyGeometry
335
     * Modify the polygon geometry in place.
336
     */
337
    modifyGeometry: function() {
338
        var angle, point;
339
        var ring = this.feature.geometry.components[0];
340
        // if the number of sides ever changes, create a new geometry
341
        if(ring.components.length != (this.sides + 1)) {
342
            this.createGeometry();
343
            ring = this.feature.geometry.components[0];
344
        }
345
        for(var i=0; i<this.sides; ++i) {
346
            point = ring.components[i];
347
            angle = this.angle + (i * 2 * Math.PI / this.sides);
348
            point.x = this.origin.x + (this.radius * Math.cos(angle));
349
            point.y = this.origin.y + (this.radius * Math.sin(angle));
350
            point.clearBounds();
351
        }
352
    },
353
    
354
    /**
355
     * Method: calculateAngle
356
     * Calculate the angle based on settings.
357
     *
358
     * Parameters:
359
     * point - {<OpenLayers.Geometry.Point>}
360
     * evt - {Event}
361
     */
362
    calculateAngle: function(point, evt) {
363
        var alpha = Math.atan2(point.y - this.origin.y,
364
                               point.x - this.origin.x);
365
        if(this.snapAngle && (this.snapToggle && !evt[this.snapToggle])) {
366
            var snapAngleRad = (Math.PI / 180) * this.snapAngle;
367
            this.angle = Math.round(alpha / snapAngleRad) * snapAngleRad;
368
        } else {
369
            this.angle = alpha;
370
        }
371
    },
372

    
373
    /**
374
     * APIMethod: cancel
375
     * Finish the geometry and call the "cancel" callback.
376
     */
377
    cancel: function() {
378
        // the polygon geometry gets cloned in the callback method
379
        this.callback("cancel", null);
380
        this.finalize();
381
    },
382

    
383
    /**
384
     * Method: finalize
385
     * Finish the geometry and call the "done" callback.
386
     */
387
    finalize: function() {
388
        this.origin = null;
389
        this.radius = this.options.radius;
390
    },
391

    
392
    /**
393
     * APIMethod: clear
394
     * Clear any rendered features on the temporary layer.  This is called
395
     *     when the handler is deactivated, canceled, or done (unless persist
396
     *     is true).
397
     */
398
    clear: function() {
399
        if (this.layer) {
400
            this.layer.renderer.clear();
401
            this.layer.destroyFeatures();
402
        }
403
    },
404
    
405
    /**
406
     * Method: callback
407
     * Trigger the control's named callback with the given arguments
408
     *
409
     * Parameters:
410
     * name - {String} The key for the callback that is one of the properties
411
     *     of the handler's callbacks object.
412
     * args - {Array} An array of arguments with which to call the callback
413
     *     (defined by the control).
414
     */
415
    callback: function (name, args) {
416
        // override the callback method to always send the polygon geometry
417
        if (this.callbacks[name]) {
418
            this.callbacks[name].apply(this.control,
419
                                       [this.feature.geometry.clone()]);
420
        }
421
        // since sketch features are added to the temporary layer
422
        // they must be cleared here if done or cancel
423
        if(!this.persist && (name == "done" || name == "cancel")) {
424
            this.clear();
425
        }
426
    },
427

    
428
    CLASS_NAME: "OpenLayers.Handler.RegularPolygon"
429
});
(12-12/12)