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/GeoExt/docs/_sources/primers/openlayers-primer.txt @ 81

Revision 76, 14.3 KB checked in by djay, 13 years ago (diff)

Ajout du répertoire web

  • Property svn:executable set to *
Line 
1.. highlight:: javascript
2
3====================
4 Primer: OpenLayers
5====================
6
7The OpenLayers mapping library is the key component of GeoExt, performing the
8core map-related functions of every GeoExt-based application. To get up to speed
9with GeoExt, let's discover some OpenLayers basics.
10
11Layers
12======
13
14As its name suggests, OpenLayers manages a list of layers that together form a
15web-based mapping client. Each layer represents a different set of data. For
16instance, one layer might be responsible for displaying the boundary of a
17country. Another layer responsible for that country's roads.
18
19OpenLayers contains many types of layers (you can see them all at the
20`OpenLayers website
21<http://trac.openlayers.org/browser/trunk/openlayers/lib/OpenLayers/Layer>`_).
22For this primer, we'll focus on two different layer types: ``WMS`` and
23``Vector``.
24
25The WMS Layer
26-------------
27
28This is the canonical layer type found in almost all GeoExt applications, where
29one or more images are used to display map-related information to the user. This
30type is named 'WMS' because it implements the `Web Map Service
31<http://www.opengeospatial.org/standards/wms>`_ standard set by the `Open
32Geospatial Consortium. <http://www.opengeospatial.org/>`_
33
34If you followed the :doc:`/tutorials/quickstart` guide, you will have already
35encountered a ``MapPanel`` and created your very own WMS layer. Let's dissect
36what you did:
37
38    .. code-block:: javascript
39        :linenos:
40   
41        var layer = new OpenLayers.Layer.WMS(
42            "Global Imagery",
43            "http://maps.opengeo.org/geowebcache/service/wms",
44            {layers: "bluemarble"}
45        );
46        map.addLayer(layer);
47   
48This tells OpenLayers that you'd like to create a new WMS layer referenced by
49the ``layer`` variable, and that you'd like to add that layer to the map. In
50this case, we're adding the `Blue Marble data set
51<http://earthobservatory.nasa.gov/Features/BlueMarble/>`_ provided by NASA.
52
53In **line 2** we provide "Global Imagery" as the name of the layer. This can be
54anything, and is only used to reference the layer on screen.
55
56In **line 3** we provide the location of the WMS server tasked with providing
57the images. Here, we use a GeoWebCache instance located at
58``maps.opengeo.org``\ .
59
60In **line 4** we provide extra parameters for the WMS server. Since many servers
61host different data sets, we need to specify which set we'd like. We do this by
62creating a new object and setting the ``layers`` property to ``"bluemarble"``\ ,
63the identifier for the Blue Marble data set.
64
65Note that ``layers`` isn't the only WMS parameter we can provide. You can find
66out more in the `OpenLayers API Documentation`_, by selecting 'Layer' and then
67'WMS' in the navigation.
68
69And that's it! Now let's move on to the vector layer.
70
71The Vector Layer
72----------------
73
74The WMS Layer, and many of the layer types provided by OpenLayers, use raster
75files (images like JPG, GIF, and PNG) to display maps. However, OpenLayers can
76also render map features directly in the browser, simply by adding an
77``OpenLayers.Layer.Vector`` to the map. This is useful when displaying data from
78an OGC `Web Feature Service <http://www.opengeospatial.org/standards/wfs>`, a
79KML document, or even sketched in by the user. Here's an example that generates
80some random data and displays it in a vector layer::
81
82    var vectorLayer = new OpenLayers.Layer.Vector();
83    for (var i = 0; i < 10; i++){
84        var x = -180 + Math.random() * 360;
85        var y = -90 + Math.random() * 180;
86        var numSides = 3 + Math.round(Math.random() * 6);
87        vectorLayer.addFeature(
88            new OpenLayers.Feature.Vector(
89                OpenLayers.Geometry.Polygon.createRegularPolygon(
90                    new OpenLayers.Geometry.Point(x, y),
91                    numSides)));
92    }
93
94    var map = new OpenLayers.Map();
95    map.addLayer(vectorLayer);
96
97While OpenLayers provides customized vector layers for loading data from
98existing sources, the GeoExt team recommends that you use the generic vector
99layer and populate it using :class:`GeoExt.data.FeatureStore`\ . For more
100information on doing this, see :doc:`/tutorials/remote-features-tutorial`\ .
101
102Other Layers
103------------
104
105WMS and Vector are not the only layer types in OpenLayers. There are plenty more
106available, including Google Maps, Virtual Earth, and many more. Browse the
107`OpenLayers API documentation <http://dev.openlayers.org/apidocs>`_ for more
108information.
109
110Controls
111========
112
113Although OpenLayers is great at managing layers, it also provides a way to
114interact with those layers, primarily through the use of controls.
115
116Controls are primary user interface elements and/or API hooks that control and
117manage interaction with an OpenLayers map. For instance, panning and navigating
118a map is handled by the ``OpenLayers.Control.Navigation`` control. If you want a
119zoom bar in addition to zoom buttons, you'd add a ``PanZoomBar`` control. If you
120then want to see where you've navigated, you'd use the ``NavigationHistory``
121control.
122
123Each control provides different and unique functionality. For this primer, we'll
124focus only on the ``NavigationHistory`` control.
125
126
127NavigationHistory Control
128-------------------------
129
130Take a look at the OpenLayers `NavigationHistory control example
131<http://openlayers.org/dev/examples/navigation-history.html>`_. If you view the
132source, you'll come across code like this:
133
134    .. code-block:: javascript
135       
136        var map = new OpenLayers.Map('map');
137        var nav = new OpenLayers.Control.NavigationHistory();
138        map.addControl(nav);
139       
140The above code is fairly straightforward. First create a map, then a
141``NavigationHistory`` control, and then finally add that control to the map. If
142you were to then look at your map in a web browser, you would only see the
143layers that you had added -- no special user interface elements for exploring
144the navigation history.
145
146This is because without more intervention, the NavigationHistory control only
147provides an API allowing you to scroll through the history using a programmable
148interface.
149
150But the ``NavigationHistory`` control also provides a user interface. Let's
151continue on through the example:
152
153    .. code-block:: javascript
154       
155        panel = new OpenLayers.Control.Panel({
156            div: document.getElementById("panel")
157        });
158        panel.addControls([nav.next, nav.previous]);
159        map.addControl(panel);
160       
161To expose this interface, we first create a ``Panel`` control, and then add the
162``next`` and ``previous`` buttons to the panel giving the user something to
163click on. We finally add the panel to the map.
164
165Now try the example again in your browser. *Beautiful ain't it?*
166
167Initialization w/ Controls
168--------------------------
169
170In the above examples, we only added controls to the map using the
171``map.addControl()`` method. Often, controls are added when the map is
172initialized bypassing the ``map.addControl()`` method. This is done simply by
173using the ``controls`` key and passing an array of controls, as seen below.
174
175    .. code-block:: javascript
176       
177        var map = new OpenLayers.Map({
178            controls: [
179                new OpenLayers.Control.Navigation(),
180                new OpenLayers.Control.Measure()
181            ]
182        });
183       
184.. note:: If you use the ``controls`` key, **you will not be given the default
185    controls** when initializing the map. You will have to add those controls
186    yourself instead. `Find out more.
187    <http://docs.openlayers.org/library/controls.html>`_
188
189More Controls
190--------------
191
192You can find more controls by
193`browsing the OpenLayers source code
194<http://trac.openlayers.org/browser/trunk/openlayers/lib/OpenLayers/Control>`_
195or by reading `OpenLayers' Control documentation
196<http://docs.openlayers.org/library/controls.html>`_.
197
198
199
200Events
201======
202
203Events are the main mechanism for notifying multiple objects that something has
204happened. For instance, the ``NavigationHistory`` control listens to the map's
205``zoomend`` event to save the user's zoom history for a later date; similarly,
206other objects may listen to the same event without interfering or knowing about
207the ``NavigationHistory`` control. This makes events very powerful, allowing
208objects to perform their desired function while decreasing coupling within
209OpenLayers and Ext applications.
210
211Both GeoExt and OpenLayers make extensive use of events. However, the OpenLayers
212events are slightly different from those in GeoExt, though they provide the same
213functionality. Let's explore those differences.
214
215GeoExt Events
216-------------
217
218GeoExt uses the event library that comes standard with Ext. GeoExt events are
219synonymous with Ext events.
220
221Ext events can be used in any Ext or GeoExt components that extend the
222``Ext.util.Observable`` class. `More here.
223<http://www.slideshare.net/sdhjl2000/ext-j-s-observable>`_
224
225To throw an event in any component that extends ``Ext.util.Observable``, you
226must first tell the component that the event may be thrown. For instance, in a
227custom ``Ext.Panel`` class, this is done using the ``addEvents()`` method below.
228
229.. code-block:: javascript
230   
231    var MyPanel = Ext.extend(Ext.Panel, {
232        initComponent: function() {
233            // ...
234            this.addEvents("event1" /*, "event2", ... etc.*/ );
235           
236            MyPanel.superclass.initComponent.call(this);
237        }
238    });
239
240Finally triggering the event is easy:
241
242.. code-block:: javascript
243   
244    var MyPanel = Ext.extend(Ext.Panel, {
245         
246        // ...
247         
248        myFunction: function() {
249            var arg1 = "somevalue";
250            this.fireEvent("event1", arg1 /*, arg2, ... etc. */);
251        }
252    });
253
254Great! Now in order for the event to be useful, we have to listen to it. Below
255is an example of adding two listeners to an instance of ``MyPanel`` using the
256``on()`` function, and then finally triggering the event by calling
257``myFunction()``.
258
259.. code-block:: javascript
260   
261    var panel = new MyPanel(/* ... */);
262   
263    // First listener.
264    panel.on("event1", function(arg1) {
265        alert("First listener responded. Got " + arg1 + "!");
266    });
267   
268    // Second listener.
269    panel.on("event1", function(arg1) {
270        alert("Second listener responded. Got " + arg1 + "!");
271    });
272
273    panel.myFunction();
274       
275.. note:: The ``on()`` function takes an optional third parameter that specifies
276    the scope of the listening function. If given, the ``this`` identifier
277    within the listening function will refer to the object passed.
278   
279And that's it! Now let's see how to do the same thing in OpenLayers.
280
281OpenLayers Events
282-----------------
283
284OpenLayers provides similar functionality as the ``Ext.util.Observable`` class,
285but it does so using the ``OpenLayers.Events`` class. Unlike
286``Ext.util.Observable``, OpenLayers classes do not extend ``OpenLayers.Events``.
287
288Instead, it is customary for OpenLayers classes to create an attribute called
289``events`` that is an instance of ``OpenLayers.Events``, as per the code below.
290
291.. code-block:: javascript
292   
293    var MyControl = new OpenLayers.Class(OpenLayers.Control, {
294
295        events: null,
296       
297        initialize: function() {
298            this.events = new OpenLayers.Events(
299                this,
300                null,
301                ["event1" /*, "event2", ... etc. */]
302                false
303            );
304           
305            OpenLayers.Control.prototype.initialize.call(this);
306        }
307    });
308       
309The first parameter to the ``OpenLayers.Events`` constructor is the object that
310will 'own' these events -- in other words, the caller that triggers the event.
311In situations like the example above, it is usually ``this``.
312
313The second parameter specifies a ``div`` that will listen to events thrown by
314the browser. Here, this functionality is ignored; see the note below.
315
316The third parameter is an array specifying the events that this
317``OpenLayers.Events`` object can throw. This is analogous to
318``Ext.util.Observable``'s ``addEvents()`` method, and can accept any number of
319events.
320
321The fourth parameter is the ``fallthrough``, a boolean that is related to the
322second parameter above. For our purposes, we'll leave it as ``false``.
323
324.. note:: The ``OpenLayers.Events`` class handles both browser events like when
325    the window resizes, as well as handling developer-created events like
326    ``event1`` above. This makes initializing an ``OpenLayers.Events`` object
327    fairly mucky, though using it like we did above is nearly the same. See more
328    below.
329
330Triggering an event is just as easy as Ext's ``fireEvent()``, except here we use
331``triggerEvent()``:
332
333.. code-block:: javascript
334   
335    var MyControl = new OpenLayers.Class(OpenLayers.Control, {
336
337        // ...
338       
339        myFunction: function() {
340            var evt = {
341                arg1: "somevalue" /*, arg2: ..., ... etc.*/
342            }
343            this.events.triggerEvent("event1", evt);
344        }
345    });
346       
347.. note:: ``OpenLayers.Events`` passes data to listeners using a single object
348    with properties -- otherwise called 'the event object' -- instead of passing
349    function arguments like Ext. All listener functions, then, should only
350    expect one named argument. See example below.
351
352Finally, let's add two listeners and call ``myFunction()``:
353
354.. code-block:: javascript
355   
356    var control = new MyControl(/* ... */);
357   
358    // First listener.
359    control.events.register("event1", null, function(evt) {
360        alert("First listener responded. Got " + evt.arg1 + "!");
361    });
362   
363    // Second listener.
364    control.events.register("event1", null, function(evt) {
365        alert("Second listener responded. Got " + evt.arg1 + "!");
366    });
367
368    control.myFunction();
369       
370.. note:: Like Ext's ``on()`` function, OpenLayer's ``register()`` function also
371    takes an optional ``scope`` value in order to specify the scope of the
372    listening function, but it expects this value as the second parameter passed
373    to the function. We don't have a scope for our listeners in this example,
374    hence the ``null`` parameters.
375   
376And that's it! Events in GeoExt should now be old hat. Fire away!
377
378More Information
379----------------
380
381More information about both event types can be found at the links below:
382
383* `OpenLayers Events Class Documentation <http://dev.openlayers.org/docs/files/OpenLayers/Events-js.html>`_
384* `Ext.util.Observable Class Documentation <http://dev.sencha.com/deploy/dev/docs/?class=Ext.util.Observable>`_
385* `Ext.util.Observable SlideShare <http://www.slideshare.net/sdhjl2000/ext-j-s-observable>`_
Note: See TracBrowser for help on using the repository browser.