]> dev.renevier.net Git - syp.git/blob - openlayers/lib/OpenLayers/Control/WMSGetFeatureInfo.js
initial commit
[syp.git] / openlayers / lib / OpenLayers / Control / WMSGetFeatureInfo.js
1 /* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
2  * license.  See http://svn.openlayers.org/trunk/openlayers/license.txt for the
3  * full text of the license. */
4
5
6 /**
7  * @requires OpenLayers/Control.js
8  * @requires OpenLayers/Handler/Click.js
9  * @requires OpenLayers/Handler/Hover.js
10  * @requires OpenLayers/Request.js
11  */
12
13 /**
14  * Class: OpenLayers.Control.WMSGetFeatureInfo
15  * The WMSGetFeatureInfo control uses a WMS query to get information about a point on the map.  The
16  * information may be in a display-friendly format such as HTML, or a machine-friendly format such 
17  * as GML, depending on the server's capabilities and the client's configuration.  This control 
18  * handles click or hover events, attempts to parse the results using an OpenLayers.Format, and 
19  * fires a 'getfeatureinfo' event with the click position, the raw body of the response, and an 
20  * array of features if it successfully read the response.
21  *
22  * Inherits from:
23  *  - <OpenLayers.Control>
24  */
25 OpenLayers.Control.WMSGetFeatureInfo = OpenLayers.Class(OpenLayers.Control, {
26     
27    /**
28      * APIProperty: hover
29      * {Boolean} Send GetFeatureInfo requests when mouse stops moving.
30      *     Default is false.
31      */
32     hover: false,
33
34     /**
35      * APIProperty: maxFeatures
36      * {Integer} Maximum number of features to return from a WMS query. This
37      *     sets the feature_count parameter on WMS GetFeatureInfo
38      *     requests.
39      */
40     maxFeatures: 10,
41     
42     /**
43      * Property: layers
44      * {Array(<OpenLayers.Layer.WMS>)} The layers to query for feature info.
45      *     If omitted, all map WMS layers with a url that matches this <url> or
46      *     <layerUrl> will be considered.
47      */
48     layers: null,
49
50     /**
51      * Property: queryVisible
52      * {Boolean} If true, filter out hidden layers when searching the map for
53      *     layers to query.  Default is false.
54      */
55     queryVisible: false,
56
57     /**
58      * Property: url
59      * {String} The URL of the WMS service to use.  If not provided, the url
60      *     of the first eligible layer will be used.
61      */
62     url: null,
63     
64     /**
65      * Property: layerUrls
66      * {Array(String)} Optional list of urls for layers that should be queried.
67      *     This can be used when the layer url differs from the url used for
68      *     making GetFeatureInfo requests (in the case of a layer using cached
69      *     tiles).
70      */
71     layerUrls: null,
72
73     /**
74      * Property: infoFormat
75      * {String} The mimetype to request from the server
76      */
77     infoFormat: 'text/html',
78     
79     /**
80      * Property: vendorParams
81      * {Object} Additional parameters that will be added to the request, for
82      * WMS implementations that support them. This could e.g. look like
83      * (start code)
84      * {
85      *     radius: 5
86      * }
87      * (end)
88      */
89     vendorParams: {},
90     
91     /**
92      * Property: format
93      * {<OpenLayers.Format>} A format for parsing GetFeatureInfo responses.
94      *     Default is <OpenLayers.Format.WMSGetFeatureInfo>.
95      */
96     format: null,
97     
98     /**
99      * Property: formatOptions
100      * {Object} Optional properties to set on the format (if one is not provided
101      *     in the <format> property.
102      */
103     formatOptions: null,
104
105     /**
106      * APIProperty: handlerOptions
107      * {Object} Additional options for the handlers used by this control, e.g.
108      * (start code)
109      * {
110      *     "click": {delay: 100},
111      *     "hover": {delay: 300}
112      * }
113      * (end)
114      */
115     handlerOptions: null,
116     
117     /**
118      * Property: handler
119      * {Object} Reference to the <OpenLayers.Handler> for this control
120      */
121     handler: null,
122     
123     /**
124      * Property: hoverRequest
125      * {<OpenLayers.Request>} contains the currently running hover request
126      *     (if any).
127      */
128     hoverRequest: null,
129     
130     /**
131      * Constant: EVENT_TYPES
132      *
133      * Supported event types (in addition to those from <OpenLayers.Control>):
134      * getfeatureinfo - Triggered when a GetFeatureInfo response is received.
135      *      The event object has a *text* property with the body of the
136      *      response (String), a *features* property with an array of the
137      *      parsed features, an *xy* property with the position of the mouse
138      *      click or hover event that triggered the request, and a *request*
139      *      property with the request itself.
140      */
141     EVENT_TYPES: ["getfeatureinfo"],
142
143     /**
144      * Constructor: <OpenLayers.Control.WMSGetFeatureInfo>
145      *
146      * Parameters:
147      * options - {Object} 
148      */
149     initialize: function(options) {
150         // concatenate events specific to vector with those from the base
151         this.EVENT_TYPES =
152             OpenLayers.Control.WMSGetFeatureInfo.prototype.EVENT_TYPES.concat(
153             OpenLayers.Control.prototype.EVENT_TYPES
154         );
155
156         options = options || {};
157         options.handlerOptions = options.handlerOptions || {};
158
159         OpenLayers.Control.prototype.initialize.apply(this, [options]);
160         
161         if(!this.format) {
162             this.format = new OpenLayers.Format.WMSGetFeatureInfo(
163                 options.formatOptions
164             );
165         }
166
167         if (this.hover) {
168             this.handler = new OpenLayers.Handler.Hover(
169                    this, {
170                        'move': this.cancelHover,
171                        'pause': this.getInfoForHover
172                    },
173                    OpenLayers.Util.extend(this.handlerOptions.hover || {}, {
174                        'delay': 250
175                    }));
176         } else {
177             this.handler = new OpenLayers.Handler.Click(this,
178                 {click: this.getInfoForClick}, this.handlerOptions.click || {});
179         }
180     },
181
182     /**
183      * Method: activate
184      * Activates the control.
185      * 
186      * Returns:
187      * {Boolean} The control was effectively activated.
188      */
189     activate: function () {
190         if (!this.active) {
191             this.handler.activate();
192         }
193         return OpenLayers.Control.prototype.activate.apply(
194             this, arguments
195         );
196     },
197
198     /**
199      * Method: deactivate
200      * Deactivates the control.
201      * 
202      * Returns:
203      * {Boolean} The control was effectively deactivated.
204      */
205     deactivate: function () {
206         return OpenLayers.Control.prototype.deactivate.apply(
207             this, arguments
208         );
209     },
210     
211     /**
212      * Method: getInfoForClick 
213      * Called on click
214      *
215      * Parameters:
216      * evt - {<OpenLayers.Event>} 
217      */
218     getInfoForClick: function(evt) {
219         // Set the cursor to "wait" to tell the user we're working on their
220         // click.
221         OpenLayers.Element.addClass(this.map.viewPortDiv, "olCursorWait");
222         this.request(evt.xy, {});
223     },
224    
225     /**
226      * Method: getInfoForHover
227      * Pause callback for the hover handler
228      *
229      * Parameters:
230      * evt - {Object}
231      */
232     getInfoForHover: function(evt) {
233         this.request(evt.xy, {hover: true});
234     },
235
236     /**
237      * Method: cancelHover
238      * Cancel callback for the hover handler
239      */
240     cancelHover: function() {
241         if (this.hoverRequest) {
242             this.hoverRequest.abort();
243             this.hoverRequest = null;
244         }
245     },
246
247     /**
248      * Method: findLayers
249      * Internal method to get the layers, independent of whether we are
250      *     inspecting the map or using a client-provided array
251      */
252     findLayers: function() {
253
254         var layers = [];
255         
256         var candidates = this.layers || this.map.layers;
257         var layer, url;
258         for(var i=0, len=candidates.length; i<len; ++i) {
259             layer = candidates[i];
260             if(layer instanceof OpenLayers.Layer.WMS &&
261                (!this.queryVisible || layer.getVisibility())) {
262                 url = layer.url instanceof Array ? layer.url[0] : layer.url;
263                 // if the control was not configured with a url, set it
264                 // to the first layer url
265                 if(!this.url) {
266                     this.url = url;
267                 }
268                 if(this.urlMatches(url)) {
269                     layers.push(layer);
270                 }
271             }
272         }
273
274         return layers;
275     },
276     
277     /**
278      * Method: urlMatches
279      * Test to see if the provided url matches either the control <url> or one
280      *     of the <layerUrls>.
281      *
282      * Parameters:
283      * url - {String} The url to test.
284      *
285      * Returns:
286      * {Boolean} The provided url matches the control <url> or one of the
287      *     <layerUrls>.
288      */
289     urlMatches: function(url) {
290         var matches = OpenLayers.Util.isEquivalentUrl(this.url, url);
291         if(!matches && this.layerUrls) {
292             for(var i=0, len=this.layerUrls.length; i<len; ++i) {
293                 if(OpenLayers.Util.isEquivalentUrl(this.layerUrls[i], url)) {
294                     matches = true;
295                     break;
296                 }
297             }
298         }
299         return matches;
300     },
301
302     /**
303      * Method: request
304      * Sends a GetFeatureInfo request to the WMS
305      * 
306      * Parameters:
307      * clickPosition - {<OpenLayers.Pixel>} The position on the map where the
308      *     mouse event occurred.
309      * options - {Object} additional options for this method.
310      * 
311      * Valid options:
312      * - *hover* {Boolean} true if we do the request for the hover handler
313      */
314     request: function(clickPosition, options) {
315         options = options || {};
316         var layerNames = [];
317         var styleNames = [];
318
319         var layers = this.findLayers();
320         if(layers.length > 0) {
321
322             for (var i = 0, len = layers.length; i < len; i++) { 
323                 layerNames = layerNames.concat(layers[i].params.LAYERS);
324                 // in the event of a WMS layer bundling multiple layers but not
325                 // specifying styles,we need the same number of commas to specify
326                 // the default style for each of the layers.  We can't just leave it
327                 // blank as we may be including other layers that do specify styles.
328                 if (layers[i].params.STYLES) {
329                     styleNames = styleNames.concat(layers[i].params.STYLES);
330                 } else {
331                     if (layers[i].params.LAYERS instanceof Array) {
332                         styleNames = styleNames.concat(new Array(layers[i].params.LAYERS.length));
333                     } else { // Assume it's a String
334                         styleNames = styleNames.concat(layers[i].params.LAYERS.replace(/[^,]/g, ""));
335                     }
336                 }
337             }
338     
339             var wmsOptions = {
340                 url: this.url,
341                 params: OpenLayers.Util.applyDefaults({
342                     service: "WMS",
343                     version: "1.1.0",
344                     request: "GetFeatureInfo",
345                     layers: layerNames,
346                     query_layers: layerNames,
347                     styles: styleNames,
348                     bbox: this.map.getExtent().toBBOX(),
349                     srs: this.map.getProjection(),
350                     feature_count: this.maxFeatures,
351                     x: clickPosition.x,
352                     y: clickPosition.y,
353                     height: this.map.getSize().h,
354                     width: this.map.getSize().w,
355                     info_format: this.infoFormat 
356                 }, this.vendorParams), 
357                 callback: function(request) {
358                     this.handleResponse(clickPosition, request);
359                 },
360                 scope: this                    
361             };
362     
363             var response = OpenLayers.Request.GET(wmsOptions);
364     
365             if (options.hover === true) {
366                 this.hoverRequest = response.priv;
367             }
368         } else {
369             // Reset the cursor.
370             OpenLayers.Element.removeClass(this.map.viewPortDiv, "olCursorWait");
371         }
372     },
373     
374     /**
375      * Method: handleResponse
376      * Handler for the GetFeatureInfo response.
377      * 
378      * Parameters:
379      * xy - {<OpenLayers.Pixel>} The position on the map where the
380      *     mouse event occurred.
381      * request - {XMLHttpRequest} The request object.
382      */
383     handleResponse: function(xy, request) {
384         
385         var doc = request.responseXML;
386         if(!doc || !doc.documentElement) {
387             doc = request.responseText;
388         }
389         var features = this.format.read(doc);
390
391         this.events.triggerEvent("getfeatureinfo", {
392             text: request.responseText,
393             features: features,
394             request: request,
395             xy: xy
396         });
397         
398         // Reset the cursor.
399         OpenLayers.Element.removeClass(this.map.viewPortDiv, "olCursorWait");
400     },
401    
402     /** 
403      * Method: setMap
404      * Set the map property for the control. 
405      * 
406      * Parameters:
407      * map - {<OpenLayers.Map>} 
408      */
409     setMap: function(map) {
410         this.handler.setMap(map);
411         OpenLayers.Control.prototype.setMap.apply(this, arguments);
412     },
413
414     CLASS_NAME: "OpenLayers.Control.WMSGetFeatureInfo"
415 });