Bienvenue sur PostGIS.fr

Bienvenue sur PostGIS.fr , le site de la communauté des utilisateurs francophones de PostGIS.

PostGIS ajoute le support d'objets géographique à la base de données PostgreSQL. En effet, PostGIS "spatialise" le serverur PostgreSQL, ce qui permet de l'utiliser comme une base de données SIG.

Maintenu à jour, en fonction de nos disponibilités et des diverses sorties des outils que nous testons, nous vous proposons l'ensemble de nos travaux publiés en langue française.

source: trunk/workshop-routing-foss4g/web/OpenLayers/lib/OpenLayers/Layer/WFS.js @ 76

Revision 76, 20.1 KB checked in by djay, 12 years ago (diff)

Ajout du répertoire web

  • Property svn:executable set to *
Line 
1/* Copyright (c) 2006-2010 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
7/**
8 * @requires OpenLayers/Tile/WFS.js
9 * @requires OpenLayers/Layer/Vector.js
10 * @requires OpenLayers/Layer/Markers.js
11 * @requires OpenLayers/Console.js
12 */
13
14/**
15 * Class: OpenLayers.Layer.WFS
16 * *Deprecated*.  To be removed in 3.0.  Instead use OpenLayers.Layer.Vector
17 *     with a Protocol.WFS and one or more Strategies.
18 *
19 * Inherits from:
20 *  - <OpenLayers.Layer.Vector>
21 *  - <OpenLayers.Layer.Markers>
22 */
23OpenLayers.Layer.WFS = OpenLayers.Class(
24  OpenLayers.Layer.Vector, OpenLayers.Layer.Markers, {
25
26    /**
27     * APIProperty: isBaseLayer
28     * {Boolean} WFS layer is not a base layer by default.
29     */
30    isBaseLayer: false,
31   
32    /**
33     * Property: tile
34     * {<OpenLayers.Tile.WFS>}
35     */
36    tile: null,   
37   
38    /**
39     * APIProperty: ratio
40     * {Float} The ratio property determines the size of the serverside query
41     *    relative to the map viewport size. By default, we load an area twice
42     *    as big as the map, to allow for panning without immediately reload.
43     *    Setting this to 1 will cause the area of the WFS request to match
44     *    the map area exactly. It is recommended to set this to some number
45     *    at least slightly larger than 1, otherwise accidental clicks can
46     *    cause a data reload, by moving the map only 1 pixel.
47     */
48    ratio: 2,
49
50    /** 
51     * Property: DEFAULT_PARAMS
52     * {Object} Hashtable of default key/value parameters
53     */
54    DEFAULT_PARAMS: { service: "WFS",
55                      version: "1.0.0",
56                      request: "GetFeature"
57                    },
58   
59    /**
60     * APIProperty: featureClass
61     * {<OpenLayers.Feature>} If featureClass is defined, an old-style markers
62     *     based WFS layer is created instead of a new-style vector layer. If
63     *     sent, this should be a subclass of OpenLayers.Feature
64     */
65    featureClass: null,
66   
67    /**
68      * APIProperty: format
69      * {<OpenLayers.Format>} The format you want the data to be parsed with.
70      * Must be passed in the constructor. Should be a class, not an instance.
71      * This option can only be used if no featureClass is passed / vectorMode
72      * is false: if a featureClass is passed, then this parameter is ignored.
73      */
74    format: null,
75
76    /**
77     * Property: formatObject
78     * {<OpenLayers.Format>} Internally created/managed format object, used by
79     * the Tile to parse data.
80     */
81    formatObject: null,
82
83    /**
84     * APIProperty: formatOptions
85     * {Object} Hash of options which should be passed to the format when it is
86     * created. Must be passed in the constructor.
87     */
88    formatOptions: null, 
89
90    /**
91     * Property: vectorMode
92     * {Boolean} Should be calculated automatically. Determines whether the
93     *     layer is in vector mode or marker mode.
94     */
95    vectorMode: true, 
96   
97    /**
98     * APIProperty: encodeBBOX
99     * {Boolean} Should the BBOX commas be encoded? The WMS spec says 'no',
100     *     but some services want it that way. Default false.
101     */
102    encodeBBOX: false,
103   
104    /**
105     * APIProperty: extractAttributes
106     * {Boolean} Should the WFS layer parse attributes from the retrieved
107     *     GML? Defaults to false. If enabled, parsing is slower, but
108     *     attributes are available in the attributes property of
109     *     layer features.
110     */
111    extractAttributes: false,
112
113    /**
114     * Constructor: OpenLayers.Layer.WFS
115     *
116     * Parameters:
117     * name - {String}
118     * url - {String}
119     * params - {Object}
120     * options - {Object} Hashtable of extra options to tag onto the layer
121     */
122    initialize: function(name, url, params, options) {
123        if (options == undefined) { options = {}; } 
124       
125        if (options.featureClass || 
126            !OpenLayers.Layer.Vector || 
127            !OpenLayers.Feature.Vector) {
128            this.vectorMode = false;
129        }   
130
131        // Uppercase params
132        params = OpenLayers.Util.upperCaseObject(params);
133       
134        // Turn off error reporting, browsers like Safari may work
135        // depending on the setup, and we don't want an unneccesary alert.
136        OpenLayers.Util.extend(options, {'reportError': false});
137        var newArguments = [];
138        newArguments.push(name, options);
139        OpenLayers.Layer.Vector.prototype.initialize.apply(this, newArguments);
140        if (!this.renderer || !this.vectorMode) {
141            this.vectorMode = false; 
142            if (!options.featureClass) {
143                options.featureClass = OpenLayers.Feature.WFS;
144            }   
145            OpenLayers.Layer.Markers.prototype.initialize.apply(this, 
146                                                                newArguments);
147        }
148       
149        if (this.params && this.params.typename && !this.options.typename) {
150            this.options.typename = this.params.typename;
151        }
152       
153        if (!this.options.geometry_column) {
154            this.options.geometry_column = "the_geom";
155        }   
156       
157        this.params = OpenLayers.Util.applyDefaults(
158            params, 
159            OpenLayers.Util.upperCaseObject(this.DEFAULT_PARAMS)
160        );
161        this.url = url;
162    },   
163   
164
165    /**
166     * APIMethod: destroy
167     */
168    destroy: function() {
169        if (this.vectorMode) {
170            OpenLayers.Layer.Vector.prototype.destroy.apply(this, arguments);
171        } else {   
172            OpenLayers.Layer.Markers.prototype.destroy.apply(this, arguments);
173        }   
174        if (this.tile) {
175            this.tile.destroy();
176        }
177        this.tile = null;
178
179        this.ratio = null;
180        this.featureClass = null;
181        this.format = null;
182
183        if (this.formatObject && this.formatObject.destroy) {
184            this.formatObject.destroy();
185        }
186        this.formatObject = null;
187       
188        this.formatOptions = null;
189        this.vectorMode = null;
190        this.encodeBBOX = null;
191        this.extractAttributes = null;
192    },
193   
194    /**
195     * Method: setMap
196     *
197     * Parameters:
198     * map - {<OpenLayers.Map>}
199     */
200    setMap: function(map) {
201        if (this.vectorMode) {
202            OpenLayers.Layer.Vector.prototype.setMap.apply(this, arguments);
203           
204            var options = {
205              'extractAttributes': this.extractAttributes
206            };
207           
208            OpenLayers.Util.extend(options, this.formatOptions);
209            if (this.map && !this.projection.equals(this.map.getProjectionObject())) {
210                options.externalProjection = this.projection;
211                options.internalProjection = this.map.getProjectionObject();
212            }   
213           
214            this.formatObject = this.format ? new this.format(options) : new OpenLayers.Format.GML(options);
215        } else {   
216            OpenLayers.Layer.Markers.prototype.setMap.apply(this, arguments);
217        }   
218    },
219   
220    /**
221     * Method: moveTo
222     *
223     * Parameters:
224     * bounds - {<OpenLayers.Bounds>}
225     * zoomChanged - {Boolean}
226     * dragging - {Boolean}
227     */
228    moveTo:function(bounds, zoomChanged, dragging) {
229        if (this.vectorMode) {
230            OpenLayers.Layer.Vector.prototype.moveTo.apply(this, arguments);
231        } else {
232            OpenLayers.Layer.Markers.prototype.moveTo.apply(this, arguments);
233        }   
234
235        // don't load wfs features while dragging, wait for drag end
236        if (dragging) {
237            // TBD try to hide the vector layer while dragging
238            // this.setVisibility(false);
239            // this will probably help for panning performances
240            return false;
241        }
242       
243        if ( zoomChanged ) {
244            if (this.vectorMode) {
245                this.renderer.clear();
246            }
247        }
248       
249    //DEPRECATED - REMOVE IN 3.0
250        // don't load data if current zoom level doesn't match
251        if (this.options.minZoomLevel) {
252            OpenLayers.Console.warn(OpenLayers.i18n('minZoomLevelError'));
253           
254            if (this.map.getZoom() < this.options.minZoomLevel) {
255                return null;
256            }
257        }
258       
259        if (bounds == null) {
260            bounds = this.map.getExtent();
261        }
262
263        var firstRendering = (this.tile == null);
264
265        //does the new bounds to which we need to move fall outside of the
266        // current tile's bounds?
267        var outOfBounds = (!firstRendering &&
268                           !this.tile.bounds.containsBounds(bounds));
269
270        if (zoomChanged || firstRendering || (!dragging && outOfBounds)) {
271            //determine new tile bounds
272            var center = bounds.getCenterLonLat();
273            var tileWidth = bounds.getWidth() * this.ratio;
274            var tileHeight = bounds.getHeight() * this.ratio;
275            var tileBounds = 
276                new OpenLayers.Bounds(center.lon - (tileWidth / 2),
277                                      center.lat - (tileHeight / 2),
278                                      center.lon + (tileWidth / 2),
279                                      center.lat + (tileHeight / 2));
280
281            //determine new tile size
282            var tileSize = this.map.getSize();
283            tileSize.w = tileSize.w * this.ratio;
284            tileSize.h = tileSize.h * this.ratio;
285
286            //determine new position (upper left corner of new bounds)
287            var ul = new OpenLayers.LonLat(tileBounds.left, tileBounds.top);
288            var pos = this.map.getLayerPxFromLonLat(ul);
289
290            //formulate request url string
291            var url = this.getFullRequestString();
292       
293            var params = null;
294
295            // Cant combine "filter" and "BBOX". This is a cheap hack to help
296            // people out who can't migrate to the WFS protocol immediately.
297            var filter = this.params.filter || this.params.FILTER;
298            if (filter) {
299                params = {FILTER: filter};
300            }
301            else {
302                params = {BBOX: this.encodeBBOX ? tileBounds.toBBOX() 
303                                                    : tileBounds.toArray()};
304            }
305           
306            if (this.map && !this.projection.equals(this.map.getProjectionObject())) {
307                var projectedBounds = tileBounds.clone();
308                projectedBounds.transform(this.map.getProjectionObject(), 
309                                          this.projection);
310                if (!filter){
311                    params.BBOX = this.encodeBBOX ? projectedBounds.toBBOX() 
312                                                : projectedBounds.toArray();
313                }
314            }                                 
315
316            url += "&" + OpenLayers.Util.getParameterString(params);
317
318            if (!this.tile) {
319                this.tile = new OpenLayers.Tile.WFS(this, pos, tileBounds, 
320                                                     url, tileSize);
321                this.addTileMonitoringHooks(this.tile);
322                this.tile.draw();
323            } else {
324                if (this.vectorMode) {
325                    this.destroyFeatures();
326                    this.renderer.clear();
327                } else {
328                    this.clearMarkers();
329                }   
330                this.removeTileMonitoringHooks(this.tile);
331                this.tile.destroy();
332               
333                this.tile = null;
334                this.tile = new OpenLayers.Tile.WFS(this, pos, tileBounds, 
335                                                     url, tileSize);
336                this.addTileMonitoringHooks(this.tile);
337                this.tile.draw();
338            } 
339        }
340    },
341
342    /**
343     * Method: addTileMonitoringHooks
344     * This function takes a tile as input and adds the appropriate hooks to
345     *     the tile so that the layer can keep track of the loading tile
346     *     (making sure to check that the tile is always the layer's current
347     *     tile before taking any action).
348     *
349     * Parameters:
350     * tile - {<OpenLayers.Tile>}
351     */
352    addTileMonitoringHooks: function(tile) {
353        tile.onLoadStart = function() {
354            //if this is the the layer's current tile, then trigger
355            // a 'loadstart'
356            if (this == this.layer.tile) {
357                this.layer.events.triggerEvent("loadstart");
358            }
359        };
360        tile.events.register("loadstart", tile, tile.onLoadStart);
361     
362        tile.onLoadEnd = function() {
363            //if this is the the layer's current tile, then trigger
364            // a 'tileloaded' and 'loadend'
365            if (this == this.layer.tile) {
366                this.layer.events.triggerEvent("tileloaded");
367                this.layer.events.triggerEvent("loadend");
368            }
369        };
370        tile.events.register("loadend", tile, tile.onLoadEnd);
371        tile.events.register("unload", tile, tile.onLoadEnd);
372    },
373   
374    /**
375     * Method: removeTileMonitoringHooks
376     * This function takes a tile as input and removes the tile hooks
377     *     that were added in addTileMonitoringHooks()
378     *
379     * Parameters:
380     * tile - {<OpenLayers.Tile>}
381     */
382    removeTileMonitoringHooks: function(tile) {
383        tile.unload();
384        tile.events.un({
385            "loadstart": tile.onLoadStart,
386            "loadend": tile.onLoadEnd,
387            "unload": tile.onLoadEnd,
388            scope: tile
389        });
390    },
391
392    /**
393     * Method: onMapResize
394     * Call the onMapResize method of the appropriate parent class.
395     */
396    onMapResize: function() {
397        if(this.vectorMode) {
398            OpenLayers.Layer.Vector.prototype.onMapResize.apply(this, 
399                                                                arguments);
400        } else {
401            OpenLayers.Layer.Markers.prototype.onMapResize.apply(this, 
402                                                                 arguments);
403        }
404    },
405   
406    /**
407     * Method: display
408     * Call the display method of the appropriate parent class.
409     */
410    display: function() {
411        if(this.vectorMode) {
412            OpenLayers.Layer.Vector.prototype.display.apply(this, 
413                                                                arguments);
414        } else {
415            OpenLayers.Layer.Markers.prototype.display.apply(this, 
416                                                                 arguments);
417        }
418    },
419   
420    /**
421     * APIMethod: mergeNewParams
422     * Modify parameters for the layer and redraw.
423     *
424     * Parameters:
425     * newParams - {Object}
426     */
427    mergeNewParams:function(newParams) {
428        var upperParams = OpenLayers.Util.upperCaseObject(newParams);
429        var newArguments = [upperParams];
430        return OpenLayers.Layer.HTTPRequest.prototype.mergeNewParams.apply(this, 
431                                                                 newArguments);
432    },
433
434    /**
435     * APIMethod: clone
436     *
437     * Parameters:
438     * obj - {Object}
439     *
440     * Returns:
441     * {<OpenLayers.Layer.WFS>} An exact clone of this OpenLayers.Layer.WFS
442     */
443    clone: function (obj) {
444       
445        if (obj == null) {
446            obj = new OpenLayers.Layer.WFS(this.name,
447                                           this.url,
448                                           this.params,
449                                           this.getOptions());
450        }
451
452        //get all additions from superclasses
453        if (this.vectorMode) {
454            obj = OpenLayers.Layer.Vector.prototype.clone.apply(this, [obj]);
455        } else {
456            obj = OpenLayers.Layer.Markers.prototype.clone.apply(this, [obj]);
457        }   
458
459        // copy/set any non-init, non-simple values here
460
461        return obj;
462    },
463
464    /**
465     * APIMethod: getFullRequestString
466     * combine the layer's url with its params and these newParams.
467     *   
468     *    Add the SRS parameter from 'projection' -- this is probably
469     *     more eloquently done via a setProjection() method, but this
470     *     works for now and always.
471     *
472     * Parameters:
473     * newParams - {Object}
474     * altUrl - {String} Use this as the url instead of the layer's url
475     */
476    getFullRequestString:function(newParams, altUrl) {
477        var projectionCode = this.projection.getCode() || this.map.getProjection();
478        this.params.SRS = (projectionCode == "none") ? null : projectionCode;
479
480        return OpenLayers.Layer.Grid.prototype.getFullRequestString.apply(
481                                                    this, arguments);
482    },
483   
484    /**
485     * APIMethod: commit
486     * Write out the data to a WFS server.
487     */
488    commit: function() {
489        if (!this.writer) {
490            var options = {};
491            if (this.map && !this.projection.equals(this.map.getProjectionObject())) {
492                options.externalProjection = this.projection;
493                options.internalProjection = this.map.getProjectionObject();
494            }   
495           
496            this.writer = new OpenLayers.Format.WFS(options,this);
497        }
498
499        var data = this.writer.write(this.features);
500
501        OpenLayers.Request.POST({
502            url: this.url,
503            data: data,
504            success: this.commitSuccess,
505            failure: this.commitFailure,
506            scope: this
507        });
508    },
509
510    /**
511     * Method: commitSuccess
512     * Called when the Ajax request returns a response
513     *
514     * Parameters:
515     * response - {XmlNode} from server
516     */
517    commitSuccess: function(request) {
518        var response = request.responseText;
519        if (response.indexOf('SUCCESS') != -1) {
520            this.commitReport(OpenLayers.i18n("commitSuccess", {'response':response}));
521           
522            for(var i = 0; i < this.features.length; i++) {
523                this.features[i].state = null;
524            }   
525            // TBD redraw the layer or reset the state of features
526            // foreach features: set state to null
527        } else if (response.indexOf('FAILED') != -1 ||
528            response.indexOf('Exception') != -1) {
529            this.commitReport(OpenLayers.i18n("commitFailed", {'response':response}));
530        }
531    },
532   
533    /**
534     * Method: commitFailure
535     * Called when the Ajax request fails
536     *
537     * Parameters:
538     * response - {XmlNode} from server
539     */
540    commitFailure: function(request) {},
541   
542    /**
543     * APIMethod: commitReport
544     * Called with a 'success' message if the commit succeeded, otherwise
545     *     a failure message, and the full request text as a second parameter.
546     *     Override this function to provide custom transaction reporting.
547     *
548     * string - {String} reporting string
549     * response - {String} full XML response
550     */
551    commitReport: function(string, response) {
552        OpenLayers.Console.userError(string);
553    },
554
555   
556    /**
557     * APIMethod: refresh
558     * Refreshes all the features of the layer
559     */
560    refresh: function() {
561        if (this.tile) {
562            if (this.vectorMode) {
563                this.renderer.clear();
564                this.features.length = 0;
565            } else {   
566                this.clearMarkers();
567                this.markers.length = 0;
568            }   
569            this.tile.draw();
570        }
571    },
572   
573    /**
574     * APIMethod: getDataExtent
575     * Calculates the max extent which includes all of the layer data.
576     *
577     * Returns:
578     * {<OpenLayers.Bounds>}
579     */
580    getDataExtent: function () {
581        var extent; 
582        //get all additions from superclasses
583        if (this.vectorMode) {
584            extent = OpenLayers.Layer.Vector.prototype.getDataExtent.apply(this);
585        } else {
586            extent = OpenLayers.Layer.Markers.prototype.getDataExtent.apply(this);
587        }   
588
589        return extent;
590    },
591   
592    /**
593     * APIMethod: setOpacity
594     * Call the setOpacity method of the appropriate parent class to set the
595     *     opacity. 
596     *
597     * Parameter:
598     * opacity - {Float}
599     */
600    setOpacity: function (opacity) {
601        if (this.vectorMode) {
602            OpenLayers.Layer.Vector.prototype.setOpacity.apply(this, [opacity]);
603        } else {
604            OpenLayers.Layer.Markers.prototype.setOpacity.apply(this, [opacity]);
605        }   
606    },
607
608    CLASS_NAME: "OpenLayers.Layer.WFS"
609});
Note: See TracBrowser for help on using the repository browser.