downloading - GisClient

bookmarkalikeInternet και Εφαρμογές Web

14 Δεκ 2013 (πριν από 3 χρόνια και 7 μήνες)

478 εμφανίσεις

Introduction to OpenLayers
Documentation
Release 0.9
OpenGeo
October 30,2008
CONTENTS
1 Getting Started 3
1.1 Links to have on hand..........................................3
1.2 Workshop Modules............................................3
2 Module 1:Basics 5
2.1 A Very Simple Map...........................................5
2.2 Step 1:Getting the OpenLayers Library.................................6
2.3 Step 2:The Map in the Document Object Model (DOM)........................6
2.4 Step 3:The Map Object.........................................7
2.5 Step 4:Creating a Layer.........................................7
2.6 Step 5:Positioning the Map.......................................7
2.7 Step 6:Loading the Map.........................................8
3 Module 2:Layers 9
3.1 WMS Layers...............................................9
3.2 Commercial Layers...........................................10
3.3 WFS Layers...............................................11
4 Module 3:Controls 15
4.1 Adding New Controls..........................................15
4.2 Placing Controls Outside the Map Viewport...............................18
4.3 Grouping Controls in a Panel......................................19
4.4 Control Types..............................................20
4.5 Navigation History Control.......................................20
5 Module 4:Vector Features 23
5.1 Vector Formats..............................................23
5.2 Feature Editing..............................................25
5.3 Styling..................................................25
5.4 WFS-T..................................................28
6 Module 5:Integration 29
6.1 Exploring jQuery UI...........................................29
6.2 Using a jQuery Slider with OpenLayers.................................29
6.3 Displaying Feature Information in a jQuery Dialog...........................30
6.4 Exploring Ext JS.............................................32
6.5 Using an Ext JS Slider with OpenLayers................................32
6.6 Displaying Feature Information in an Ext JS Window..........................33
6.7 Bringing OpenLayers and Ext JS Closer Together............................34
6.8 Enter the MapPanel Class........................................34
i
6.9 Onward with the LayerTree Class....................................35
7 Glossary 39
ii
Introduction to OpenLayers Documentation,Release 0.9
OpenLayers is a rapidly-developing library for building mapping applications in a browser.The library lets developers
integrate data from a variety of sources,provides a friendly API,and results in engaging and responsive mapping
applications.
This workshop will be divided into five modules,offering a good introduction to newcomers while still providing
advanced material to more experienced developers.
Contents:
Contents 1
Introduction to OpenLayers Documentation,Release 0.9
2 Contents
CHAPTER
ONE
Getting Started
Before you start it is recommended (but not required) that you use Firefox and install Firebug.Firebug is an add-on
for Firefox that allows you to debug JavaScript in any web page.Firebug requires Firefox and cannot be used with any
other web browser.
Make sure Apache Web Server (or equivalent web server) is running on your computer.
1.1 Links to have on hand
• OpenLayers - http://openlayers.org
• OpenLayers API docs - http://dev.openlayers.org/apidocs
• OpenLayers Examples - http://openlayers.org/dev/examples
1.2 Workshop Modules
Module 1:Basics - Create an interactive map using simple JavaScript syntax.
Module 2:Layers - Explore the various layer types available with OpenLayers.We’ll cover WMS (Web Map Service),
WFS (Web Feature Service),proprietary layers (Google,Yahoo,Virtual Earth),and more.
Module 3:Controls - Learn how to bring your map to life using built-in controls available with OpenLayers,while
gaining an understanding of how to develop your own controls.
Module 4:Vector Features - Investigate various formats for dealing with vector data,with a focus on data creation,
styling,and persistence.
Module 5:Integration - Learn how OpenLayers can be used in conjunction with other user interface frameworks such
as Ext JS.
3
Introduction to OpenLayers Documentation,Release 0.9
4 Chapter 1.Getting Started
CHAPTER
TWO
Module 1:Basics
Displaying a map is at the heart of using OpenLayers,so let’s start by making a very simple map.
2.1 A Very Simple Map
Copy the following into a text editor and save it in the ol_workshop directory of your Apache document root as
1-basics.html.Open it in your browser (http://localhost/ol_workshop/1-basics.html).
<html>
<head>
<script src="openlayers/lib/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function init() {
map = new OpenLayers.Map(’map’);
var wms = new OpenLayers.Layer.WMS(
"Blue Marble",
"http://localhost/geoserver/wms",
{layers:’world’}
);
map.addLayers([wms]);
map.zoomToMaxExtent();
}
</script>
</head>
<body onload="init()">
<div id="map"style="width:600px;height:300px"></div>
</body>
</html>
When you open the page in your browser,it should look like this:
5
Introduction to OpenLayers Documentation,Release 0.9
The script can thought of as having six distinct steps:
1.The OpenLayers library is loaded using the script tag.
2.There is a div element with the id “map” that contains the map.
3.A map is created using JavaScript.
4.A layer is created using JavaScript,and then added to the map.
5.The map zooms out as far as possible.
6.JavaScript gets called only after the body tag’s onLoad event.
More details for each step are below.
2.2 Step 1:Getting the OpenLayers Library
<script src="openlayers/lib/OpenLayers.js"></script>
The openlayers/lib/OpenLayers.js URL points to the location of a JavaScript file that loads OpenLayers.
Because OpenLayers is open source,you can use debugging tools such as Firebug to explore the OpenLayers library
right in your browser!
Note:It is also easy to compress OpenLayers into a single file that dramatically improves load time.For more
information about how to set up a build profile,see http://trac.openlayers.org/wiki/Profiles.
2.3 Step 2:The Map in the Document Object Model (DOM)
<div id="map"style="width:600px;height:300px"></div>
6 Chapter 2.Module 1:Basics
Introduction to OpenLayers Documentation,Release 0.9
This is a container for the map that we are creating in our page markup.Later,when we initialize the “map” object,
we will give the id of this div element to the map’s constructor.
The size of the map is determined by the size of the element that contains it.Here,we have set the size of the map
with an inline style declaration to be 600 pixels by 300 pixels.(Note that these style declarations are better placed in
a <style> element - we’re just putting themdirectly on the div element for simplicity here).
2.4 Step 3:The Map Object
map = new OpenLayers.Map(’map’);
Maps in OpenLayers are represented by the Map class.Each map object represents a separate map on the page.We
create a new map by using the JavaScript new keyword with the OpenLayers.Map constructor.
In this code,we have passed the Map constructor an argument that is the identifier (‘map’) of the element that we
are using for the container of the map.The Map constructor can also take as an optional second argument an object
containing more parameters for fine-tuning your map’s features.
For more information,the reference for the API documentation for the Map constructor can be found at
http://dev.openlayers.org/apidocs/files/OpenLayers/Map-js.html#OpenLayers.Map.OpenLayers.Map
This code creates a newOpenLayers.Map object and gives it the variable name map.We have declared this variable
outside the init function (see var map;) so that you can access it globally (for debugging purposes).
Task
• If you are using Firebug,try typing map into the console.This will allow you to explore the map object and all
its properties.
2.5 Step 4:Creating a Layer
var wms = new OpenLayers.Layer.WMS(
"Blue Marble",
"http://localhost/geoserver/wms",
{layers:’world’}
);
map.addLayers([wms]);
OpenLayers organizes a single map into several layers.This code constructs one layer (referred to by the name wms)
and adds it to the map.
Note:Module 2:Layers will go into more detail on types of layers and how to create them.WMS layers will be
described there.
2.6 Step 5:Positioning the Map
map.zoomToMaxExtent();
2.4.Step 3:The Map Object 7
Introduction to OpenLayers Documentation,Release 0.9
This code tells the map to zoomout to its maximumextent,which by default is the entire world.It is possible to set a
different maximumextent as an option in the Map constructor.
OpenLayers maps need to be told what part of the world they should display before anything will appear on the page.
Calling map.zoomToMaxExtent() is one way to do this.Alternative ways that offer more precision include using
zoomToExtent() and setCenter().Find references to both of these map methods in the API documents:
http://dev.openlayers.org/apidocs/files/OpenLayers/Map-js.html
2.7 Step 6:Loading the Map
<body onload="init()">
In order to ensure that your document is ready,it is important to make sure that the entire page has been loaded before
the script creating the map is executed.
We ensure this by putting the map-creating code in a function that is only called when the page’s <body> element
receives the onload event.
8 Chapter 2.Module 1:Basics
CHAPTER
THREE
Module 2:Layers
Every OpenLayers map has one or more layers.Layers contain all the geospatial data that the user sees on the map.
There are several different kinds of layers.Some layers request the data as tiles of images that cover the map.Two ex-
amples of this are WMS (Web Map Service) layers,which are requested using an OGC (Open Geospatial Consortium)
open standard protocol,and also proprietary (“commercial”) layers,such as those provided by Google and Yahoo.
Another kind of layer loads the raw data feature by feature.An example of this is a WFS (Web Feature Service) layer.
More details will be given below.
3.1 WMS Layers
The 1-basics.html page created in Module 1:Basics uses a WMS layer.WMS stands for Web Map Service.It is
an OGC standard protocol for requesting geospatial data dynamically rendered as an image.The images get returned
as tiles which cover the area of the map container.
A WMS layer is created in OpenLayers with four arguments (the fourth one being optional).
Note:See the WMS layer class documentation for reference:http://dev.openlayers.org/apidocs/files/OpenLayers/Layer/WMS-
js.html
In the previous module,we:
• gave our layer the title “Blue Marble”.This is just for your convenience.
• set the URL to “http://localhost/geoserver/wms“.This is the URL from which OpenLayers will look for the
tiles.
• set the layers parameter to “world”.Since the WMS server fromwhich the images are requested may have many
different sets of data,this parameter specifies which one is being requested.
Tasks
• Copy the page you made in Module 1 and modify it so that the WMS layer is titled “OpenLayers WMS”,the
URL is “http://labs.metacarta.com/wms/vmap0“,and the layers parameter to “basic” (i.e.{layers:“basic”}).
You should be able to see a map of political boundaries for the world when you browse to that page.
• (Bonus) There are a good number of publicly available WMS sources online.Search for wms sites on Google
or try your luck at http://wms-sites.com/and add a new layer to your map.
9
Introduction to OpenLayers Documentation,Release 0.9
3.2 Commercial Layers
In addition to publicly available WMS layers,there are also a number of commercial providers of map tiles.Open-
Layers provides support for Google Maps,Yahoo Maps,Virtual Earth,and MultiMap.
Task
In this step,we’ll add a Google Maps layer to our 1-basics.html page.Make a copy of that page and save it as 2-
commercial.html.(We are using the “Blue Marble” layer in this workshop because it is hosted locally,and so will
have faster load times.)
This involves adding a new<script> tag that downloads the Google Maps code and creating a second layer for our
map.Edit your 2-commercial.html page to contain the following code.
Note:In the code below,the Google Maps script tag is wrapped for this documentation,but should be on one line in
your editor.Remove all spaces fromthe script src attribute starting with “http://maps.google.com“.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src=’http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAjpkAC9ePGem0lIq5XcMiuhR_wWLPFku8Ix9i2SXYRVK3e45q1BQUd_beF8dtzKET_EteAjPdGDwqpQ’></script>
<script src="openlayers/lib/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function init() {
map = new OpenLayers.Map(’map’);
var wms = new OpenLayers.Layer.WMS(
"Blue Marble",
"http://localhost/geoserver/wms",
{layers:’topp:bluemarble’}
);
var gphy = new OpenLayers.Layer.Google(
"Google Physical",
{type:G_PHYSICAL_MAP}
);
map.addLayers([wms,gphy]);
//add a layer switcher
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.zoomToMaxExtent();
}
</script>
</head>
<body onload="init()">
<div id="map"style="width:600px;height:300px"></div>
</body>
</html>
Reload your page in a browser and you should see two layers available fromthe layer switcher on the right.Expand the
10 Chapter 3.Module 2:Layers
Introduction to OpenLayers Documentation,Release 0.9
layer switcher with the “+” button.Toggle between the two layers to see the difference in the tiles from Blue Marble
and those fromGoogle.You’ll notice that the Blue Marble imagery looks a bit squashed compared to the Google tiles.
This is because the two layers are using two different projections (officially known as “spatial reference systems”).
3.3 WFS Layers
So far,we have dealt only with base layers.Only one base layer can be shown at a time in a map.But overlay layers
can stacked over other layers and viewed simultaneously.
In this section we will create a WFS overlay layer.WFS stands for Web Feature Service;it is another OGC stan-
dard.Instead of requesting images of rendered data,WFS requests return a serialized representation of the data itself
(vectors).OpenLayers layers requested via WFS turn the data into points,lines,and polygons in your browser.
Task
Start with a copy of your first,basic map with the Blue Marble layer.Call it 2-wfs.html.Now edit it to look like this:
<html>
<head>
<script src="openlayers/lib/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function init() {
map = new OpenLayers.Map(’map’);
var wms = new OpenLayers.Layer.WMS(
"Blue Marble",
"http://localhost/geoserver/wms",
{layers:’world’}
);
//initialize the WFS layer here
var wfs = new OpenLayers.Layer.WFS(
"States",
"http://localhost/geoserver/wfs",
{typename:"topp:states"}
);
//add both layers here
map.addLayers([wms,wfs]);
map.zoomToMaxExtent();
}
</script>
</head>
<body onload="init()">
<div id="map"style="width:600px;height:300px"></div>
</body>
</html>
Open the page in your browser.You should see polygons representing the United States overlayed on top of the
familiar base layer.
3.3.WFS Layers 11
Introduction to OpenLayers Documentation,Release 0.9
Task
Examine the map in the browser.Move the map until it is centered on the Northeast US and shows a couple dozen
states.
(For advanced users:If you are using Firefox and have Firebug installed,open your Firebug console (Ctrl+Shift+L or
Cmd+Shift+L depending on your OS).In the console tab,try entering the following:
map.getExtent();
You should be able to see how you can inspect the state of your application,accessing any properties or methods
described in the API documentation,link provided above.)
Task
Edit 2-wfs.html and set the maxExtent option on the map.You do this by giving the constructor a second argument,
in this case the object of type OpenLayers.Bounds,which represents a box-shaped area on the map.
Edit the 2-wfs.html file to change the maxExtent property of your map.If you are using Firebug,you can use values
that you get fromit,or simply use the following code:
map = new OpenLayers.Map(’map’,{
maxExtent:new OpenLayers.Bounds(
-83.02587890625,38.96728515625,
-69.84228515625,45.55908203125
)
});
Save your changes and refresh the map to see the map centered on your new location at startup.
Let’s take a look at the code:
//initialize the WFS layer here
var wfs = new OpenLayers.Layer.WFS(
"States",
12 Chapter 3.Module 2:Layers
Introduction to OpenLayers Documentation,Release 0.9
"http://localhost/geoserver/wfs",
{typename:"topp:states"}
);
This code is very similar to the WMS layer code written above.The differences are
• we are initializing a different OpenLayers class
• the URL has changed because the server uses a different URL for WFS than it does for WMS
• we include a typename parameter.This parameter names which set of data to pull from the server,similar to
layers for WMS.Later in this workshop,you will get different data by changing this parameter.
Finally,we add this layer to the map by appending it to the list of layers we pass to the map.addLayers() method:
map.addLayers([wms,wfs]);
When first loaded,the map was zoomed out to its maximum extent.That makes it hard to see the data on the WFS
overlay.OpenLayers lets you set the center and zoom level that your map opens up to so that users don’t have to
always scroll to the relevant place on the map.
Bonus Task
The map above displays two layers with data in the same spatial reference system.When showing the Google layer,
we mentioned how the tiles looked different from the Blue Marble tiles because the data was in a different spatial
reference system.For WMS layers (or tiled images in general),you are restricted to making requests in the spatial
reference systems that the server supports - that is,we cannot transform the imagery into a new spatial reference
systeminside the browser.We can,however,transformvector data (fromWFS) on the client side.
Create a map with two layers:one commercial base layer (Google) and one WFS overlay (as defined above).For the
commercial layer,you’ll want to read up on the sphericalMercator parameter.For the vector overlay,find information
on the projection option.There are examples in the OpenLayers examples directory that should be of use as well.
3.3.WFS Layers 13
Introduction to OpenLayers Documentation,Release 0.9
14 Chapter 3.Module 2:Layers
CHAPTER
FOUR
Module 3:Controls
In OpenLayers,controls provide a way for users to interact with your map.Some controls have a visual representation
and some others are invisible to the user.When you create a map with the default options,you are provided with a
few visible default controls.These controls allow users to navigate with mouse movements (drag to pan,double-click
to zoom in) and buttons to pan & zoom.In addition there are default controls that prepare the map for any layer
attributions and creating bookmarks to return to your map.
4.1 Adding New Controls
In this section,we’ll be adding a few new controls to your map.
(Find a full list of available controls in the OpenLayers API documentation:
http://dev.openlayers.org/apidocs/files/OpenLayers-js.html)
4.1.1 Overview Map
Open the 3-controls.html page in your browser (http://localhost/ol_workshop/3-controls.html).Because this map is
created with no special options,it has the default controls.We’ll add an overviewmap control that will showup in the
map (sometimes referred to as the “viewport”).
Immediately before the map.zoomToMaxExtent() line,add the following code:
var overview = new OpenLayers.Control.OverviewMap();
map.addControl(overview);
15
Introduction to OpenLayers Documentation,Release 0.9
Similarly to how we create a new map and add layers,we can create a new control and add it to the map as well.
Because we didn’t provide any arguments to the overview map constructor,we get the default options.The second
line of code above adds the control to the map.You’ll see this procedure repeated with other controls:construct a new
control,add it to your map.
4.1.2 CustomOverview Map Options
By default,when you add an overviewmap control to your map,it is configured with the same base layer as your main
map.If you want to change this or any other behavior of your control,you need to provide additional arguments when
creating the control.The map created by the overview map control can be a different layer fromthe main map.
Note:The OverviewMap control wiki page has some detail on customizing this control:
http://trac.openlayers.org/wiki/Control/OverviewMap
16 Chapter 4.Module 3:Controls
Introduction to OpenLayers Documentation,Release 0.9
Create a new WMS layer and add it to your overview map.You can use the Blue Marble global imagery layer
(“topp:bluemarble”) fromour local GeoServer instance.
var ov_imagery = new OpenLayers.Layer.WMS(
"Countries",
"http://localhost/geoserver/wms",
{layers:"topp:bluemarble"}
);
var overview = new OpenLayers.Control.OverviewMap({
layers:[ov_imagery]
});
map.addControl(overview);
You can experiment with some of the other options for configuring the overview map control following the examples
on the control’s wiki page.In the next step,we’ll add one more control to the map viewport and then see howto make
better use of the screen area on the map.
4.1.3 One More Control for the Map Viewport
Another typical control for a web mapping application is a layer switcher.A layer switcher allows users to turn on
and off various layers.For the layer switcher to be of any use,you’ll want to have at least two layers in your map.
Edit your page to create two layers (“topp:bluemarble”,and “topp:countries”) and add a layer switcher to your map.
Change your overview map so that it uses the default options.
map = new OpenLayers.Map(’map’);
var imagery = new OpenLayers.Layer.WMS(
"Global Imagery",
"http://localhost/geoserver/wms",
{layers:"topp:bluemarble"}
);
var countries = new OpenLayers.Layer.WMS(
"Countries",
"http://localhost/geoserver/wms",
4.1.Adding New Controls 17
Introduction to OpenLayers Documentation,Release 0.9
{
layers:"topp:countries",
format:"image/gif",
transparent:"TRUE"
},
{isBaseLayer:false}
);
map.addLayers([imagery,countries]);
map.addControl(new OpenLayers.Control.OverviewMap());
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.zoomToMaxExtent();
The above code uses some additional parameters for the countries layer to request GIF images with transparent back-
grounds.In addition,the option isBaseLayer is false for the layer,causing it to act as an overlay layer instead of a base
layer.
The layer switcher control is created with the default options and added to the map in a single line of code.Refresh
your page to see both the layer switcher and the overview map inside the map viewport (click on the blue plus to
expand it).At this point,your map is getting a bit cramped.By default,OpenLayers places controls that have visual
representations inside the map viewport.With a small map,it soon becomes necessary to place controls outside of the
map viewport.
4.2 Placing Controls Outside the Map Viewport
If you wanted to display the map coordinates of the mouse,you could make use of the MousePosition control.The
display for this control doesn’t take up much space,but since our viewport is already crowded,let’s create a mouse
position control and place it somewhere else on the page.
First,in the HTML body of your code,add a block level element with no content.For this example,just paste the
following below your map viewport (the div element with the id “map”).
18 Chapter 4.Module 3:Controls
Introduction to OpenLayers Documentation,Release 0.9
<div id="mouseposition"></div>
This creates a container for the output from the mouse position control.Next,construct the control with the div
property set in the options argument,and add the control to your map.
map.addControl(new OpenLayers.Control.MousePosition({
div:document.getElementById("mouseposition")
}));
Refresh your page.When you hover over the map viewport,you should see the map coordinates of your mouse
displayed below the map.This output could use a bit of style,and you can specify your style declarations in a
cascading style sheet (CSS),but for now we’ll leave it with the default style.
4.3 Grouping Controls in a Panel
In addition to placing individual controls in elements that you create outside the map viewport,you can group controls
together in a control panel.
As before,add markup that creates a container for a control panel in your page.Below the mouse position element
(the div element with id “mouseposition”),add the following markup.
<div id="panel"></div>
Now,create a control panel and add it to your map (just prior to the line containing map.zoomToMaxExtent() ).
var panel = new OpenLayers.Control.Panel({
div:document.getElementById("panel")
});
map.addControl(panel);
If you refresh your page,you shouldn’t see anything different about your application.We have to add some controls
to the panel to see something,but first,it is important to understand a bit about control types.
4.3.Grouping Controls in a Panel 19
Introduction to OpenLayers Documentation,Release 0.9
4.4 Control Types
There are three types of controls in OpenLayers - represented by three constants:
1.OpenLayers.Control.TYPE_BUTTON
2.OpenLayers.Control.TYPE_TOOL
3.OpenLayers.Control.TYPE_TOGGLE
Controls of type OpenLayers.Control.TYPE_BUTTON trigger some action when they are clicked.The ZoomOut
control is a button-type control.When you click on it,the map zooms out.
Controls of type OpenLayers.Control.TYPE_TOOL become activated when clicked on,and are deactivated by a second
click.In a control panel,only one tool-type control can be active at a time.A DrawFeature control is a tool-type
control.When active,the DrawFeature control responds to mouse events (drawing a feature).The Navigation control
is also a tool type control.You cannot draw features and navigate with your mouse at the same time,so when these
controls are both part of the same panel,only one can be active at a time.
Controls of type OpenLayers.Control.TYPE_TOGGLE can be turned on and off (by mouse clicks for example) without
affecting the state of other controls in the same panel.In a control panel,more than one toggle-type control can be
active at a time.In a vector editing environment,a snapping control can be activated to cause vertices to snap to other
vertices or edges while being dragged.Such a control would be a toggle - as it could be activated and deactivated
without altering the state of other editing controls.
A control panel itself doesn’t add behavior to your application.However,when you add controls to a panel,the
behavior of these controls is modified depending on the control type.
4.5 Navigation History Control
In the next step,you’ll add a navigation history control to your map.This control has two sub-controls:“previous”
and “next.” These sub-controls are button-type controls.When you click on the “previous” or “next” controls,the
map returns to the previous or next states in the map’s navigation history (similar to back and forward buttons in your
browser’s history,except limited to the history of map navigation).
To configure the display of the next and previous controls,you need to add a few style declarations to your page.In
the head of your page,add the following code.
<style>
#panel {
right:0px;
height:30px;
width:200px;
}
#panel div {
float:left;
margin:5px;
}
</style>
The above style declarations determine the position and size of the element with id panel and specify the layout of div
elements within the panel element.
Next,create a navigation history control,add it to the map,and add the two sub-controls to the panel control created
above.
20 Chapter 4.Module 3:Controls
Introduction to OpenLayers Documentation,Release 0.9
var history = new OpenLayers.Control.NavigationHistory();
map.addControl(history);
panel.addControls([history.next,history.previous]);
Refresh your page.You should see two button-type controls below the mouse position output.
4.5.Navigation History Control 21
Introduction to OpenLayers Documentation,Release 0.9
22 Chapter 4.Module 3:Controls
CHAPTER
FIVE
Module 4:Vector Features
In Module 2,we saw two different kinds of layers:layers that loaded images that tiled the surface of the map (WMS),
and layers that loaded individual features as points,lines,and polygons (WFS).In this module,we will explore the
power OpenLayers gives you over vector data.
5.1 Vector Formats
OpenLayers has the ability to read and write vector data in a variety of different serialized formats.These include:
• GeoJSON - A standard way of representing geospatial features using JavaScript Object Notation.
• KML - An XML schema for geospatial data that is used by Google Earth and Google Maps.
• GeoRSS - An emerging standard for encoding location as part of an RSS feed.
• GML - The Open Geospatial Consortium’s XML schema for representing geographic features.
• WKT - Well Known Text,a simple text format for representing features,also supported by the OGC.
Task
Open 4-vector-formats.html in your browser.Use the drawing tools to draw points,lines and polygons.Hover over
features you have drawn (with the hand tool) to see the underlying code used to generate those features.Change output
formats using the dropdown menu to see the various formats for vector feature serialization.Try to get a sense of the
structure of each format.
Task
If you have already installed Google Earth on your system,draw lines or polygons in Google Earth,select and copy
them,and paste themin to the input box in this example.Select KML as the format and click the “add feature” button.
23
Introduction to OpenLayers Documentation,Release 0.9
24 Chapter 5.Module 4:Vector Features
Introduction to OpenLayers Documentation,Release 0.9
Bonus Task
The above task can also be done in reverse.Draw a feature in OpenLayers,choose KML from the drop-down menu,
and then hover over the feature.Copy the output and paste into Google Earth (the “My Places” folder must be selected
in Google Earth before you can paste in a new shape).
5.2 Feature Editing
One of the reasons you might want to load data into OpenLayers as vector data instead of rendered as tiles is that
OpenLayers provides tools that let you modify individual features.
Task
Open 4-modify.html in your browser.Practice drawing polygons and modifying features you have drawn.The modify
feature control can be configured with options that allow feature rotation,resizing,or reshaping.
5.3 Styling
Another reason why you might want to use a vector layer is that with OpenLayers you get powerful tools for controlling
the appearance of,or “styling,” that data in your client.
By default,features rendered by OpenLayers are orange.This style is completely customizable using style rules that
can either be written in JavaScript or read in froman external style file (such as an SLD fromGeoServer).
Task
Open 4-style-rules.html in your browser.This example requests US States from GeoServer with a WFS layer.This
layer is rendered on the client side using rules that determine color based on population.
Take a look at the source code of this example.First,notice that we have added an extra property to our WFS layer:
var states = new OpenLayers.Layer.WFS(
"US States",
5.2.Feature Editing 25
Introduction to OpenLayers Documentation,Release 0.9
"http://localhost/geoserver/wfs",
{typename:"topp:states"},
{isBaseLayer:true,extractAttributes:true,styleMap:myStyleMap}
);
We set the styleMap property of the layer to myStyleMap.
var myStyleMap = new OpenLayers.StyleMap({
"default":defStyle,
"select":selStyle
});
In this case,we have initialized the StyleMap with a hash of Styles,indexed by “render intent.” The three render
intents are:
• default - style for standard display of features on the map
• select - style for features that have been selected somehow
• temporary - style for features that are meant to only temporarily be on the map
Our example uses only the default and select render intent.Notice how when you hover over one of the features in
the example,the appearance of that feature changes.That’s because a different style (with a select intent) is used for
selected features fromthe default.
Now let’s look at a particular style.
var selStyle = new OpenLayers.Style({
fillColor:"#ffaa00"
});
This is the style for selected features in the example.In this case,the constructor takes a key/value pair (“hash”) that
tells OpenLayers how to render the feature when this style is used (in this case:fillColor:“#ffaa00”).
More complex styles can use several rules to determine how different features get rendered.For example,look at the
first rule added to the default style:
defStyle.addRules([
new OpenLayers.Rule({
symbolizer:{
fillColor:"#ffeecc"
},
filter:new OpenLayers.Filter.Comparison({
type:OpenLayers.Filter.Comparison.LESS_THAN,
property:"PERSONS",
value:1000000
})
}),
//...
This rule sets the fill color of features that pass through the given filter.OpenLayers Filters are based on the OGC filter
specification,and work in a similar way.This filter matches any feature which has a PERSONS property that is less
than 1000000.There are other rules in this code for other population ranges.
Note:More information about how to build Comparison filters can be found at
http://dev.openlayers.org/apidocs/files/OpenLayers/Filter/Comparison-js.html.
26 Chapter 5.Module 4:Vector Features
Introduction to OpenLayers Documentation,Release 0.9
In addition to creating rule-based styling,feature styles can be determined based on any function that evaluates each
vector feature.
Task
Open the 4-style-context.html example.This example is similar to the previous example except that the fill color is
based on population density,a value that is not intrinsic to the data but instead is calculated dynamically.Both this
example and the previous one use a SelectFeature control.Here the SelectFeature control is used to change the feature
style and display details about the selected feature (name and population density).Open the example in your text
editor to see how the control is configured.
Look at how this style is written:
var defStyle = new OpenLayers.Style(
{
strokeWidth:0,
fillColor:"${getFillColor}"
},{
context:{
getFillColor:function(feature) {
var max = 75;
var density = feature.attributes.PERSONS/feature.attributes.LAND_KM;
//calculate hex values from density
var grn = (
Math.round(
225
*
(1 - Math.min(max,density)/max)
)).toString(16);
grn = (grn.length == 1)?("0"+ grn):grn;
//...
return"#ff"+ grn + blu;
}
}
}
);
5.3.Styling 27
Introduction to OpenLayers Documentation,Release 0.9
In this style,we define a “context” for the style,which includes a function named getFillColor which takes a feature
as its argument and outputs some color value based on the properties of the feature.The “${...}” syntax is then used
to refer to that function in the context.When this style is used to determine howa feature is rendered,the getFillColor
function gets called on that feature,and the output of that function is assigned to that feature’s fillColor property in the
renderer.
Bonus Task
See if you can edit the 4-style-context.html example to create styles that colors all states blue whose names start with
the letter “M”.(The property that stores a state’s name is STATE_NAME.) The following reference might be useful:
http://www.w3schools.com/jsref/jsref_obj_string.asp.
5.4 WFS-T
OpenLayers is valuable as a vector editing tool (see Section 2 of this module) because it can interact with persistent data
stores on servers.In this section,we will use WFS-Transactional (WFS-T),an OGC standard for issuing transactions
to a set of geospatial data in order to modify that data on a server.
Task
Open 4-persistence.html in your browser.Examine the points on the map by clicking on them.Now add your own
point by clicking the “Add Point” button,putting in a title and description for your point,and then clicking on the map.
Look at the Request box.Inside should be the XML that has been POSTed to the server in order to tell it about your
change to the data.Embedded in this request is a description of your point in one of the formats you looked at in
Section 1 of this module.Can you tell which one?
Refresh the page.You should see you point loaded onto the map.Click on it to make sure.
28 Chapter 5.Module 4:Vector Features
CHAPTER
SIX
Module 5:Integration
As suggested by the title of this workshop,OpenLayers provides the mapping foundation for your web application.
To build an application with rich user interface components,OpenLayers is best paired with a UI framework.There
are a number of full featured UI frameworks available;Ext JS,Dojo (via Dijit),and YUI are popular frameworks with
good layout controls and widgets.This module provides examples of integrations with Ext JS as well as the less well
established,but rapidly developing jQuery UI libraries.
6.1 Exploring jQuery UI
The jQuery library is focused on providing efficient shortcuts for accessing DOMelements,adding behavior to those
elements,and simplifying typical AJAXcoding patterns.The jQuery UI library builds on the jQuery core by providing
themeable widgets.Both the UI library and the core are designed around and dedicated to unobtrusive JavaScript
coding,providing a concise workflow.
jQuery links:
• jQuery http://jquery.com/
• jQuery UI http://ui.jquery.com/
• jQuery UI Docs http://docs.jquery.com/UI
In addition to the links above,you’ll find jQuery UI examples in the jquery-ui directory included with this workshop.
Spend a bit of time reading the material on jQuery,including the demos and tutorials.
6.2 Using a jQuery Slider with OpenLayers
The jQuery UI slider widget creates a draggable handle that can be configured to return a value within some range
based on the handle position.Raster layers in OpenLayers provide a setOpacity method that controls the image opacity
and accepts values between 0 (totally transparent) and 1 (totally opaque).A slider widget is a user-friendly way to set
layer opacity.
A jQuery UI slider can be created with something like the following markup.
<div id="slider">
<div class="ui-slider-handle"></div>
</div>
To give these elements the slider behavior,you would run the following code.
29
Introduction to OpenLayers Documentation,Release 0.9
jQuery("#slider").slider();
The jQuery function is also exported under the alias $.In the examples below,you’ll see the use of the $ function -
this is entirely equivalent to using the jQuery function.Look in the slider documentation on the jQuery UI site to how
you could define a function that would be called with each movement of the slider handle.
The 5-jqui-slider.html example shows the use of a slider to set layer opacity.See how you can change the opacity of
the country boundaries and labels with the slider.
Task:
In the jQuery documentation,find the options to the slider function that allow you to specify a number of incremental
steps within the slider range.Experiment with adding discrete intervals to the slider range.Modify the end values of
the range to restrict opacity settings.
6.3 Displaying Feature Information in a jQuery Dialog
OpenLayers provides a number of pop-up classes for displaying information in the map viewport.It is often appropri-
ate to have uniform dialogs displayed from your map and from other parts of your application.The jQuery UI dialog
function is a flexible way to produce themeable dialogs that serve a variety of purposes.
The previous example started with existing markup and used the jQuery function to select and modify DOMelements.
The jQuery function can also be used to create elements given an HTML string.The code belowcreates a div element
and turns it into a modeless dialog.
jQuery("<div>Hello!</div>").dialog();
This technique is used in the 5-jqui-dialog.html example to create dialogs populated with the results from WMS
GetFeatureInfo requests.OpenLayers does not provide a control to construct GetFeatureInfo requests,but a simple
control can be created as in the example.Open the example in your browser.Click on the map to see information
about a country displayed in a dialog.
30 Chapter 6.Module 5:Integration
Introduction to OpenLayers Documentation,Release 0.9
Tasks
• Find the appropriate documentation to determine how to make the feature info windows modal - so that you
have to close a window before interacting with anything else in the application.
• Experiment with editing the style declarations in the head of the page to change the look of the displayed
information.The page loads a stylesheet for the default jQuery UI theme.Find the themes directory in the
jquery-ui directory and load a different stylesheet.Note that in if you choose a non-default theme (say “flora”)
the element that is used to create a dialog needs to have an additional CSS class name (in this case,“flora”).You
can use the jQuery addClass function to add a class name to an element before calling dialog().
6.3.Displaying Feature Information in a jQuery Dialog 31
Introduction to OpenLayers Documentation,Release 0.9
6.4 Exploring Ext JS
Ext JS is an extremely full-featured library for complex layouts and dynamic widgets.Ext JS is especially useful for
mimicking desktop applications in a browser.The library is a heavier dependency (and thus a larger download) than
jQuery UI,but does provide a more robust tool set.
Ext JS links:
• Ext JS overview http://extjs.com/products/extjs/
• Ext JS samples http://extjs.com/deploy/dev/examples/
• Ext JS documentation http://extjs.com/deploy/dev/docs/
Note that the entire Ext JS example set and documentation is available in the ext directory packaged with this module.
Spend a bit of time exploring the Ext examples and figuring out how to use the documentation.
6.5 Using an Ext JS Slider with OpenLayers
As with the jQuery sliders,an Ext slider provides a widget for collecting a user supplied value within some range.
This exercise will duplicate the functionality of the above 5-jqui-slider.html example.
The configuration for Ext widgets is extremely flexible.One way to create a slider widget is to start with a DOM
element that will serve as the slider container.
<div id="slider"></div>
Given the above,the following code creates a functioning Ext slider.
var slider = new Ext.Slider({renderTo:"slider"});
The 5-ext-slider.html example uses the above technique to create a slider widget for setting the opacity of a layer.
Open the example in your browser to see the slider in action.
32 Chapter 6.Module 5:Integration
Introduction to OpenLayers Documentation,Release 0.9
Tasks
Find the Slider widget in the Ext JS documentation.Locate the configuration option that allows you to specify a set
of intervals for setting the slider value.Experiment with adding a set of intervals to the slider.Configure the slider to
restrict the range of opacity values that can be set.
6.6 Displaying Feature Information in an Ext JS Window
Ext JS provides windows with behavior and looks familiar to desktop application developers.The theme for an Ext
based application is moderately configurable,though developing custom themes can be labor-intensive.Using Ext
windows to display map related information gives your application a well integrated feel if you are using Ext widgets
for non-map related parts of your application.
An Ext window can be created with no existing markup.The following code creates a modeless window and opens it.
var win = new Ext.Window({
title:"Window",
items:[
{html:"Hello!"}
]
});
win.show();
Ext builds complex elements based on containers with one or more items.The windowabove contains a panel element
that was created from the HTML string “Hello!” Using the above technique,windows can be created to display
information about features on your map.
Open the 5-ext-window.html example in your browser.Click on the map to issue a request for information about a
country.This information will be presented in an Ext window.
Tasks
• Find the Ext.Window class in the Ext documentation.Change the configuration of the windows in the 5-ext-
window.html example to make them modal windows (so your application will not receive browser events until
the window is closed).
• Experiment with some of the other window configuration properties to change the look or behavior of the
windows displayed by the example.
6.6.Displaying Feature Information in an Ext JS Window 33
Introduction to OpenLayers Documentation,Release 0.9
6.7 Bringing OpenLayers and Ext JS Closer Together
Up to this point,we’ve been exploring integration that involves the use of standard library widgets with standard
OpenLayers functionality.In the above examples,the widgets don’t really “know” much of anything about the map,
and the map doesn’t really “know” anything about the widgets.It is also possible to extend Ext (or jQuery) components
with specific map related functionality.
The OpenLayers.Map constructor creates functioning maps given a single DOMelement,independent of its context.
The Ext.Panel class provides flexible components that can be nested in other containers to build complex layouts.A
merger of the two would be a MapPanel class that creates a functional map that is easily coupled together with other
components in rich applications.
6.8 Enter the MapPanel Class
The workshop materials include a geoext directory with a couple custom Ext classes.The MapPanel class extends
Ext.Panel and contains an OpenLayers.Map.The MapPanel class registers an “xtype” with Ext,meaning that it can
be instantiated with the configuration syntax similar to other Ext components.
Open the 5-geoext-mappanel.html example to see a MapPanel instance in an Ext.Window.View the page source in
your text editor and familiarize yourself with the syntax.
34 Chapter 6.Module 5:Integration
Introduction to OpenLayers Documentation,Release 0.9
Tasks
• Based on code fromearlier examples,add one or more additional layers to the map panel.
• The control’s configuration properties (xtype:“mappanel”) can be used to add non-default controls to the map.
Experiment with adding a layer switcher or a scale line control to the map.
6.9 Onward with the LayerTree Class
As an alternative to a custom-built layer switcher,the Ext.tree.TreePanel can be used to represent a hierarchy of layers
with different functionality than the OpenLayers.Control.LayerSwitcher.As with a folder/file tree in the file explorers
of most operating systems,the Ext.tree.TreePanel allows for nodes to be nested,reordered,expanded,and collapsed.
In a mapping application with a single “group” of layers,much of the functionality of a tree is not accessed.However
a customlayer switcher control can also be used to provide layer grouping that is not provided by OpenLayers itself.
Find the 5-geoext-layertree.html example and open it in both your web browser and text editor.See howlayer visibility
and ordering can be controlled.
6.9.Onward with the LayerTree Class 35
Introduction to OpenLayers Documentation,Release 0.9
Tasks
Work on creating a newexample that uses both the LayerTree and MapPanel components.Since you need to access the
OpenLayers.Map instance in the MapPanel to configure the LayerTree,the structure of your example will be different
than the preceding examples.The following code should be of assistance in getting started.
//an alternative to creating a MapPanel with a
//configuration object only
var mapPanel = new GeoExt.component.MapPanel({
layers:layerList
});
//the LayerTree needs to have a reference to the
//map property of the MapPanel
var layerTree = new GeoExt.component.LayerTree({
map:mapPanel.map
});
//both of the above components can be items in
//Ext.Window instances
36 Chapter 6.Module 5:Integration
Introduction to OpenLayers Documentation,Release 0.9
6.9.Onward with the LayerTree Class 37
Introduction to OpenLayers Documentation,Release 0.9
38 Chapter 6.Module 5:Integration
CHAPTER
SEVEN
Glossary
OGC The Open Geospatial Consortium(OGC) is a standards organization that develops specifications for geospatial
services.
WFS The Web Feature Service (WFS) specification from the OGC defines an interface for reading and writing geo-
graphic features across the web.
WMS The Web Map Service (WMS) specification from the OGC defines an interface for requesting rendered map
images across the web.
• Search Page
39