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/Control/WMSGetFeatureInfo.js @ 76

Revision 76, 17.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/Control.js
9 * @requires OpenLayers/Handler/Click.js
10 * @requires OpenLayers/Handler/Hover.js
11 * @requires OpenLayers/Request.js
12 */
13
14/**
15 * Class: OpenLayers.Control.WMSGetFeatureInfo
16 * The WMSGetFeatureInfo control uses a WMS query to get information about a point on the map.  The
17 * information may be in a display-friendly format such as HTML, or a machine-friendly format such
18 * as GML, depending on the server's capabilities and the client's configuration.  This control
19 * handles click or hover events, attempts to parse the results using an OpenLayers.Format, and
20 * fires a 'getfeatureinfo' event with the click position, the raw body of the response, and an
21 * array of features if it successfully read the response.
22 *
23 * Inherits from:
24 *  - <OpenLayers.Control>
25 */
26OpenLayers.Control.WMSGetFeatureInfo = OpenLayers.Class(OpenLayers.Control, {
27
28   /**
29     * APIProperty: hover
30     * {Boolean} Send GetFeatureInfo requests when mouse stops moving.
31     *     Default is false.
32     */
33    hover: false,
34
35    /**
36     * APIProperty: drillDown
37     * {Boolean} Drill down over all WMS layers in the map. When
38     *     using drillDown mode, hover is not possible, and an infoFormat that
39     *     returns parseable features is required. Default is false.
40     */
41    drillDown: false,
42
43    /**
44     * APIProperty: maxFeatures
45     * {Integer} Maximum number of features to return from a WMS query. This
46     *     sets the feature_count parameter on WMS GetFeatureInfo
47     *     requests.
48     */
49    maxFeatures: 10,
50
51    /** APIProperty: clickCallback
52     *  {String} The click callback to register in the
53     *      {<OpenLayers.Handler.Click>} object created when the hover
54     *      option is set to false. Default is "click".
55     */
56    clickCallback: "click",
57   
58    /**
59     * Property: layers
60     * {Array(<OpenLayers.Layer.WMS>)} The layers to query for feature info.
61     *     If omitted, all map WMS layers with a url that matches this <url> or
62     *     <layerUrls> will be considered.
63     */
64    layers: null,
65
66    /**
67     * Property: queryVisible
68     * {Boolean} If true, filter out hidden layers when searching the map for
69     *     layers to query.  Default is false.
70     */
71    queryVisible: false,
72
73    /**
74     * Property: url
75     * {String} The URL of the WMS service to use.  If not provided, the url
76     *     of the first eligible layer will be used.
77     */
78    url: null,
79   
80    /**
81     * Property: layerUrls
82     * {Array(String)} Optional list of urls for layers that should be queried.
83     *     This can be used when the layer url differs from the url used for
84     *     making GetFeatureInfo requests (in the case of a layer using cached
85     *     tiles).
86     */
87    layerUrls: null,
88
89    /**
90     * Property: infoFormat
91     * {String} The mimetype to request from the server
92     */
93    infoFormat: 'text/html',
94   
95    /**
96     * Property: vendorParams
97     * {Object} Additional parameters that will be added to the request, for
98     * WMS implementations that support them. This could e.g. look like
99     * (start code)
100     * {
101     *     radius: 5
102     * }
103     * (end)
104     */
105    vendorParams: {},
106   
107    /**
108     * Property: format
109     * {<OpenLayers.Format>} A format for parsing GetFeatureInfo responses.
110     *     Default is <OpenLayers.Format.WMSGetFeatureInfo>.
111     */
112    format: null,
113   
114    /**
115     * Property: formatOptions
116     * {Object} Optional properties to set on the format (if one is not provided
117     *     in the <format> property.
118     */
119    formatOptions: null,
120
121    /**
122     * APIProperty: handlerOptions
123     * {Object} Additional options for the handlers used by this control, e.g.
124     * (start code)
125     * {
126     *     "click": {delay: 100},
127     *     "hover": {delay: 300}
128     * }
129     * (end)
130     */
131    handlerOptions: null,
132   
133    /**
134     * Property: handler
135     * {Object} Reference to the <OpenLayers.Handler> for this control
136     */
137    handler: null,
138   
139    /**
140     * Property: hoverRequest
141     * {<OpenLayers.Request>} contains the currently running hover request
142     *     (if any).
143     */
144    hoverRequest: null,
145   
146    /**
147     * Constant: EVENT_TYPES
148     *
149     * Supported event types (in addition to those from <OpenLayers.Control>):
150     * beforegetfeatureinfo - Triggered before the request is sent.
151     *      The event object has an *xy* property with the position of the
152     *      mouse click or hover event that triggers the request.
153     * nogetfeatureinfo - no queryable layers were found.
154     * getfeatureinfo - Triggered when a GetFeatureInfo response is received.
155     *      The event object has a *text* property with the body of the
156     *      response (String), a *features* property with an array of the
157     *      parsed features, an *xy* property with the position of the mouse
158     *      click or hover event that triggered the request, and a *request*
159     *      property with the request itself. If drillDown is set to true and
160     *      multiple requests were issued to collect feature info from all
161     *      layers, *text* and *request* will only contain the response body
162     *      and request object of the last request.
163     */
164    EVENT_TYPES: ["beforegetfeatureinfo", "nogetfeatureinfo", "getfeatureinfo"],
165
166    /**
167     * Constructor: <OpenLayers.Control.WMSGetFeatureInfo>
168     *
169     * Parameters:
170     * options - {Object}
171     */
172    initialize: function(options) {
173        // concatenate events specific to vector with those from the base
174        this.EVENT_TYPES =
175            OpenLayers.Control.WMSGetFeatureInfo.prototype.EVENT_TYPES.concat(
176            OpenLayers.Control.prototype.EVENT_TYPES
177        );
178
179        options = options || {};
180        options.handlerOptions = options.handlerOptions || {};
181
182        OpenLayers.Control.prototype.initialize.apply(this, [options]);
183       
184        if(!this.format) {
185            this.format = new OpenLayers.Format.WMSGetFeatureInfo(
186                options.formatOptions
187            );
188        }
189       
190        if(this.drillDown === true) {
191            this.hover = false;
192        }
193
194        if(this.hover) {
195            this.handler = new OpenLayers.Handler.Hover(
196                   this, {
197                       'move': this.cancelHover,
198                       'pause': this.getInfoForHover
199                   },
200                   OpenLayers.Util.extend(this.handlerOptions.hover || {}, {
201                       'delay': 250
202                   }));
203        } else {
204            var callbacks = {};
205            callbacks[this.clickCallback] = this.getInfoForClick;
206            this.handler = new OpenLayers.Handler.Click(
207                this, callbacks, this.handlerOptions.click || {});
208        }
209    },
210
211    /**
212     * Method: activate
213     * Activates the control.
214     *
215     * Returns:
216     * {Boolean} The control was effectively activated.
217     */
218    activate: function () {
219        if (!this.active) {
220            this.handler.activate();
221        }
222        return OpenLayers.Control.prototype.activate.apply(
223            this, arguments
224        );
225    },
226
227    /**
228     * Method: deactivate
229     * Deactivates the control.
230     *
231     * Returns:
232     * {Boolean} The control was effectively deactivated.
233     */
234    deactivate: function () {
235        return OpenLayers.Control.prototype.deactivate.apply(
236            this, arguments
237        );
238    },
239   
240    /**
241     * Method: getInfoForClick
242     * Called on click
243     *
244     * Parameters:
245     * evt - {<OpenLayers.Event>}
246     */
247    getInfoForClick: function(evt) {
248        this.events.triggerEvent("beforegetfeatureinfo", {xy: evt.xy});
249        // Set the cursor to "wait" to tell the user we're working on their
250        // click.
251        OpenLayers.Element.addClass(this.map.viewPortDiv, "olCursorWait");
252        this.request(evt.xy, {});
253    },
254   
255    /**
256     * Method: getInfoForHover
257     * Pause callback for the hover handler
258     *
259     * Parameters:
260     * evt - {Object}
261     */
262    getInfoForHover: function(evt) {
263        this.events.triggerEvent("beforegetfeatureinfo", {xy: evt.xy});
264        this.request(evt.xy, {hover: true});
265    },
266
267    /**
268     * Method: cancelHover
269     * Cancel callback for the hover handler
270     */
271    cancelHover: function() {
272        if (this.hoverRequest) {
273            this.hoverRequest.abort();
274            this.hoverRequest = null;
275        }
276    },
277
278    /**
279     * Method: findLayers
280     * Internal method to get the layers, independent of whether we are
281     *     inspecting the map or using a client-provided array
282     */
283    findLayers: function() {
284
285        var candidates = this.layers || this.map.layers;
286        var layers = [];
287        var layer, url;
288        for(var i=0, len=candidates.length; i<len; ++i) {
289            layer = candidates[i];
290            if(layer instanceof OpenLayers.Layer.WMS &&
291               (!this.queryVisible || layer.getVisibility())) {
292                url = layer.url instanceof Array ? layer.url[0] : layer.url;
293                // if the control was not configured with a url, set it
294                // to the first layer url
295                if(this.drillDown === false && !this.url) {
296                    this.url = url;
297                }
298                if(this.drillDown === true || this.urlMatches(url)) {
299                    layers.push(layer);
300                }
301            }
302        }
303        return layers;
304    },
305   
306    /**
307     * Method: urlMatches
308     * Test to see if the provided url matches either the control <url> or one
309     *     of the <layerUrls>.
310     *
311     * Parameters:
312     * url - {String} The url to test.
313     *
314     * Returns:
315     * {Boolean} The provided url matches the control <url> or one of the
316     *     <layerUrls>.
317     */
318    urlMatches: function(url) {
319        var matches = OpenLayers.Util.isEquivalentUrl(this.url, url);
320        if(!matches && this.layerUrls) {
321            for(var i=0, len=this.layerUrls.length; i<len; ++i) {
322                if(OpenLayers.Util.isEquivalentUrl(this.layerUrls[i], url)) {
323                    matches = true;
324                    break;
325                }
326            }
327        }
328        return matches;
329    },
330
331    /**
332     * Method: buildWMSOptions
333     * Build an object with the relevant WMS options for the GetFeatureInfo request
334     *
335     * Parameters:
336     * url - {String} The url to be used for sending the request
337     * layers - {Array(<OpenLayers.Layer.WMS)} An array of layers
338     * clickPosition - {<OpenLayers.Pixel>} The position on the map where the mouse
339     *     event occurred.
340     * format - {String} The format from the corresponding GetMap request
341     */
342    buildWMSOptions: function(url, layers, clickPosition, format) {
343        var layerNames = [], styleNames = [];
344        for (var i = 0, len = layers.length; i < len; i++) { 
345            layerNames = layerNames.concat(layers[i].params.LAYERS);
346            styleNames = styleNames.concat(this.getStyleNames(layers[i]));
347        }
348        var params = OpenLayers.Util.extend({
349            service: "WMS",
350            version: layers[0].params.VERSION,
351            request: "GetFeatureInfo",
352            layers: layerNames,
353            query_layers: layerNames,
354            styles: styleNames,
355            bbox: this.map.getExtent().toBBOX(null,
356                layers[0].reverseAxisOrder()),
357            feature_count: this.maxFeatures,
358            height: this.map.getSize().h,
359            width: this.map.getSize().w,
360            format: format,
361            info_format: this.infoFormat
362        }, (parseFloat(layers[0].params.VERSION) >= 1.3) ?
363            {
364                crs: this.map.getProjection(),
365                i: clickPosition.x,
366                j: clickPosition.y
367            } :
368            {
369                srs: this.map.getProjection(),
370                x: clickPosition.x,
371                y: clickPosition.y
372            }
373        );
374        OpenLayers.Util.applyDefaults(params, this.vendorParams);
375        return {
376            url: url,
377            params: OpenLayers.Util.upperCaseObject(params),
378            callback: function(request) {
379                this.handleResponse(clickPosition, request);
380            },
381            scope: this
382        };
383    },
384
385    /**
386     * Method: getStyleNames
387     * Gets the STYLES parameter for the layer. Make sure the STYLES parameter
388     * matches the LAYERS parameter
389     *
390     * Parameters:
391     * layer - {<OpenLayers.Layer.WMS>}
392     *
393     * Returns:
394     * {Array(String)} The STYLES parameter
395     */
396    getStyleNames: function(layer) {
397        // in the event of a WMS layer bundling multiple layers but not
398        // specifying styles,we need the same number of commas to specify
399        // the default style for each of the layers.  We can't just leave it
400        // blank as we may be including other layers that do specify styles.
401        var styleNames;
402        if (layer.params.STYLES) {
403            styleNames = layer.params.STYLES;
404        } else {
405            if (layer.params.LAYERS instanceof Array) {
406                styleNames = new Array(layer.params.LAYERS.length);
407            } else { // Assume it's a String
408                styleNames = layer.params.LAYERS.replace(/[^,]/g, "");
409            }
410        }
411        return styleNames;
412    },
413
414    /**
415     * Method: request
416     * Sends a GetFeatureInfo request to the WMS
417     *
418     * Parameters:
419     * clickPosition - {<OpenLayers.Pixel>} The position on the map where the
420     *     mouse event occurred.
421     * options - {Object} additional options for this method.
422     *
423     * Valid options:
424     * - *hover* {Boolean} true if we do the request for the hover handler
425     */
426    request: function(clickPosition, options) {
427        var layers = this.findLayers();
428        if(layers.length == 0) {
429            this.events.triggerEvent("nogetfeatureinfo");
430            // Reset the cursor.
431            OpenLayers.Element.removeClass(this.map.viewPortDiv, "olCursorWait");
432            return;
433        }
434       
435        options = options || {};
436        if(this.drillDown === false) {
437            var wmsOptions = this.buildWMSOptions(this.url, layers,
438                clickPosition, layers[0].params.FORMAT); 
439            var request = OpenLayers.Request.GET(wmsOptions);
440   
441            if (options.hover === true) {
442                this.hoverRequest = request;
443            }
444        } else {
445            this._requestCount = 0;
446            this._numRequests = 0;
447            this.features = [];
448            // group according to service url to combine requests
449            var services = {}, url;
450            for(var i=0, len=layers.length; i<len; i++) {
451                var layer = layers[i];
452                var service, found = false;
453                url = layer.url instanceof Array ? layer.url[0] : layer.url;
454                if(url in services) {
455                    services[url].push(layer);
456                } else {
457                    this._numRequests++;
458                    services[url] = [layer];
459                }
460            }
461            var layers;
462            for (var url in services) {
463                layers = services[url];
464                var wmsOptions = this.buildWMSOptions(url, layers, 
465                    clickPosition, layers[0].params.FORMAT);
466                OpenLayers.Request.GET(wmsOptions); 
467            }
468        }
469    },
470
471    /**
472     * Method: triggerGetFeatureInfo
473     * Trigger the getfeatureinfo event when all is done
474     *
475     * Parameters:
476     * request - {XMLHttpRequest} The request object
477     * xy - {<OpenLayers.Pixel>} The position on the map where the
478     *     mouse event occurred.
479     * features - {Array(<OpenLayers.Feature.Vector>)}
480     */
481    triggerGetFeatureInfo: function(request, xy, features) {
482        this.events.triggerEvent("getfeatureinfo", {
483            text: request.responseText,
484            features: features,
485            request: request,
486            xy: xy
487        });
488
489        // Reset the cursor.
490        OpenLayers.Element.removeClass(this.map.viewPortDiv, "olCursorWait");
491    },
492   
493    /**
494     * Method: handleResponse
495     * Handler for the GetFeatureInfo response.
496     *
497     * Parameters:
498     * xy - {<OpenLayers.Pixel>} The position on the map where the
499     *     mouse event occurred.
500     * request - {XMLHttpRequest} The request object.
501     */
502    handleResponse: function(xy, request) {
503       
504        var doc = request.responseXML;
505        if(!doc || !doc.documentElement) {
506            doc = request.responseText;
507        }
508        var features = this.format.read(doc);
509        if (this.drillDown === false) {
510            this.triggerGetFeatureInfo(request, xy, features);
511        } else {
512            this._requestCount++;
513            this._features = (this._features || []).concat(features);
514            if (this._requestCount === this._numRequests) {
515                this.triggerGetFeatureInfo(request, xy, this._features.concat()); 
516                delete this._features;
517                delete this._requestCount;
518                delete this._numRequests;
519            }
520        }
521    },
522
523    CLASS_NAME: "OpenLayers.Control.WMSGetFeatureInfo"
524});
Note: See TracBrowser for help on using the repository browser.