Map Server
Map Server
Release 6.0
1 About 3
2 An Introduction to MapServer 5
2.1 MapServer Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Anatomy of a MapServer Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3 Installation and Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.4 Introduction to the Mapfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.5 Making the Site Your Own . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.6 Enhancing your site . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.7 How do I get Help? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3 MapServer Tutorial 25
3.1 Tutorial Timeframe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.2 Tutorial Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.3 Before Using the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.4 Windows, UNIX/Linux Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.5 Other Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.6 Section 1: Static Maps and the MapFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.7 Section 2: CGI variables and the User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.8 Section 3: Query and more HTML Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.9 Section 4: Advanced User Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4 Installation 31
4.1 Compiling on Unix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.2 Compiling on Win32 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.3 PHP MapScript Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.4 .NET MapScript Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.5 IIS Setup for MapServer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
4.6 Oracle Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
5 Mapfile 63
5.1 Cartographical Symbol Construction with MapServer . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.2 CLASS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
5.3 CLUSTER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
i
5.4 Display of International Characters in MapServer . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
5.5 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
5.6 FEATURE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
5.7 FONTSET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
5.8 GRID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
5.9 INCLUDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
5.10 JOIN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
5.11 LABEL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
5.12 LAYER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
5.13 LEGEND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
5.14 MAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
5.15 OUTPUTFORMAT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
5.16 PROJECTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
5.17 QUERYMAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
5.18 REFERENCE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
5.19 SCALEBAR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
5.20 STYLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
5.21 SYMBOL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
5.22 Symbology Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
5.23 Templating . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
5.24 Union Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
5.25 Variable Substitution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
5.26 WEB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
5.27 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
6 MapScript 171
6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
6.2 SWIG MapScript API Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
6.3 PHP MapScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
6.4 Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
6.5 Python MapScript Appendix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
6.6 Python MapScript Image Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
6.7 Mapfile Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
6.8 Querying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
6.9 MapScript Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
ii
9.1 WMS Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
9.2 WMS Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
9.3 WMS Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
9.4 Map Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
9.5 WFS Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
9.6 WFS Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
9.7 WFS Filter Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
9.8 SLD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
9.9 WCS Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
9.10 WCS Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
9.11 SOS Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
9.12 MapScript Wrappers for WxS Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
10 Optimization 503
10.1 Debugging MapServer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
10.2 FastCGI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
10.3 Mapfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
10.4 Raster . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
10.5 Tile Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
10.6 Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
11 Utilities 525
11.1 legend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
11.2 msencrypt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
11.3 scalebar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
11.4 shp2img . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
11.5 shptree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
11.6 shptreetst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
11.7 shptreevis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
11.8 sortshp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
11.9 sym2img . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534
11.10 tile4ms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
11.11 Batch Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
11.12 File Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
12 CGI 541
12.1 MapServer CGI Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
12.2 mapserv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
12.3 Map Context Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
12.4 MapServer CGI Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
12.5 Run-time Substitution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
12.6 A Simple CGI Wrapper Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
14 Development 555
14.1 Sponsors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
14.2 MapServer Release Plans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
14.3 Announcements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
14.4 Bug Submission . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
14.5 Subversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
iii
14.6 Documentation Development Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
14.7 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
14.8 Request for Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
14.9 Mapfile Editing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 775
14.10 External Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777
15 Download 779
15.1 Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
15.2 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
15.3 Binaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 780
15.4 Demo Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 781
16 Glossary 783
17 Errors 787
17.1 drawEPP(): EPPL7 support is not available . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
17.2 loadMapInternal(): Given map extent is invalid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
17.3 msSaveImageGD(): Unable to access file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 788
17.4 msLoadMap(): Failed to open map file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
17.5 msQueryByPoint: search returned no results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
17.6 msLoadFontset(): Error opening fontset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
17.7 msGetLabelSize(): Requested font not found . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
17.8 loadLayer(): Unknown identifier. Maximum number of classes reached . . . . . . . . . . . . . . . . 790
17.9 msReturnPage(): Web application error. Malformed template name . . . . . . . . . . . . . . . . . . 790
17.10 Unable to load dll (MapScript) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
17.11 msProcessProjection(): Projection library error.major axis or radius = 0 not given . . . . . . . . . . . 791
17.12 msProcessProjection(): no options found in ‘init’ file . . . . . . . . . . . . . . . . . . . . . . . . . . 791
17.13 msProcessProjection(): No such file or directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . 792
17.14 msQueryByPoint: search returned no results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 792
18 FAQ 795
18.1 Where is the MapServer log file? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795
18.2 What books are available about MapServer? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795
18.3 How do I compile MapServer for Windows? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795
18.4 What do MapServer version numbers mean? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795
18.5 Is MapServer Thread-safe? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 796
18.6 What does STATUS mean in a LAYER? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797
18.7 How can I make my maps run faster? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797
18.8 What does Polyline mean in MapServer? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797
18.9 What is MapScript? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798
18.10 Does MapServer support reverse geocoding? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798
18.11 Does MapServer support geocoding? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798
18.12 How do I set line width in my maps? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798
18.13 Why do my JPEG input images look crappy via MapServer? . . . . . . . . . . . . . . . . . . . . . . 798
18.14 Which image format should I use? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 799
18.15 Why doesn’t PIL (Python Imaging Library) open my PNGs? . . . . . . . . . . . . . . . . . . . . . . 799
18.16 Why do my symbols look poor in JPEG output? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 800
18.17 How do I add a copyright notice on the corner of my map? . . . . . . . . . . . . . . . . . . . . . . . 800
18.18 How do I have a polygon that has both a fill and an outline with a width? . . . . . . . . . . . . . . . 801
18.19 How can I create simple antialiased line features? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802
18.20 Which OGC Specifications does MapServer support? . . . . . . . . . . . . . . . . . . . . . . . . . . 802
18.21 Why does my requested WMS layer not align correctly? . . . . . . . . . . . . . . . . . . . . . . . . 803
18.22 When I do a GetCapabilities, why does my browser want to download mapserv.exe/mapserv? . . . . 804
18.23 Why do my WMS GetMap requests return exception using MapServer 5.0? . . . . . . . . . . . . . . 804
iv
18.24 Using MapServer 6.0, why don’t my layers show up in GetCapabilities responses or are not found
anymore? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
18.25 Where do I find my EPSG code? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
18.26 How can I reproject my data using ogr2ogr? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
18.27 What’s with MapServer’s logo? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
19 License 807
20 Credits 809
Bibliography 811
v
vi
MapServer Documentation, Release 6.0
Note: The entire documentation is also available as a single PDF document and ePub document
If you plan on upgrading to the MapServer 6.0 release, be sure to review the MapServer Migration Guide.
Contents 1
MapServer Documentation, Release 6.0
2 Contents
CHAPTER 1
About
MapServer is an Open Source geographic data rendering engine written in C. Beyond browsing GIS data, MapServer
allows you create “geographic image maps”, that is, maps that can direct users to content. For example, the Minnesota
DNR Recreation Compass provides users with more than 10,000 web pages, reports and maps via a single application.
The same application serves as a “map engine” for other portions of the site, providing spatial context where needed.
MapServer was originally developed by the University of Minnesota (UMN) ForNet project in cooperation with
NASA, and the Minnesota Department of Natural Resources (MNDNR). Later it was hosted by the TerraSIP project,
a NASA sponsored project between the UMN and a consortium of land management interests.
MapServer is now a project of OSGeo, and is maintained by a growing number of developers (nearing 20) from
around the world. It is supported by a diverse group of organizations that fund enhancements and maintenance,
and administered within OSGeo by the MapServer Project Steering Committee made up of developers and other
contributors.
• Advanced cartographic output
– Scale dependent feature drawing and application execution
– Feature labeling including label collision mediation
– Fully customizable, template driven output
– TrueType fonts
– Map element automation (scalebar, reference map, and legend)
– Thematic mapping using logical- or regular expression-based classes
• Support for popular scripting and development environments
– PHP, Python, Perl, Ruby, Java, and .NET
• Cross-platform support
– Linux, Windows, Mac OS X, Solaris, and more
• Support of numerous Open Geospatial Consortium <OGC (OGC) standards
– WMS (client/server), non-transactional WFS (client/server), WMC, WCS, Filter Encoding, SLD, GML,
SOS, OM
• A multitude of raster and vector data formats
– TIFF/GeoTIFF, EPPL7, and many others via GDAL
3
MapServer Documentation, Release 6.0
– ESRI shapfiles, PostGIS, ESRI ArcSDE, Oracle Spatial, MySQL and many others via OGR
• Map projection support
– On-the-fly map projection with 1000s of projections through the Proj.4 library
4 Chapter 1. About
CHAPTER 2
An Introduction to MapServer
Contents
• An Introduction to MapServer
– MapServer Overview
– Anatomy of a MapServer Application
– Installation and Requirements
– Introduction to the Mapfile
– Making the Site Your Own
– Enhancing your site
– How do I get Help?
MapServer is a popular Open Source project whose purpose is to display dynamic spatial maps over the Internet. Some
of its major features include:
• support for display and querying of hundreds of raster, vector, and database formats
• ability to run on various operating systems (Windows, Linux, Mac OS X, etc.)
• support for popular scripting languages and development environments (PHP, Python, Perl, Ruby, Java, .NET)
• on-the-fly projections
5
MapServer Documentation, Release 6.0
– Initialization File - uses a form with hidden variables to send an initial query to the http server and
MapServer. This form could be placed on another page or be replaced by passing the initialization infor-
mation as variables in a URL.
– Template File - controls how the maps and legends output by MapServer will appear in the browser. By
referencing MapServer CGI variables in the template html, you allow MapServer to populate them with
values related to the current state of your application (e.g. map image name, reference image name, map
extent, etc.) as it creates the html page for the browser to read. The template also determines how the user
can interact with the MapServer application (browse, zoom, pan, query).
See Also:
Templating
• MapServer CGI - The binary or executable file that receives requests and returns images, data, etc. It sits in the
cgi-bin or scripts directory of the http server. The Web server user must have execute rights for the directory that
it sits in, and for security reasons, it should not be in the web root. By default, this program is called mapserv
• HTTP Server - serves up the html pages when hit by the user’s browser. You need a working HTTP (Web)
server, such as Apache or Microsoft Internet Information Server, on the machine on which you are installing
MapServer.
OSGeo4W is a new Windows installer that downloads and/or updates MapServer, add-on applications, and also other
Open Source geospatial software. The following steps illustrate how to use OSGeo4W:
1. Download OSGeo4W http://download.osgeo.org/osgeo4w/osgeo4w-setup.exe
2. Execute (double-click) the .exe
3. Choose “Advanced” install type
Note: Express contains options for higher-level packages such as MapServer, GRASS, and uDig. Advanced
gives you full access to choosing commandline tools and applications for MapServer that are not included in the
Express install
4. Select packages to install
Note: Click on the “Default” text beside the higher-level packages (such as Web) to install all of Web’s sub-
packages, or click on the “Skip” text beside the sub-package (such as MapServer) to install that package and all
of its dependencies.
5. Let the installer fetch the packages.
MapServer runs on Linux, Windows, Mac OS X, Solaris, and more. To compile or install some of the required pro-
grams, you may need administrative rights to the machine. People commonly ask questions about minimum hardware
specifications for MapServer applications, but the answers are really specific to the individual application. For devel-
opment and learning purposes, a very minimal machine will work fine. For deployment, you will want to investigate
Optimization of everything from your data to server configuration.
You need a working and properly configured HTTP (Web) server, such as Apache or Microsoft Internet Information
Server, on the machine on which you are installing MapServer. OSGeo4W contains Apache already, but you can
reconfigure things to use IIS if you need to. Alternatively, MS4W can be used to install MapServer on Windows.
If you are on a Windows machine, and you don’t have a HTTP server installed, you may want to check out MS4W,
which will install a pre-configured HTTP server, MapServer, and more. The FGS Linux Installer provides similar
functionality for several Linux distributions.
This introduction will assume you are using pre-compiled OSGeo4W Windows binaries to follow along. Obtaining
MapServer or Linux or Mac OS X should be straightforward. Visit Download for installing pre-compiled MapServer
builds on Mac OS X and Linux.
You will also need a Web browser, and a text editor (vi, emacs, notepad, homesite) to modify your html and mapfiles.
2.3.4 Skills
In addition to learning how the different components of a MapServer application work together and learning Map File
syntax, building a basic application requires some conceptual understanding and proficiency in several skill areas.
You need to be able to create or at least modify HTML pages and understand how HTML forms work. Since the
primary purpose of a MapServer application is to create maps, you will also need to understand the basics of geographic
data and likely, map projections. As your applications get more complex, skills in SQL, DHTML/Javascript, Java,
databases, expressions, compiling, and scripting may be very useful.
The .map file is the basic configuration file for data access and styling for MapServer. The file is an ASCII text file,
and is made up of different objects. Each object has a variety of parameters available for it. All .map file (or mapfile)
parameters are documented in the mapfile reference. A simple mapfile example displaying only one layer follows, as
well as the map image output:
MAP
NAME "sample"
STATUS ON
SIZE 600 400
SYMBOLSET "../etc/symbols.txt"
EXTENT -180 -90 180 90
UNITS DD
SHAPEPATH "../data"
IMAGECOLOR 255 255 255
FONTSET "../etc/fonts.txt"
#
# Start of web interface definition
#
WEB
IMAGEPATH "/ms4w/tmp/ms_tmp/"
IMAGEURL "/ms_tmp/"
END
#
# Start of layer definitions
#
LAYER
NAME ’global-raster
TYPE RASTER
STATUS DEFAULT
DATA b l u e m a r b le.gif
END
END
Note:
• Comments in a mapfile are specified with a ‘#’ character
• MapServer parses mapfiles from top to bottom, therefore layers at the end of the mapfile will be drawn last
(meaning they will be displayed on top of other layers)
• Using relative paths is always recommended
• Paths should be quoted (single or double quotes are accepted)
• starting with MapServer 5.0, there is no limit to the number of layers in a mapfile
• DATA parameter is relative to the SHAPEPATH parameter the MAP object
• if no DATA extension is provided in the filename, MapServer will assume it is an ESRI shapefile (.shp)
Raster Layers
LAYER
NAME "bathymetry"
TYPE RASTER
STATUS DEFAULT
DATA "bath_mapserver.tif"
END
See Also:
Raster Data
Vector Layers
Vector layers of TYPE point, line, or polygon can be displayed. The following example shows how to display only
lines from a TYPE polygon layer, using the OUTLINECOLOR parameter:
LAYER
NAME "world_poly"
DATA ’shapefile/countries_area.shp’
STATUS ON
TYPE POLYGON
CLASS
NAME ’The World’
STYLE
OUTLINECOLOR 0 0 0
END
END
END # layer
See Also:
Vector Data
• typical styling information is stored within the CLASS and STYLE objects of a LAYER
• starting with MapServer 5.0, there is no limit to the number of classes or styles in a mapfile
• the following example shows how to display a road line with two colors by using overlayed STYLE objects
CLASS
NAME "Primary Roads"
STYLE
SYMBOL "circle"
COLOR 178 114 1
SIZE 15
END #style1
STYLE
SYMBOL "circle"
COLOR 254 161 0
SIZE 7
END #style2
END
2.4.4 SYMBOLs
SYMBOLSET "../etc/symbols.txt"
END
See Also:
Cartographical Symbol Construction with MapServer, Symbology Examples, and SYMBOL
2.4.5 LABEL
Figure 2.6: Rendered Bluemarble image with skier symbol and a label
See Also:
LABEL, FONTSET
1. String comparisons
(EXPRESSION "africa")
2. Regular expressions
(EXPRESSION /^9|^10/)
3. Logical expressions
([POPULATION] > 50000 AND ’[LANGUAGE]’ eq ’FRENCH’)
Note: Logical expressions should be avoided wherever possible as they are very costly in terms of drawing time.
See Also:
Expressions
2.4.7 INCLUDE
Added to MapServer 4.10, any part of the mapfile can now be stored in a separate file and added to the main mapfile
using the INCLUDE parameter. The filename to be included can have any extension, and it is always relative to the
main .map file. Here are some potential uses:
• LAYER s can be stored in files and included to any number of applications
• STYLE s can also be stored and included in multiple applications
The following is an example of using mapfile includes to include a layer definition in a separate file:
If ‘shadedrelief.lay’ contains:
LAYER
NAME ’shadedrelief’
STATUS ON
TYPE RASTER
DATA ’GLOBALeb3colshade.jpg’
END
The following is an example of a mapfile where all LAYER s are in separate .lay files, and all other objects (WEB,
REFERENCE, SCALEBAR, etc.) are stored in a “.ref” file:
NAME "base"
#
# include reference objects
#
INCLUDE "../templates/template.ref"
#
# Start of layer definitions
#
INCLUDE "../layers/usa/usa_outline.lay"
INCLUDE "../layers/canada/base/1m/provinces.lay"
INCLUDE "../layers/canada/base/1m/roads_atlas_of_canada_1m.lay"
INCLUDE "../layers/canada/base/1m/roads_atlas_of_canada_1m_shields.lay"
INCLUDE "../layers/canada/base/1m/populated_places.lay"
END # Map File
Warning: Mapfiles must end with the .map extension or MapServer will not recognize them. Include files can
have any extension you want, however.
See Also:
INCLUDE
You can also send a HTTP request directly to the MapServer CGI program without passing any configuration vari-
ables (e.g. http://your.domain.name/cgi-bin/ms4/mapserv.exe). If you receive the message, ‘No query information to
decode. QUERY_STRING not set.’, your installation is working.
Download the MapServer Demo. UnZip it and follow the directions in ReadMe.txt. You will need to move the demo
files to their appropriate locations on your HTTP server, and modify the Map File and html pages to reflect the paths
and URLs of your server. Next, point your browser to init.html and hit the ‘initialize button’. If you get errors, verify
that you have correctly modified the demo files.
Now that you have a working MapServer demo, you can use the demo to display your own data. Add new LAYERs
to your Map file that refer to your own geographic data layers. (You will probably want to delete the existing layers or
set their status to OFF.)
Unless you are adding layers that fall within the same geographic area as the demo, modify MAP EXTENT to match
the extent of your data. To determine the extent of your data, you can use ogrinfo. If you have access to a GIS, you
could use that as well. The MAP EXTENT needs to be in the units of your output projection.
If you add geographic data layers of different projections, you will need to modify your Map File to add a PROJEC-
TION block to the MAP (output projection ) and each of the LAYER (existing layer projection).
MapServer supports several data input formats ‘natively’, and many more if it is compiled with the open source
libraries GDAL and OGR.
Vector data includes features made up of points, lines, and polygons. MapServer supports ESRI shapefiles by de-
fault, but it can be compiled to support spatially enabled databases such as PostgreSQL-PostGIS, Geography Markup
Language (GML), MapInfo, delimited text files, and more formats with OGR.
See the Vector Data reference for examples on how to add different geographic data sources to your MapServer project.
Raster data is image or grid data. By default, MapServer supports Tiff/GeoTiff, and EPPL7. With GDAL, it supports
GRASS, Jpeg2000, ArcInfo Grids, and more formats. If you do compile MapServer with GDAL, which includes tiff
support, do not compile with native tiff support, as this will cause a conflict. More specific information can be found
in the Raster Data reference.
2.5.4 Projections
Because the earth is round and your monitor (or paper map) is flat, distortions will occur when you display geographic
data in a two-dimensional image. Projections allow you to represent geographic data on a flat surface. In doing
so, some of the original properties (e.g. area, direction, distance, scale or conformity)of the data will be distorted.
Different projections excel at accurately portraying different properties. A good primer on map projections can be
found at the University of Colorado.
With MapServer, if you keep all of your spatial data sets in the same projection (or unprojected Latitude and Longi-
tude), you do not need to include any projection info in your Map File. In building your first MapServer application,
this simplification is recommended.
On-the-fly projection can be accomplished when MapServer is compiled with Proj.4 support. Instructions on how to
enable Proj.4 support on Windows can be found on the Wiki.
There are two primary ways to query spatial data. Both methods return data through the use of templates and CGI
variable replacement. A QUERYMAP can be used to map the results of the query.
To be queryable, each mapfile LAYER must have a TEMPLATE defined, or each CLASS within the LAYER must have a
TEMPLATE defined. More information about the CGI variables used to define queries can be found in the MapServer
CGI Reference.
The user selects features based on data associated with that feature. ‘Show me all of the lakes where depth is greater
than 100 feet’, with ‘depth’ being a field in the shapefile .dbf or the spatial database. Attribute queries are accomplished
by passing query definition information to MapServer in the URL (or form post). Mode=itemquery returns a single
result, and mode=itemnquery returns multiple result sets.
The request must also include a QLAYER, which identifies the layer to be queried, and a QSTRING which contains
the query string. Optionally, QITEM, can be used in conjunction with QSTRING to define the field to be queried.
Attribute queries only apply within the EXTENT set in the map file.
The user selects features based on a click on the map or a user-defined selection box. Again the request is passed
through a URL or form post. By setting mode=QUERY, a user click will return the one closest feature. In
mode=NQUERY, all features found by a map click or user-defined selection box are returned. Additional query
options can be found in the CGI.
2.6.4 Interfaces
Data organization is at least as important as hardware configuration in optimizing a MapServer application for perfor-
mance. MapServer is quite efficient at what it does, but by reducing the amount of processing that it needs to do at the
time of a user request, you can greatly increase performance. Here are a few rules:
• Index Your data - By creating spatial indexes for your shapefiles using shptree. Spatial indexes should also be
created for spatially aware databases such as PostGIS and Oracle Spatial.
• Tile Your Data - Ideally, your data will be ‘sliced up’ into pieces about the size in which it will be displayed.
There is unnecessary overhead to searching through a large shapefile or image of which you are only going
to display a small area. By breaking the data up into tiles and creating a tile index, MapServer only needs to
open up and search the data files of interest. Shapefile data can be broken into smaller tiles and then a tileindex
shapefile can be created using the tile4ms utility. A tileindex shapefile for raster files can also be created.
• Pre-Classify Your Data - MapServer allows for the use of quite complex EXPRESSIONs to classify data.
However, using logical and regular expressions is more resource intensive than string comparisons. To increase
efficiency, you can divide your data into classes ahead of time, create a field to use as the CLASSITEM and
populate it with a simple value that identifies the class, such as 1,2,3, or 4 for a four class data set. You can then
do a simple string comparison for the class EXPRESSION.
• Pre-Process Your Images - Do resource intensive processing up front. See the Raster Data reference for more
info.
• Generalize for Overview - create a more simple, generalized data layer to display at small scales, and then
use scale-dependent layers utilizing LAYER MINSCALE and LAYER MAXSCALE to show more detailed data
layers as the user zooms in. This same concept applies to images.
See Also:
Optimization
2.7.1 Documentation
Register and post questions to the MapServer Users listserv. Questions to the list are usually answered quickly and
often by the developers themselves. A few things to remember:
1. Search the archives for your answer first, people get tired of answering the same questions over and over.
2. Provide version and configuration information for your MapServer installation, and relevant snippets of your
map and template files.
3. Always post your responses back to the whole list, as opposed to just the person who replied to your question.
2.7.3 IRC
MapServer users and developers can be found on Internet Relay Chat. The channel is #mapserver on irc.freenode.net.
2.7.4 Gallery
2.7.5 Tutorial
Perry Nacionales built a great Tutorial on how to build a MapServer application. You are invited to extend the collec-
tion of examples if you see cases that are missing.
Download the MapServer Test Suite for a demonstration of some MapServer functionality.
2.7.7 Books
Web Mapping Illustrated , a new book by Tyler Mitchell that describes well and provides real-world examples for the
use of Web mapping concepts, Open Source GIS software, MapServer, Web services, and PostGIS.
Mapping Hacks , by Schuyler Erle, Rich Gibson, and Jo Walsh, creatively demonstrates digital mapping tools and
concepts. MapServer only appears in a handful of the 100 hacks, but many more are useful for concepts and inspiration.
Beginning MapServer: Opensource GIS Development , by Bill Kropla, is a new book focusing on MapServer. So new,
I haven’t seen it yet. According to the publisher, it covers installation and configuration, basic MapServer topics and
features, incorporation of dynamic data, advanced topics, MapScript, and the creation of an actual application.
MapServer Tutorial
While some users can go through this tutorial in one day, those who work on each example in detail can probably
expect to finish in one week.
The dataset used in this tutorial was taken from the U.S. Department of the Interior’s National Atlas of the United
States. You can visit their web site at http://www.nationalatlas.gov. The dataset was clipped to the upper great lakes
region (Minnesota, Michigan, and Wisconsin) to reduce storage size. Additional raster images were added courtesy
of the TerraSIP project at the University of Minnesota. When using this tutorial, you are encouraged to use your own
dataset.
Like MapServer itself, this tutorial is open and customizable to anyone. This was done in the hope that someone (or
some folks) will help design and develop it further.
Download the data (and all html files) for this tutorial at http://demo.mapserver.org/tutorial/tutorial.zip.
25
MapServer Documentation, Release 6.0
3.4.1 Paths
This tutorial was created in Linux/UNIX but should work with minimal changes on Windows platform. The main
differences are the paths in the map files. Windows users need to specify the drive letter of the hard disk where their
tutorial files reside. Here’s an example:
A UNIX map file might include a parameter like this:
SHAPEPATH "/data/projects/tutorial/data"
or:
SHAPEPATH "C:\data\projects\tutorial\data".
Notice that either slash or backslash works in Windows. The usual backslash may work well for you if you want to
make a distinction between virtual (as in URLs or web addresses) and local paths in your map file. However, if you
plan to move your application to UNIX at some point, you’ll have the tedious task of switching all backslashes to
slashes.
While we’re on the subject of paths, keep in mind that paths in mapfiles are typically relative to the system’s root
directory: the slash (“/”) in UNIX or some drive letter (“C:”) in Windows. This is true except when specifi-
cally asked to enter a URL or when referencing a URL. When working with HTML template files, paths are rel-
ative to the web server’s root directory. i.e., “/tutorial/” is relative to “http://demo.mapserver.org/“. Please read
http://www.alistapart.com/articles/slashforward/ for a few insights on URLs.
3.4.2 Executable
Another issue is that UNIX executable files don’t require a .EXE or .COM extensions, but they do in Windows. If
you are using Windows, append .exe to all instances of “/cgi-bin/mapserv” or “/cgi-bin/mapserv50” to make it “/cgi-
bin/mapserv.exe” or “/cgi-bin/mapserv50.exe”.
Other documentation exist to give you better understanding of the many customizations MapServer offer. Please visit
the MapServer documentation page at http://www.mapserver.org. There you will find several HOWTO documents,
from getting started to using MapScript, a scripting interface for MapServer.
• Take a shapefile. Any shapefile. We can use MapServer to display that shapefile on a web browser. Look...
So far we have only looked at the mapfile when creating maps. In creating web mapping applications, it is usually
our intention to make maps that can be changed by the user (of the application) interactively. That is, a user should be
able to change the content of (or the information in) the map. To accomplish this interactivity, we use the MapServer
HTML templates.
A MapServer HTML template is essentially an HTML file with a few MapServer specific tags. These tags are the
MapServer CGI variables and are enclosed in square brackets “[]”. When the MapServer CGI program processes an
application, it first parses the query string and the mapfile, and produces the necessary output. Some of this output
will need to be written to the HTML template file which you would have to also specify in the mapfile using the web
template keyword (or in a separate HTML initialization file). The CGI program will replace all the variables in the
HTML template with the proper value before sending it back to the web browser. If you are to directly view an HTML
template on a web browser, there won’t be any maps rendered and you will instead get blank images and other junk.
Variables
MapServer provides several variables for web mapping: the “img” variable which you’ve seen in Example 1.9 is but
one example. There area few core CGI variables originally designed as part of the mapping interface but practically
all the mapfile parameters can be defined as variables. The definitive reference to the CGI variables can be found at
here.
We can also define our own variables, which MapServer will pass along to our application. For example, we can create
a variable called “root” to represent the root directory of this tutorial, the value for “root” will then be “/tutorial”.
When the MapServer CGI program processes our HTML template, it will replace every instance of he “[root]” tag
with “/tutorial”. You will see this in action for each of the following examples.
3.7.2 Examples
To learn more about query and HTML templates with MapServer, see examples 3.1 to 3.4 in the Tutorial Viewer.
To learn more about advanced navigation such as pan and rubber-band zoom with Javascript and MapServer CGI, see
examples 4.1 to 4.4 in the Tutorial Viewer.
Begin tutorial
Installation
Table of Contents
• Compiling on Unix
– Introduction
– Obtaining the necessary software
– libgd
– Anti-Grain Geometry Support
– OGC Support
– Spatial Warehousing
– Compiling
– Installation
4.1.1 Introduction
The University of Minnesota’s MapServer is an open-source and freely available map rendering engine for the web.
Due to its open-source nature, it can be compiled on a wide variety of platforms and operating systems. We will focus
on how to obtain, compile and install MapServer on UNIX-like platforms.
You might also check the MapServerCompilation wiki page for additional information.
31
MapServer Documentation, Release 6.0
You can obtain the MapServer source code as well as the demo package from the Download section.
You can also get the latest MapServer source code from Subversion.
• libpng: libpng should be on your system by default. 1.2.12 is the current release with security patches, although
versions all the way back to 1.2.7 should work.
• freetype: Version 2.x or above is required by GD.
• GD: libgd is used by MapServer for rendering images. Version 2.0.28 or greater required. Version 2.0.29 or
later is required to use curved (following) labels, and version 2.0.34 is required for antialiasing (1 pixel wide
lines/outlines).
• zlib: Zlib should be on your system by default. 1.2.1 is the current release with security patches.
• libproj: libproj provides projection support for MapServer. Version 4.4.6 or greater is required.
• libcurl: libcurl is the foundation of OGC (WFS/WMS/WCS) client and server support. Version 7.10 or greater
is required
• OGR: OGR provides access to at least 18 different vector formats.
• GDAL: GDAL provides access to at least 42 different raster formats.
• AGG: AGG (Anti-Grain Geometry) is an optional dependency to enable high quality antialiased output for
vector data. Currently versions 2.4 and 2.5 are identical featurewise, and only vary in their licence (2.4 is BSD,
2.5 is GPL)
• libtiff: libtiff provides TIFF (Tagged Image File Format) reading support to MapServer.
• libgeotiff libgeotiff provides support to read GeoTIFF files (TIFF files with geographic referencing).
• libjpeg: libjpeg allows MapServer to render images in JPEG format. A sufficient version should be installed by
default on your system. Version 6b is the current version and dates back to 1998.
• GEOS: GEOS allows MapServer to do spatial predicate and algebra operations (within, touches, etc & union,
difference, intersection). Requires version 4.10 or greater.
• libxml: libxml is required to use OGC SOS support in MapServer (versions 4.10 and greater).
• SDE Client Library: The client libraries for your platform should be part of the ArcSDE media kit. They are not
publicly available for download.
• Oracle Spatial OCI: The client libraries for your platform are available for download from Oracle’s website.
Ideally, your client library matches the database you are querying from, but this is not a hard requirement.
• libpq: libpq is required to support the use of PostGIS geometries within the PostgreSQL database. Ideally, your
client library matches the database you are querying from.
• pdflib (lite): PDFlib Lite is the Open Source version of PDFlib that allows MapServer to produce PDF output.
Version 4.0.3 or greater is required.
32 Chapter 4. Installation
MapServer Documentation, Release 6.0
• libming: libming provides Macromedia Flash output to MapServer. Version 0.2a is required. Later versions are
not known to work.
4.1.3 libgd
There are a number of issues that you should be aware of when using GD in combination with MapServer.
MapServer aggressively takes advantage of new features and bug fixes in the latest versions of libgd. The minimum
required version to run MapServer is 2.0.29. Upgrading to at least 2.0.34 is advised as it includes an important bug
fix for antialiased lines. Configure should detect which version of libgd you have installed, but you can quickly check
yourself by issuing the following command:
gdlib-config --version
libiconv
If you intend to use international character sets, your version of libgd must be compiled against the GNU iconv
libraries. If you are using a pre-packaged version, it is very likely that this is the case. To check for yourself, issue the
following command and look for ‘-liconv’ in the output:
gdlib-config --libs
Pre-packaged/system libraries
If you intend to use your system’s libgd, ensure that you have the development package also installed so MapServer
can find and use the appropriate headers.
MacOSX
FreeType support
The GD you compile MapServer against MUST be compiled against the FreeType library in order to use TrueType
fonts. MapServer no longer uses it’s own interface to FreeType, using it through GD instead.
When you run your “configure” script, look for the following output:
using GD ( -DUSE_GD_GIF -DUSE_GD_PNG -DUSE_GD_JPEG
-DUSE_GD_WBMP -DUSE_GD_TTF -DGD_HAS_GDIMAGEGIFPTR) from system libs.
If your GD is built against FreeType, you will see either “-DUSE_GD_TTF” (Or “-DUSE_GD_FT” for Freetype 2.x)
part. If it’s missing, you will need to recompile your GD to make sure you include FreeType support. See the GD
documentation for more information.
Also note that the configure script looks for the FreeType library separately as well, generating output looking some-
what like this:
Even though you have FreeType installed on your system and the configure script finds it, does NOT mean you will
have TrueType font support. GD MUST be compiled against FreeType either way.
Versions of libgd earlier than 2.0.34 contain a one very significant bug and will always cause a segfault if you attempt
to do one pixel wide antialiasing. You can manually patch older gd’s, or better yet upgrade to at least GD 2.0.34.
In gd.c, function gdImageSetAAPixelColor() change:
int dr,dg,db,p,r,g,b;
p = gdImageGetPixel(im,x,y);
to
int dr,dg,db,p,r,g,b;
if (!gdImageBoundsSafeMacro (im, x, y)) return;
p = gdImageGetPixel(im,x,y);
More detail about this patch (if you need any) was described by Steve Lime in a post to mapserver-users.
ANGLE FOLLOW, a new feature that allows MapServer to draw curved labels about a linear feature like a road,
requires libgd 2.0.29 and TrueType font support. Configure should autodetect if you have a sufficient libgd and
TrueType support to be able to use this feature.
Since version 5.0 MapServer supports the AGG rendering backend. Download the 2.4 tarball from the antigrain
website and just type make in the root directory. If you intend on using mapscript, you must beforehand tweak the agg
makefile to add -fPIC to the compiler options.
MapServer provides support for many OGC specifications. At 4.2.3, it provides support for WMS (Web Mapping
Service), SLD (Styled Layer Descriptor), WFS (Web Feature Service), and experimental support for WCS (Web
Coverage Service).
WMS support
WMS Server
Support for this specification is automatically enabled when you include PROJ.4 support. (–with-proj) You can check
this yourself by looking for the following in your “configure” output:
checking whether we should include WMS support...
OGC WMS compatibility enabled (-DUSE_WMS).
34 Chapter 4. Installation
MapServer Documentation, Release 6.0
If, for some reason you DON’T want WMS support, you can force it off by passing “–without-wms” to your configure
script.
More information on using this feature is available in the WMS Server HOWTO available on the MapServer website.
WMS Client
Cascading is also supported. This allows mapserver to transparently fetch remote layers over WMS, basically acting
like a client, and combine them with other layers to generate the final map.
In order to enable this feature, you will need to pass the “–with-wmsclient” option to the configure script. MapServer
will automatically look for libcurl, which is also required.
To verify that the WMS Client feature is enabled, check the output from the configure script:
checking whether we should include WMS Client Connections support...
OGC WMS Client Connections enabled (-DUSE_WMS_LYR).
Note that this feature is disabled by default, you have to specifically request it.
More information on using this feature is available in the WMS Client HOWTO available on the MapServer website.
WFS support
WFS Server
Support for this specification is enabled by passing the configure script the “–with-wfs” option. OGR and PROJ.4
support is required.
You can check this yourself by looking for the following in your “configure” output:
checking whether we should include WFS Server support...
OGC WFS Server support enabled (-DUSE_WFS_SVR).
Note that this feature is disabled by default, you have to specifically request it.
More information on using this feature is available in the WFS Server HOWTO available on the MapServer website.
WFS Client
MapServer can also act as a WFS client. This effectively means that MapServer reads it’s data from a remote server’s
WFS output and renders it into a map, just like it would when reading data from a shapefile.
In order to enable this feature, you will need to make sure you include OGR (Built with Xerces support) and PROJ.4
support, and pass the “–with-wfsclient” option to your configure script. MapServer will automatically look for libcurl,
which is also required.
To verify that the WFS Client feature is enabled, check the output from the configure script:
checking whether we should include WFS Client Connections support...
OGC WFS Client Connections enabled (-DUSE_WFS_LYR).
Note that this feature is disabled by default, you have to specifically request it.
More information on using this feature is available in the WFS Client HOWTO available on the MapServer website.
MapServer can use a wide variety of sources of data input. One of the solutions growing in popularity is to use spatially
enabled databases to store data, and to use them directly to draw maps for the web.
Here you will find out how to enable mapserver to talk to one of these products. Please refer to the MapFile reference
for more details on how to use these. This section only details how to compile MapServer for their use.
PostGIS
PostGIS adds support for geographic objects to the PostgreSQL object-relational database. In effect, PostGIS “spa-
tially enables” the PostgreSQL server, allowing it to be used as a backend spatial database for geographic information
systems (GIS), much like ESRI’s SDE or Oracle’s Spatial extension. PostGIS is included in many distributions’
packaging system, but you can also roll your own if needed.
MapServer can use PostGIS as a data source. In order to do so simply use “–with-postgis” when running your configure
script.
--with-postgis=/usr/local/pgsql/bin/pg_config
ArcSDE
MapServer allows you to use SDE as a data source both for geometry and attributes. In order to achieve this, you must
have the SDE client librairies at your disposition, and have them installed on the machine running MapServer.
In order to enable SDE support in MapServer, you have to compile it with two options specified:
--with-sde=/opt/sdeexe90
--with-sde-version=90
Oracle Spatial
Oracle’s Spatial Warehousing cartridge is also supported by MapServer. In order to connect to it, you will need to
compile MapServer against the Oracle libraries by passing the “–with-oraclespatial” argument to your configure script.
You will very likely need an ORACLE_HOME environment variable set to have it configure things correctly.
--with-oraclespatial=/opt/oracle
4.1.7 Compiling
First prepare the ground by making sure all of your required and/or recommended libraries are installed before at-
tempting to compile MapServer. This will make your life much less complicated ;). Here is the order that I usually
use:
1. Compile GD. This often means acquiring libjpeg, libpng, zlib, and freetype before actually compiling the library.
You shouldn’t have too much trouble finding binaries of the libraries that GD requires, and often, they will
already be installed with your system. On unix, I’ve had very little luck finding pre-compiled binaries of the
required GD library. See libgd section for notes about patching libgd if you plan to use antialiasing.
2. Compile GDAL/OGR. Describing how to compile GDAL/OGR is beyond the scope of this document. If you
have requirements for lots of different formats, make sure to install those libraries first. I often find that building
up a GDAL/OGR library often takes as long as compiling MapServer itself!
3. Compile Proj.4. Proj.4 is a straight-forward configure/make/make install library.
36 Chapter 4. Installation
MapServer Documentation, Release 6.0
7. Configure your environment using “configure”. I often place my configure command in its own file and changes
its mode to be executable (+x) to save typing and have a record of how MapServer was configured.
./configure --with-sde=/usr/sde/sdeexe90 \
--with-sde-version=90 \
--with-ogr=/usr/local/bin/gdal-config \
--with-gdal=/usr/local/bin/gdal-config \
--with-httpd=/usr/sbin/httpd \
--with-wfsclient \
--with-wmsclient \
--enable-debug \
--with-curl-config=/usr/bin/curl-config \
--with-proj=/usr/local \
--with-tiff \
--with-gd=/usr/local/ \
--with-jpeg \
--with-freetype=/usr/ \
--with-oraclespatial=/usr/oracle \
--with-threads \
--with-wcs \
--with-postgis=/usr/local/database/bin/pg_config \
--with-libiconv=/usr \ # new in 4.8
--with-geos=/usr/local/bin/geos-config \ # new in 4.8
--with-libiconv=/usr \ # new in 4.8
--with-xml2-config=/usr/bin/xml2-config \ # new in 4.10
--with-sos \ # new in 4.10
--with-agg=/path/to/agg-2.4
8. Now that you have configured your build options and selected all the libraries you wish mapserver to use, you’re
ready to compile the source code into an executable.
This is actually quite simple, just execute “make”:
[user@host mapserver]$ make
9. There is no make install step in the installation of MapServer. The output of the compilation of MapServer is a
binary executable that you can use in a CGI execution environment.
To make sure all went well, look for the file called mapserv
[user@host mapserver]$ ls -al mapserv
-rwxr-xr-x 1 user user 351177 Dec 21 11:38 mapserv
The message above is perfectly normal, and means exactly what it says. If you get anything else, something
went terribly wrong.
4.1.8 Installation
MapServer binary
The MapServer program itself consists of only one file, the “mapserv” binary executable. This is a CGI executable,
meant to be called and run by your web server.
In this section, we will assume you are running Apache under its default directory structure in /usr/local/apache. You
may need to have privileges to edit your httpd.conf (the main apache configuration file), or have someone (such as
your webmaster) help you with the configuration details.
The main goal is to get the “mapserv” binary installed in a publicly accessible directory that is configured to run CGI
programs and scripts.
Under a default configuration, the CGI directory is “/usr/local/apache/cgi-bin” (RedHat users will use
“/home/httpd/cgi-bin”). Placing the mapserv file in this directory makes it accessible by the following URL:
“http://yourhostname.com/cgi-bin/mapserv“. When accessing this URL through your web client, you should expect
the following output if all has worked well: “No query information to decode. QUERY_STRING is set, but empty.”
If you get this message, you’re done installing MapServer.
Common problems
File permissions
The most common problem one is likely to encounter when attempting to install the binary are permissions issues:
• You do not have write permissions into your web server’s CGI Directory. Ask your webmaster to install the file
for you.
• The web server gives you a “403 Permission denied” error. Make sure the user the web server runs as (usually
“nobody”) has execute permission on the binary executable. Making the file world executable is perfectly fine
and safe:
[user@host cgi-bin]$ chmod o+x mapserv
Apache errors
You may receive a few different type of errors as well if your web server configuration isn’t right:
• 500 Internal server error: This is a fairly generic error message. All it basically tells you is that the web server
was unsuccessful in running the program. You will have to consult the web server’s error log to find out more,
and may need to enlist the help of your webmaster/system administrator.
The An Introduction to MapServer document provides excellent coverage of getting started with MapServer.
38 Chapter 4. Installation
MapServer Documentation, Release 6.0
Table of Contents
• Compiling on Win32
– Introduction
– Compiling
– Set up a Project Directory
– Download MapServer Source Code and Supporting Libraries
– The MapServer source code
– Set Compilation Options
– Compile the Libraries
– Compile MapServer
– Compiling MapServer with PostGIS support
– Common Compiling Errors
– Installation
– Other Helpful Information
– Acknowledgements
4.2.1 Introduction
This document provides a simple set of compilation procedures for MapServer on Win32 platforms.
If you’ve made it this far, chances are you already know about MapServer and are at least tempted to try compiling it
for yourself. Pre-compiled binaries for MapServer are available from a variety of sources. Refer to Windows. Building
MapServer for win32 platforms can be a daunting task, so if existing binaries are sufficient for your needs, it is strongly
advised that they be used in preference to trying to build everything from source.
However, there can be a variety of reasons to want to build MapServer from source on win32. Reasons include the
need to enable specific options, to build with alternate versions of support libraries (such as GDAL), the desire for
MapScript support not part of the core builds, the need to debug and fix bugs or even to implement new features in
MapServer. To make it easy for users and developers, I’ve made a list of steps to compile MapServer. Background
information is provided in each step, along with examples. Each example is a continuation of the previous one and in
the end will produce the MapServer DLL (libmap.dll), the CGI program (the mapserv.exe), and utility programs.
Warning: This document may refer to older library versions. You may want to try to use more recent library
versions for your build.
4.2.2 Compiling
If you are new to Windows programming, please follow this document carefully. The compilation steps are fairly
simple but I’ve added a few blurbs in each step to help you understand how MapServer compiles. For the more
experienced programmers, perhaps reading the README.Win32 that accompanies the MapServer source code would
be more useful. For those who are antsy, compiling MapServer involves download and unpacking the source codes,
editing the make files, and invoking Microsoft’s Visual C++ compiler from the command prompt. The resulting
mapserv.exe is the CGI program that installs in the cgi-bin directory of your web server.
For those who are willing to take the time, the compilation steps follow.
Before you start to compile MapServer, I recommend creating a directory called “projects” where you can put the
source code for MapServer and its supporting libraries. Since you will be working with DOS-style commands, you
might as well get used to the Windows command prompt. For Windows 95/98 users the command processor would be
called command.com. For Windows NT/2000/XP, it would be cmd.exe. So fire up the old command prompt and go to
the drive where you want to create the project directory.
Here is an example of how to create a directory called projects on the C: drive:
C:\Users> mkdir C:\Projects
To go to that directory:
C:\Users> cd \Projects
C:\Projects>
From the projects directory, you can extract the source codes for MapServer and its libraries. Now you’re ready to
download the source codes.
After creating a project directory, download the MapServer source code and the codes for the supporting libraries and
save the source code packages in the newly created “projects” directory. These source codes are usually packaged as
ZIP, or as UNIX TAR and GZIP files. You’ll need a software that can unzip these packages. 7-Zip is an example of
software that can handle these files.
Cygwin is a free, open-source software package which is a port of these tools on Windows. You can use the gzip and
tar utilities from this tool collection. Cygwin is available from http://www.cygwin.com.
In order to compile the MapServer CGI program, you must download a few required and optional libraries. At
its simplest configuration, MapServer only requires the GD (to provide the image output) and REGEX (to provide
regular expression support) libraries. This configuration allows the developer/data provider to use shapefiles as input
and, depending on the version of GD library used, GIF or PNG images as output. Additional libraries are needed for
input data in alternative formats. The libraries that work with MapServer are listed below.
The MapServer source code can be downloaded from the download page. If you’d like to get the current development
version of the software, following the nightly snapshot link under the Interim Builds title. The absolute latest copy of
the source code can be obtained from SVN; however, the SVN respository does not contain several important source
files (maplexer.c, mapparser.c and mapparser.h) normally generated on unix, so if possible, using a nightly snaphot is
substantially easier than working directly from Subversion.
Required Libraries
GD Library: MapServer uses the GD graphics library for rendering map images in GIF, PNG and JPEG format.
These map images are displayed in web browser clients using the MapServer CGI. The current official version
of GD is 2.0.33. The distributed makefiles are setup to use the prebuilt GD Win32 DLL binaries which include
40 Chapter 4. Installation
MapServer Documentation, Release 6.0
GD, libjpeg, libpng, libz, libgif and FreeType 2 all within one DLL. This package is generally listed as “Windows
DLL .zip” and the latest version is normally available at http://www.boutell.com/gd/http/gdwin32.zip.
Regex: Regex is the regular expression library used by MapServer. It can be downloaded at http://ftp.gnu.org/old-
gnu/regex/regex-0.12.tar.gz
Optional Libraries
JPEG library: This library is required by GD to render JPEG images, if building GD from source. You may down-
load this library at http://www.ijg.org/files/jpegsrc.v6b.tar.gz
PNG library: This library is required by GD to render PNG images, if building GD from source. You may download
this library at http://sourceforge.net/projects/libpng/
Zlib: This library is required by libpng to provide graphics compression support. It can be downloaded along with
the PNG library, or at http://www.gzip.org/zlib.zip .
FreeType 2: FreeType provides TrueType support in MapServer via GD. We only need to build FreeType seperately
if building GD from source. It can be downloaded at http://gnuwin32.sourceforge.net/packages/freetype.htm .
PROJ.4: Proj.4 provides on-the-fly projection support to MapServer. Users whose data are in different projection
systems can use this library to reproject into a common projection. It is also required for WMS, WFS or WCS
services.
GDAL/OGR: The GDAL/OGR library allows MapServer to read a variety of geospatial raster formats (GDAL) and
vector formats (OGR). It can be downloaded at http://www.gdal.org/.
ArcSDE: ArcSDE is an ESRI proprietary spatial database engine. Most users will not have access to it but if you
have ArcSDE license, you can use its libraries to give MapServer access to SDE databases.
EPPL7: This library allows MapServer to read EPPL7 datasets, as well as the older Erdas LAN/GIS files. This library
is set as a default library in MapServer so there’s no special source code to download.
Now that you have reviewed the libraries that provide support to MapServer, it is time to decide which ones to compile
and use. We will work with the pre-built GD distributed on Boutell.com with PNG, GIF, JPEG, and FreeType “built
in”. If you want to provide OGC Web Services (ie. WMS, WFS) or want to perform on the fly reprojection then the
PROJ.4 library will be needed. If you need additional raster and vector data sources consider including GDAL/OGR
support. GDAL is also required for WCS service.
Our example calls for the required libraries and on-the-fly projection support so we need to download GD, regex, and
Proj.4 libraries. Go ahead and get those libraries.
MapServer, like many of it’s support libraries, comes with a Visual C++ makefile called Makefile.vc. It includes the
file nmake.opt which contains many of the site specific definitions. We will only need to edit the nmake.opt file to
configure the build for our local site options, and support libraries. The Makefile.vc, and nmake.opt template file have
been provided by Assefa Yewondwossen, and the DM Solutions folks.
As of MapServer 4.4, the default MapServer build options only include GD, and regex. MapServer is built using the
/MD option (which means MSVCRT.DLL should be used), so if any support libraries are being built statically (rather
than as DLLs) we need to use /MD when building them as well. By default modern PROJ.4 builds use /MD so we
should be able to use the default PROJ.4 build without tweaking.
The example will compile with the GDWin32 pre-built DLL as well as regex-0.12, and PROJ.4. The PROJ.4 support
will ensure we can enable MapServer OGC-WMS compatibility. Use notepad or another text editor to open the
nmake.opt file and make the following changes.
Comments
Use the pound sign ( # ) to comment out the lines that you want to disable, or remove the pound sign to enable an
option for NMAKE.
A. Enable PROJ.4 support, and update the path to the PROJ.4 directory. Uncomment the PROJ= line, and the
PROJ_DIR= line as follows, and update the PROJ_DIR path to point to your PROJ build.
# Reprojecting.
# If you would like mapserver to be able to reproject data from one
# geographic projection to another, uncomment the following flag
# Proj.4 distribution (cartographic projection routines). PROJ.4 is
# also required for all OGC services (WMS, WFS, and WCS).
#
# For PROJ_DIR use full path to Proj.4 distribution
PROJ=-DUSE_PROJ -DUSE_PROJ_API_H
PROJ_DIR=c:\projects\proj-4.4.9
If you look down later in the file, you can see that once PROJ is enabled, MapServer will be linked with proj_i.lib, the
PROJ.4 stub library, meaning that MapServer will be using the PROJ.DLL as opposed to statically linking in PROJ.4.
2. Uncomment the WMS option.
# Use this flag to compile with WMS Server support.
# To find out more about the OpenGIS Web Map Server Specification go to
# http://www.opengis.org/
WMS=-DUSE_WMS_SVR
3. Update to use GD. Here’s what it should look like in our example.
GD_DIR=c:/projects/gdwin32
GD_LIB=$(GD_DIR)/bgd.lib
Note: As distributed the GDWin32 binary build does not include the bgd.lib stub library. It is necessary to run the
makemsvcimport.bat script in the gdwin32 directory first.
D. Make sure the regex path is set correctly. In order for the “delete” command in the “nmake /f makefile.vc clean”
target to work properly it is necessary to use backslashes in the REGEX_DIR definition.
# REGEX Libary
#
# VC++ does not include the REGEX library... so we must provide our one.
# The following definitions will try to build GNU regex-0.12 located in the
# regex-0.12 sub-directory.
# If it was not included in the source distribution, then you can get it from:
# ftp://ftp.gnu.org/pub/gnu/regex/regex-0.12.tar.gz
# Provide the full path to the REGEX project directory
# You do not need this library if you are compiling for PHP mapscript.
# In that case the PHP regex library will be used instead
!IFNDEF PHP
REGEX_DIR=c:\projects\regex-0.12
!ENDIF
42 Chapter 4. Installation
MapServer Documentation, Release 6.0
Before compiling MapServer, you must first compile its supporting libraries. How this is done varies for each library.
For the PROJ.4 library a nmake /f makefile.vc command in the proj-4.4.9src directory should be sufficient. The
regex-0.12 code is actually built by the MapServer build process, so you don’t need to do anything there.
Compiling libcurl
This creates a static library, libcurl.lib, to which you compile against. Versions newer than version 7.10.x should be
compiled as dynamic library. This is accomplished using the command:
nmake /f makefile.vc6 CFG=release-dll
You will then need to edit MapServer’s nmake.opt to replace the CURL_LIB variable with this line:
CURL_LIB = $(CURL_DIR)/lib/libcurl_imp.lib
Once you have compiled the supporting libraries successfully, you are ready to take the final compilation step. If
you have not already done so, open a command prompt and set the VC++ environment variables by running the
vcvars32.bat usually located in C:Program FilesMicrosoft Visual StudioVC98binvcvars32.bat.
C:\Users> cd \projects\mapserver
C:\Projects\mapserver&> C:\Program Files\Microsoft Visual Studio\VC98\Bin\vcvars32.bat"
C:\Projects\mapserver>
Now issue the command: nmake /f Makefile.vc and wait for it to finish compiling. If it compiles successfully, you
should get mapserver.lib, libmap.dll, mapserv.exe, and other .EXE files. That’s it for the compilation process. If you
run into problems, read section 4 about compiling errors. You can also ask for help from the helpful folks in the
MapServer-dev e-mail list.
To compile PostGIS support into MapServer, here’s what you need to do:
1. download the PostgreSQL 8.0.1 (or later) source from: ftp://ftp.heanet.ie/pub/postgresql/source/
2. I extracted them to C:projectspostgresql-8.0.1
3. download the Microsoft Platform SDK otherwise you get link errors on shfolder.lib.
4. compile libpq under C:projectspostgresql-8.0.1srcinterfaceslibpq using the win32.mak makefile
5. copy everything from C:projectspostgresql-8.0.1srcinterfaceslibpqrelease to C:projectspostgresql-
8.0.1srcinterfaceslibpq as the MapServer makefile will try to find it there
6. Define the following in the nmake.opt for MapServer: POSTGIS =-DUSE_POSTGIS POSTGIS_DIR
=c:/projects/postgresql-8.0.1/src
7. nmake /f makefile.vc
8. don’t forget to copy libpq.dll (from C:projectspostgresql-8.0.1srcinterfaceslibpqrelease) into a location where
MapServer can find it.
Following are a few common errors you may encounter while trying to build MapServer.
• Visual C++ Tools Not Properly Initialized.
C:\projects\mapserver> nmake -f /makefile.vc
’nmake’ is not recognized as an internal or external command,
operable program or batch file.
This occurs if you have not properly defined the path and other environment variables required to use MS
VisualC++ from the command shell. Invoke the VCVARS32.BAT script, usually with the command C:Program
FilesMicrosoft Visual StudioVC98binvcvars32.bat or something similar if visual studio was installed in an
alternate location. To test if VC++ is available, just type “nmake” or “cl” in the command shell and ensure it is
found.
• Regex Build Problems.
regex.obj : error LNK2001: unresolved external symbol _printchar
libmap.dll : fatal error LNK1120: 1 unresolved externals
NMAKE : fatal error U1077: ’link’ : return code ’0x460’
Stop.
This occurs if you use the stock regex-0.12 we referenced. I work around this by commenting out the “extern”
statement for the printchar() function, and replacing it with a stub implementation in regex-0.12regex.c.
//extern void printchar ();
void printchar( int i ) {}
If you are using the pre-built GD binaries, you still need to run the makemsvcimport.bat script in the gdwin32
directory to create a VC++ compatible stub library (bgd.lib).
4.2.11 Installation
The file we are most interested in is mapserv.exe. The other executable files are the MapServer utility programs.
See Also:
MapServer Utilities
to learn more about these utilities.
To test that the CGI program is working, type mapserv.exe at the command prompt. You should see the following
message:
This script can only be used to decode form results and
should be initiated as a CGI process via a httpd server.
44 Chapter 4. Installation
MapServer Documentation, Release 6.0
You may instead get a popup indicating that a DLL (such as bgd.dll) is missing. You will need to copy all the required
DLLs (ie. bgd.dll, and proj.dll) to the same directory as the mapserv.exe program.
Now type mapserv -v at the command prompt to get this message:
MapServer version 4.4.0-beta3 OUTPUT=GIF OUTPUT=PNG OUTPUT=JPEG OUTPUT=WBMP
SUPPORTS=PROJ SUPPORTS=FREETYPE SUPPORTS=WMS_SERVER INPUT=SHAPEFILE
DEBUG=MSDEBUG
This tells us what data formats and other options are supported by mapserv.exe. Assuming you have your web server
set up, copy mapserv.exe, libmap.dll, bgd.dll, proj.dll and any other required DLLs to the cgi-bin directory.
You are now ready to download the demo application and try out your own MapServer CGI program. If you wish,
you can also create a directory to store the utility programs. I’d suggest making a subdirectory called “bin” under
the directory “projects” and copy the executables to that subdirectory. You might find these programs useful as you
develop MapServer applications.
The MapServer Unix Compilation and Installation HOWTO has good descriptions of some MapServer compilation
options and library issues. I will write more about those options and issues on the next revision of this HOWTO.
The README documents of each of the supporting libraries provide compilation instructions for Windows.
The MapServer User community has a collective knowledge of the nuances of MapServer compilation. Seek their
advice wisely.
4.2.13 Acknowledgements
Thanks to Assefa Yewondwossen for providing the Makefile.vc. I would not have been able to write this HOWTO
without that file.
Thanks to Bart van den Eijnden for the libcurl and PostGIS compilation info.
Thanks to the Steve Lime for developing MapServer and to the many developers who contribute time and effort in
order to keep the MapServer project successful.
Table of Contents
• PHP MapScript Installation
– Introduction
– Obtaining, Compiling, and Installing PHP and the PHP/MapScript Module
– FAQ / Common Problems
4.3.1 Introduction
The PHP/MapScript module is a PHP dynamically loadable module that makes MapServer’s MapScript functions and
classes available in a PHP environment.
The original version of MapScript (in Perl) uses SWIG, but since SWIG does not support the PHP language, the
module has to be maintained separately and may not always be in sync with the Perl version.
The PHP module was developed by DM Solutions Group and is currently maintained by Mapgears.
This document assumes that you are already familiar with certain aspects of your operating system:
• For Unix/Linux users, a familiarity with the build environment, notably make.
• For Windows users, some compilation skills if you don’t have ready access to a pre-compiled installation and
need to compile your own copy of MapServer with the PHP/MapScript module.
PHP MapScript was originally developed for PHP-3.0.14 but after MapServer 3.5 support for PHP3 has been dropped
and as of the last update of this document, PHP 4.3.11 or more recent was required (PHP5 is well supported).
The best combinations of MapScript and PHP versions are:
• MapScript 4.10 with PHP 5.2.1 and up
• MapScript 4.10 with PHP 4.4.6 and up
• For a list of all classes, properties, and methods available in the module see the php reference document.
• More information on the PHP/MapScript module can be found on the PHP/MapScript page on MapTools.org.
• The MapServer Wiki also has PHP/MapScript build and installation notes and some php code snippets.
• Questions regarding the module should be forwarded to the MapServer mailing list.
4.3.2 Obtaining, Compiling, and Installing PHP and the PHP/MapScript Module
• The PHP source or the Win32 binaries can be obtained from the PHP web site.
• Once you have verified that PHP is installed and is running, you need to get the latest MapServer source and
compile MapServer and the PHP module.
Unix
• Check if you have PHP already installed (several Linux distributions have it built in).
• If not, see the PHP manual’s “Installation on Unix systems” section.
Windows
• MS4W (MapServer For Windows) is a package that contains Apache, PHP, and PHP/MapScript ready to use in
a simple zipfile. Several Open Source applications are also available for use in MS4W.
46 Chapter 4. Installation
MapServer Documentation, Release 6.0
• Windows users can follow steps in the Installing Apache, PHP and MySQL on Windows tutorial to install
Apache and PHP manually on their system.
• Window users running PWS/IIS can follow php.net’s howto for installing PHP for PWS/IIS 3, PWS 4 or newer,
and IIS 4 or newer.
Note: When setting up PHP on Windows, make sure that PHP is configured as a CGI and not as an Apache module
because php_mapscript.dll is not thread-safe and does not work as an Apache module (See the Example Steps of a Full
Windows Installation section of this document).
Installing PHP/MapScript
Simply copy the file php4_mapscript.dll to your PHP4 extensions directory (pathto/php/extensions)
Using phpinfo()
To verify that PHP and PHP/MapScript were installed properly, create a ‘.php’ file containing the following code and
try to access it through your web server:
<HTML>
<BODY>
<?php
if (PHP_OS == "WINNT" || PHP_OS == "WIN32")
{
dl("php_mapscript.dll");
}
else
{
dl("php_mapscript.so");
}
phpinfo();
?>
</BODY>
</HTML>
If PHP and PHP/MapScript were installed properly, several tables should be displayed on your page, and ‘MapScript’
should be listed in the ‘Extensions’ table.
In the ScriptAlias section of this file, add an alias for the PHP4 folder.
ScriptAlias /cgi-php4/ "pathto/apache/php4/"
In the AddType section of this file, add a type for php4 files.
AddType application/x-httpd-php4 .php
In the Action section of this file, add an action for the php.exe file.
Action application/x-httpd-php4 "/cgi-php4/php.exe"
5. Copy the file php4.ini-dist located in your Apache/php4 directory and paste it into your WindowsNT folder (eg.
c:/winnt), and then rename this file to php.ini in your WindowsNT folder.
48 Chapter 4. Installation
MapServer Documentation, Release 6.0
6. If you want specific extensions loaded by default, open the php.ini file in a text viewer and uncomment the
appropriate extension.
7. Place the file php_mapscript.dll into your Apache/php4/extensions folder.
Installation Using Microsoft’s IIS
(please see the IIS Setup for MapServer document for uptodate steps)
1. Install IIS if required (see the IIS 4.0 installation procedure).
2. Install PHP and PHP/MapScript (see above).
3. Open the Internet Service Manager (eg. C/WINNT/system32/inetsrv/inetmgr.exe).
4. Select the Default web site and create a virtual directory (right click, select New/Virtual directory). For this
example we will call the directory msapps.
5. In the Alias field enter msapps and click Next.
6. Enter the path to the root of your application (eg. “c:/msapps”) and click Next.
7. Set the directory permissions and click Finish.
8. Select the msapps virtual directory previously created and open the directory property sheets (by right clicking
and selecting properties) and then click on the Virtual directory tab.
9. Click on the Configuration button and then click the App Mapping tab.
10. Click Add and in the Executable box type: path/to/php4/php.exe %s %s. You MUST have the %s %s on the
end, PHP will not function properly if you fail to do this. In the Extension box, type the file name extension to
be associated with your PHP scripts. Usual extensions needed to be associated are phtml and php. You must
repeat this step for each extension.
11. Create a temp directory in Explorer to store MapServer created GIFs.
Note: This directory is specified in the IMAGEPATH parameter of the WEB Object in the Mapfile. For this
example we will call the temp directory ms_tmp (eg. C:/tmp/ms_tmp).
12. Open the Internet Service Manager again.
13. Select the Default web site and create a virtual directory called ms_tmp (right click, select New/Virtual direc-
tory). Set the path to the ms_tmp directory (eg. C:/tmp/ms_tmp) . The directory permissions should at least be
set to Read/Write Access.
Make sure you replace the php_mapscript.so with the name under which you installed it, it could be
php_mapscript_46.so on Unix, or php_mapscript_46.dll on Windows
You can then try the second test page mapserver/mapscript/php3/examples/test_draw_map.phtml.
This page simply opens a MapServer .map file and inserts its map, legend, and scalebar in an HTML
page. Modify the page to access one of your own MapServer .map files, and if you get the expected
result, then everything is probably working fine.
Q I try to display my .phtml or .php page in my browser but the page is shown as it would it
Notepad.
A The problem is that your PHP installation does not recognize “.phtml” as a PHP file extension. As-
suming you’re using PHP4 under Apache then you need to add the following line with the other
PHP-related AddType lines in the httpd.conf:
AddType application/x-httpd-php .phtml
For a more detailed explanation, see the Example Steps of a Full Windows Installation section of
this document.
Q I installed the PROJ.4, GDAL, or one of the support libraries on my system, it is recognized by
MapServer’s “configure” as a system lib but at runtime I get an error: “libproj.so.0: No such
file or directory”.
A You are probably running a RedHat Linux system if this happened to you. This happens because the
libraries install themselves under /usr/local/lib but this directory is not part of the runtime library
path by default on your system.
(I’m still surprised that “configure” picked proj.4 as a system lib since it’s not in the system’s lib
path...probably something magic in autoconf that we’ll have to look into)
There are a couple of possible solutions:
1. Add a “setenv LD_LIBRARY_PATH” to your httpd.conf to contain that directory
2. Edit /etc/ld.so.conf to add /usr/local/lib, and then run “/sbin/ldconfig”. This will permanently
add /usr/local/lib to your system’s runtime lib path.
50 Chapter 4. Installation
MapServer Documentation, Release 6.0
--with-proj=/usr/local --enable-runpath
and the /usr/local/lib directory will be hardcoded in the exe and .so files
I (Daniel Morissette) personally prefer option #2 because it is permanent and applies to everything
running on your system.
Q I have compiled PHP as a CGI and when PHP tries to load the php_mapscript.so, I get an
“undefined symbol: _register_list_destructors” error. What’s wrong?
A Your PHP CGI executable is probably not linked to support loading shared libraries. The MapServer
configure script must have given you a message about a flag to add to the PHP Makefile to enable
shared libs.
Edit the main PHP Makefile and add “-rdynamic” to the LDFLAGS at the top of the Makefile, then
relink your PHP executable.
Note: The actual parameter to add to LDFLAGS may vary depending on the system you’re running
on. On Linux it is “-rdynamic”, and on *BSD it is “-export-dynamic”.
Q I am dynamically loading gd.so and php_mapscript.so and running into problems, why?
A The source of the problems could be a mismatch of GD versions. The PHP GD module compiles its
own version of libgd, and if the GD library is loaded before the mapscript library, mapscript will
use the php-specific version. Wherever possible you should use a gd.so built with the same GD as
PHPMapScript. A workaround is to load the php_mapscript module before the GD module.
4.4.1 Compilation
Before compiling C# MapScript you should compile MapServer with the options for your requirements. For more
information about the compilation of MapServer please see Win32 Compilation and Installation Guide. It is highly
recommended to minimize the library dependency of your application, so when compiling MapServer enable only the
features really needed. To compile the C# binding SWIG 1.3.31 or later is required.
Warning: This document may refer to older library versions. You may want to try to use more recent library
versions for your build.
You should compile MapServer, MapScript and all of the subsequent libraries using Visual Studio 2003. Download
and uncompress the latest SWIGWIN package that contains the precompiled swig.exe Open the Visual Studio .NET
2003 Command Prompt and step into the /mapscript/csharp directory. Edit makefile.vc and set the SWIG variable to
the location of your swig.exe
Use
nmake -f makefile.vc
You should compile MapServer, MapScript and all of the subsequent libraries using Visual Studio 2005. Download
and uncompress the latest SWIGWIN package that contains the precompiled swig.exe Open the Visual Studio 2005
Command Prompt and step into the /mapscript/csharp directory Edit makefile.vc and set the SWIG variable to the
location of your swig.exe.
Use
nmake -f makefile.vc
Before the compilation you should download and install the recent mono Win32 setup package (eg. mono-1.1.13.2-
gtksharp-2.8.1-win32-1.exe) Edit makefile.vc and set the CSC variable to the location of your mcs.exe. Alternatively
you can define
MONO = YES
52 Chapter 4. Installation
MapServer Documentation, Release 6.0
Beginning from MapServer 4.8.3 you can invoke the C# compilation from the MapServer directory by uncommenting
DOT_NET in nmake.opt
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# .NET/C# MapScript
# ----------------------------------------------------------------------
# .NET will of course only work with MSVC 7.0 and 7.1. Also note that
# you will definitely want USE_THREAD defined.
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#DOT_NET = YES
for making the compilation an copying the targets into a common output directory.
For testing the compilation and the runtime environment you can use
nmake -f makefile.vc test
within the csharp directory for starting the sample applications compiled previously. Before making the test the
location of the corresponding libraries should be included in the system PATH.
Before the compilation you should download and install the recent mono Linux package. Some distributions have pre-
compiled binaries to install, but for using the latest version you might want to compile and install it from the source.
Download and uncompress the latest SWIG release. You should probably compile it from the source if pre-compiled
binaries are not available for your platform.
Before compiling MapScript, MapServer should be configured and compiled. Beginning from MapServer 4.8.2 during
configuration the mapscript/csharp/Makefile will be created according to the configuration options. Edit this file and
set the SWIG and CSC for the corresponding executable pathes if the files could not be accessed by default. To compile
at a console step into the /mapscript/csharp directory use.
make
Beginning from 4.10.0 the csharp/Makefile supports the OSX builds. Before making the build the recent MONO
package should be installed on the system.
Before compiling MapScript, MapServer should be configured and compiled. Beginning from MapServer 4.8.2 during
configuration the mapscript/csharp/Makefile will be created according to the configuration options. Edit this file and
set the SWIG and CSC for the corresponding executable pathes if the files could not be accessed by default. To compile
at a console step into the /mapscript/csharp directory use
make
4.4.2 Installation
The files required for your application should be manually installed. It is highly recommended to copy the files into
the same folder as the executable resides.
Visual Studio 2005 requires a manifest file to load the CRT native assembly wrapper
If you have compiled MapServer for using the CRT libraries and you are using the MS.NET framework 2.0 as the
execution runtime you should supply a proper manifest file along with your executable, like:
<?xml version="1.0" encoding="utf-8"?>
<assembly xsi:schemaLocation="urn:schemas-microsoft-com:asm.v1 assembly.adaptive.xsd" manifestVersion
<assemblyIdentity name="drawmap.exe" version="1.0.0.0" type="win32" />
<dependency>
<dependentAssembly asmv2:dependencyType="install" asmv2:codebase="Microsoft.VC80.CRT.manifest" asmv2:
<assemblyIdentity name="Microsoft.VC80.CRT" version="8.0.50608.0" publicKeyToken="1fc8b3b9a1e18e3b" p
<hash xmlns="urn:schemas-microsoft-com:asm.v2">
<dsig:Transforms>
<dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
</dsig:Transforms>
<dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<dsig:DigestValue>UMOlhUBGeKRrrg9DaaPNgyhRjyM=</dsig:DigestValue>
</hash>
</dependentAssembly>
</dependency>
</assembly>
This will inform the CLR that your exe depends on the CRT and the proper assembly wrapper is to be used. If you are
using the IDE the manifest file could be pregenerated by adding a reference to Microsoft.VC80.CRT.manifest within
the /Microsoft Visual Studio 8/VC/redist/x86/Microsoft.VC80.CRT directory.
According to the windows makefile the MapScript compilation target (mapscript.dll) is linked with the /MD option. In
this case the VS2005 linker will generate a manifest file containing the unmanaged assembly dependency. The sample
contents of the manifest file are:
54 Chapter 4. Installation
MapServer Documentation, Release 6.0
Like previously mentioned if you are creating a windows application the common language runtime will search for a
manifest file for the application. The name of the manifest file should be the same as the executable append and end
with the .manifest extension. However if the host process is not controlled by you (like web mapping applications using
aspnet_wp.exe as the host process) you will not be certain if the host process (.exe) will have a manifest containing a
reference to the CRT wrapper. In this case you may have to embed the manifest into the dll as a resource using the mt
tool like:
mt /manifest mapscript.dll.manifest /outputresource:mapscript.dll;#2
the common language runtime will search for the embedded resource and load the CRT assembly properly.
Normally it is enough to load the CRT with the root dll (mapscript.dll), but it is not harmful embedding the manifest
into the dependent libraries as well.
When compiling with Microsoft Visual Studio 2005 variable name collision may occur between regex.c and crtdefs.h.
For more details see:
http://trac.osgeo.org/mapserver/ticket/1651
Using the MapScript interface created by the SWIG interface generator the communication between the C# wrapper
classes (mapscript_csharp.dll) and the C code (mapscript.dll) takes place using platform invoke like:
[DllImport("mapscript", EntryPoint="CSharp_new_mapObj")]
public static extern IntPtr new_mapObj(string jarg1);
The DllImport declaration contains the library name, however to transform the library name into a file name is platform
dependent. On Windows the library name is simply appended with the .dll extension (mapscript.dll). On the Unix
systems the library file name normally starts with the lib prefix and appended with the .so extension (libmapscript.so).
Mapping of the library name may be manually controlled using a dll.config file. This simply maps the library file
the DllImport is looking for to its unix equivalent. The file normally contains the following information (map-
script_csharp.dll.config):
<configuration>
<dllmap dll="mapscript" target="libmapscript.so" />
</configuration>
The file should be placed along with the corresponding mapscript_csharp.dll file, and created by default during the
make process. For more information see:
http://trac.osgeo.org/mapserver/ticket/1596 http://www.mono-project.com/Interop_with_Native_Libraries
According to http://trac.osgeo.org/mapserver/ticket/1762 MapServer may not operate equally well on different locale
settings. Especially when the decimal separator is other than “.” inside the locale of the process may cause parse errors
when the mapfile contains float numbers. Since the MONO process takes over the locale settings of the environment
it is worth considering to set the default locale to “C” of the host process, like:
LC_ALL=C mono ./drawmap.exe ../../tests/test.map test_csharp.png
This chapter will summarize the most frequent problems the user can run into. The issues were collected mainly from
the -users list and the IRC.
You can get this problem on Windows and in most cases it can be dedicated to a missing or an unloadable shared
library. The error message talks about mapscript.dll but surely one or more of the dll-s are missing that libmap.dll
depends on. So firstly you might want to check for the dependencies of your libmap.dll in your application directory.
You can use the Visual Studio Dependency Walker to accomplish this task. You can also use a file monitoring tool
(like SysInternal’s filemon) to detect the dll-s that could not be loaded. I propose to store all of the dll-s required by
your application in the application folder. If you can run the drawmap C# sample application with your mapfile your
compilation might be correct and all of the dlls are available.
You may find that the MapScript C# interface behaves differently for the desktop and the ASP.NET applications.
Although you can run the drawmap sample correctly you may encounter the dll loading problem with the ASP.NET
applications. When creating an ASP.NET project your application folder will be ‘Inetpubwwwroot[YourApp]bin’
by default. The host process of the application will aspnet_wp.exe or w3wp.exe depending on your system. The
application will run under a different security context than the interactive user (under the context of the ASPNET
user by default). When placing the dll-s outside of your application directory you should consider that the PATH
environment variable may differ between the interactive and the ASPNET user and/or you may not have enough
permission to access a dll outside of your application folder.
If you find a problem dedicated to the MapScript C# interface feel free to file a bug report to the Issue Tracker.
56 Chapter 4. Installation
MapServer Documentation, Release 6.0
Table of Contents
• IIS Setup for MapServer
– Base configuration
– Php.ini file
– Internet Services Manager
– Under the tree for your new website - add virtual directories for
– Test PHP
– Mapfiles for IIS
– Configuration files:
Some help on how to set up MapServer/Chameleon/PhpPgAdmin on Microsoft IIS (v5.0). Contains note on changes
to the php.ini file and necessary changes to the MapServer mapfiles. Please contribute or make changes as required.
• Windows 2000
• IIS 5.0
• MS4W 1.2.1
• Chameleon 2.2
• PHP 4.3.11
• MapServer 4.7
• PhpPgAdmin 3.5.4 (if using postgresql/postgis)
• Postgres 8.0.3 (if using postgresql/postgis)
• Postgis 1.0.3 (if using postgresql/postgis)
This setup assumes that MS4W was unzipped to form c:\ms4w\ directory.<br>
Under your website tree, create a new website (e.g. msprojects). View the properties for the new website.
Web Site Tab
• set the IP address and under the Advanced tab put the complete Host Header name (e.g.msprojects.gc.ca).
Home Directory Tab
• content should come from: A directory located on this computer.
• Local Path: c:\ms4w\Apache\htdocs
4.5.4 Under the tree for your new website - add virtual directories for
cgi-bin Under Properties, virtual directory tab Local Path should point to c:\ms4w\apache\cgi-bin. Select Read.
Execute Permissions should say “scripts and executables”
ms_tmp Under Properties, virtual directory tab Local Path should point to c:\ms4w\tmp\ms_tmp. Select Read, Write.
Execute Permissions should say “scripts only”. This is where temporary images are written to so in the File
system Security tab (use windows explorer), the c:\ms4w\tmp\ms_tmp directory should have permissions set
for the Internet Guest Account (Read and execute, Read, Write, List Folder Contents).
tmp Under Properties, virtual directory tab Local Path should point to c:\ms4w\tmp. Select Read, Write. Execute
Permissions should say “scripts only”. This is where chameleon writes sessions to so in the File system Secu-
rity tab (use windows explorer), the c:\ms4w\tmp directory should have permissions set for the Internet Guest
Accounnt (Read and execute, Read, Write, List Folder Contents).
chameleon Under Properties, virtual directory tab Local Path should point to C:\ms4w\apps\chameleon\htdocs. Select
Read. Execute Permissions should say “scripts only”. Under the Chameleon tree, you can add virtual directories
for admin (c:\ms4w\apps\chameleon\admin\htdocs), samples (c:\ms4w\apps\chameleon\samples\htdocs), cwc2
(c:\ms4w\apps\chameleon\cwc2\htdocs)
phppgadmin If using postgresql/postgis, under Properties, virtual directory tab Local Path should point to
C:\ms4w\Apache\htdocs\phpPgAdmin. Select Read, Write. Execute Permissions should say “scripts and ex-
ecutables”. Under Documents - add index.php.
Note: We had to unzip the phppgadmin package into this directory in order to get phppgadmin to show us the login
page at http://yourserver/phppgadmin/index.php. You might want additional security on this directory.
gmap Good for testing purposes. Remember to change your mapfiles as discussed in Mapfiles for IIS below. Under
Properties, virtual directory tab Local Path should point to C:\ms4w\apps\gmap\htdocs. Select Read. Execute
Permissions should say “scripts only”.
In a command line window, navigate to c:\ms4w\apache\cgi-bin and run php -i. This should return the out-
put that the phpinfo() function returns. I got an error about how it couldn’t find ntwdblib.dll. I found this in
c:\ms4w\apache\php\dlls and I copied it to the cgi-bin directory.
58 Chapter 4. Installation
MapServer Documentation, Release 6.0
For Chameleon
C:\ms4w\apps\chameleon\config\chameleon.xml
C:\ms4w\apps\chameleon\config\cwc2.xml
Table of Contents
• Oracle Installation
– Preface
– System Assumptions
– Compile MapServer
– Set Environment Variables
4.6.1 Preface
This document explains the whole configuration needed to get the connect between MapServer CGI and an Oracle
database server on a linux (Ubuntu) box. The aim of this document is just to put a lot of googled knowledge in ONE
place. Hopefully it will preserve many of people spending analog amount of time than I did!
This manual was written, because I spent several days googling around to get my UMN having access to an oracle
database. I’m NOT an oracle expert, so the aim of this document is just to put a lot of googled knowledge in ONE
place. Hopefully it will preserve many of people spending analog amount of time than I did! (Or: If you have the
choice: Try PostGIS ;-))
Before we start, some basic knowledge, I didn’t know before:
• MapServer can access oracle spatial as well as geodata from any oracle locator installation! Oracle locator
comes with every oracle instance, there is no need for an extra license.
• There is no need for further installation of any packages beside oracle/oracle OCI
We assume that Oracle is already installed, there is a database and there is some geodata in the database. The following
paths should be known by the reader:
• ORACLE_HOME
• ORACLE_SID
• ORACLE_BASE
• LD_LIBRARY_PATH
We also assume that you have installed apache2 (our version was 2.0.49) and you are used to work with Linux/UNIX
systems. We also think you are able to handle the editor vi/vim.
We ensure that the Oracle user who later accesses the database has write-access to the oracle_home directory.
We also assume, that you already have setup the tnsnames.ora file. It should look like that:
MY_ORACLE =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = host)(PORT = 1521))
(CONNECT_DATA =
(SERVICE_NAME = your_name)
)
)
It is important that you know the NAME of the datasource, in this example this is “MY_ORACLE” and will be used
further on. Done that, you’re fine using User/Password@MY_ORACLE in your mapfile to connect to the oracle
database. But first we have to do some more stuff.
If you got that, you’re fine from the MapServer point of view.
It is important to set all environment variables correctly. There are one the one hand system-wide environment vari-
ables to be set, on the other hand there should be set some for the cgi-directory in your Apache configuration.
System Variables
On Ubuntu (and on many other systems) there is the file “/etc/profile” which sets environment variables for all users
on the system (you may also dedicate user-specific environment variables by editing the users “.profile” file in their
home directory, but usually the oracle database users are not users of the system with their own home)
60 Chapter 4. Installation
MapServer Documentation, Release 6.0
# **(e.g. ORACLE_HOME=/app/oracle/ora10g)
# **(e.g. ORACLE_HOME=/app/oracle)
# **(e.g. ORACLE_HOME=/app/oracle/ora10g/lib)
The command comes silent, so there is no system output if you didn’t mistype anything!
Sometimes it is confusing WHERE to set WHAT in the splitted apache2.conf-files. In the folder
“/etc/apache2/sites_available” you find your sites-file. If you did not do sth. Special e.g. installing virtual hosts,
the file is named “default”. In this file, the apache cgi-directory is defined. Our file looks like this:
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
<Directory "/var/www/cgi-bin">
AllowOverride None
Options ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory></p>
In this file, the local apache environment variables must be set. We did it within a location-block like this:
<Location "/cgi-bin/">
SetEnv ORACLE_HOME "/path/to/oracle/home"
</Location></p>
Where /cgi-bin/ in the opening location block refers to the script alias /cgi-bin/ and the TNS_ADMIN directory point
to the location of the tnsnames.ora file.
Then restart apache:
$ /etc/init.d/apache2 force-reload
Create mapfile
Before we start creating our mapfile ensure that you have a your access data (User/Password) and that you know the
Oracle SRID, which could be different from the proj-EPSG!
The data access parameters:
• CONNECTIONTYPE oraclespatial
• CONNECTION ‘user/password@MY_ORACLE‘
So you are fine now. Load the mapfile in your application and try it. If everything goes well: Great, if not, possibly this
ugly error-emssage occurs (this one cmae by querying MapServer through the WMS interface as a GetMap-request):
<ServiceExceptionReport version="1.0.1">
<ServiceException>
msDrawMap(): Image handling error. Failed to draw layer named ’test1’.
msOracleSpatialLayerOpen(): OracleSpatial error. Cannot create OCI Handlers.
Connection failure. Check the connection string. Error: .
</ServiceException>
</ServiceExceptionReport>
This points us towards, that there might be a problem with the connection to the database. First of all, let’s check, if
the mapfile is all right. Therefore we use the MapServer utility program shp2img.
Let’s assume you are in the directory, where you compiled MapServer and run shp2img:
$ cd /var/src/mapserver_version/
If not, this possibly points you towards any error in your mapfile or in the way to access the data directly. In this
case, take a look at Oracle Spatial. If there is a problem with your oracle connect, the same message as above
(MsDrawMap() ...) occurs. Check your mapfile syntax and/or the environment settings for Oracle.
For Debian/Ubuntu it’s worth also checking the file “/etc/environment” and test-wise to add the system variables
comparable to System Variables
If the output is OK, you may have a look at the generated image (output.png). Then your problem reduces to the access
of apache to oracle home directory. Carefully check your apache configuration. Please note, that the apache.config file
differs in several linux-distributions. For this paper we talk about Ubuntu, which should be the same as Debian.
62 Chapter 4. Installation
CHAPTER 5
Mapfile
63
MapServer Documentation, Release 6.0
Table of Contents
• Cartographical Symbol Construction with MapServer
– Abstract
– Introduction
* Multiple Rendering and Overlay
* Symbol Scaling
* Mapserver and symbol specification
– Using Cartographical Symbols in MapServer
* Output formats
* Symbol units
* Scaling of Symbols
– Construction of Point Symbols
* Symbols of TYPE VECTOR and ELLIPSE
* Symbols of TYPE truetype
* Symbols of TYPE pixmap
* Symbol definitions for the figure that demonstrates point symbols
* Combining symbols
– Construction of Line Symbols
* Overlaying lines
* Use of the PATTERN and GAP parameters
* Use of the OFFSET parameter
* Asymmetrical line styling with point symbols
– Area Symbols
* Hatch fill
* Polygon fills with symbols of TYPE pixmap
* Polygon fills with symbols of TYPE vector
– Examples (Mapserver 4)
* Basic Symbols
* Complex Symbols
* Mapfile Changes - line styling
– Tricks
* Changing the center of a point symbol
– Current Problems / Open Issues
* GAP - PATTERN incompatibility
– Summing up
5.1.1 Abstract
This Document refers to the syntax of MAP and symbol files for MapServer 6. The first version of the document
was based on the results of a project carried out at the University of Hannover, Institute of Landscape and Nature
Conservation. It was initiated by Mr. Dipl. Ing. Roland Hachmann. Parts have been taken from a study carried
through by Karsten Hoffmann, student of Geography and Cartography at the FU Berlin. In the context of a hands-on
training in the company GraS GmbH Mr. Hoffman mainly dealed with the development of symbols. (Download study
report in German) His degree dissertation will also concern this subject.
The document has been heavily revised for Mapserver 6.
64 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
5.1.2 Introduction
A map is an abstract representation that makes use of point, line and area symbols. Bertin (1974) created a clear and
logical symbol scheme in which symbols can be varied referring to graphical variables. The following graphical vari-
ables can be used within MapServer: FORM, SIZE, PATTERN, COLOR and LIGHTNESS. Point and area symbols
as well as text fonts (ttf) can additionally be displayed with a frame which we call OUTLINE.
The following figure shows the theoretical structure of cartographical symbols, which are also used in MapServer:
Say you want to display a highway with a black border line, two yellow lanes and a red center lane. This calls for a
combination of signatures.
Complex cartographical effects can be achieved by rendering the same vector data with different symbols, sizes and
colours on top of each other. This can be done using separate LAYERs. This could, however, have performance effects
for the application, as every rendering process of the same geometry will take up additional processor time. The
preferred solution is to use multiple STYLEs to create complex symbols by overlay.
To create the highway symbol mentioned above with a total width of 9 units, the lowest STYLE (in drawing order) will
be a broad black line with a width of 9 units. The second level STYLE will be a yellow line with a width of 7 units,
and the topmost STYLE will be a red line with a width of 1 unit. That way each yellow coloured lane will have a width
of (7-1)/2 = 3 units.
Combining symbols can be a solution for many kinds of cartographical questions. A combination of different geometry
types is also possible. A polygon data set can be rendered as lines to frame the polygons with a line signature. It can
also be rendred as polygons with a symbol filling the polygon. When the polygon fill is rendered on top of the lines,
the inner part of the underlying outline is covered by the fill symbol of the polygon. What is observed here is a clipping
effect tha in will result in an asymmetric symbol for the boundary line. To present the outline without clipping, just
reorder the LAYERs or STYLEs and put the outline presentation on top of the fill.
Yet another way to construct advanced line signatures for framed polygons is to tamper with the original geometries
by buffering or clipping the original geometry such that the new objects lie inside the original polygons or grow over
the borders. PostGIS can help achieve a lot of effects.
The OPACITY parameter of LAYER and STYLE can be used to achieve transparency (making lower symbols “shine”
through upper symbols).
Symbol Scaling
There are two basically different ways to handle the display size of symbols and cartographical elements in a map at
different scales. The size of cartographical elements is either set in screen pixel or in real world units.
• If the size is set in real world units (for example meters), it will shrink and grow according to the scale at which
the map is displayed.
• When sizes are given in screen pixels, symbols look the same at all scales.
MapServer implements the “screen pixels” size type for displaying cartographical elements. “Real world units”, as
described above, can be achieved using the SYMBOLSCALEDENOM parameter of the layer.
In a MapServer application, symbol parameters are organised in the map file as follows:
• Each LAYER has a TYPE parameter that defines the type of geometry (point, line or polygon). The symbols are
rendered at points, along lines or over areas accordingly.
• Basic symbols are defined in SYMBOL elements, using the parameters TYPE, POINTS, IMAGE, FILLED, and
more (SYMBOL elements can be collected in separate symbol files for reuse).
• Colour, lightness, size and outline are defined inside the STYLE sections of a CLASS section using the parameters
COLOR, SIZE, WIDTH and OUTLINECOLOR.
• Patterns for styling lines and polygons are defined in STYLE sections using GAP and PATTERN.
• Several basic elements can be combined to achieve a complex signature using several STYLEs inside one CLASS.
The following example shows the interaction of some of these elements and explains the configuration in the LAYER
and the SYMBOL sections necessary for rendering a cartographical point symbol (a red square with a 1 pixel wide
black outline and a smaller blue circle inside):
66 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
Vectors, truetype fonts and raster images are basic graphical elements that are defined by the TYPE parameter in the
STYLE element. This section explains how thezs elements can be combined to create complex cartographical symbols,
and it describes some other important aspects of map rendering in Mapserver.
Output formats
MapServer support raster output formats (e.g. PNG, JPEG and GIF) and vector output formats (e.g. PDF, SWG). The
raster formats (except for GIF) use anti-aliasing. See OUTPUTFORMAT for more.
Symbol units
The units used for specifying dimensions is defined in the SIZEUNITS parameter of the LAYE‘R. ‘SIZEUNITS can be
pixels, feet, inches, kilometers, meters, miles, dd and nauticalmiles. The default is pixels.
The MAP element’s RESOLUTION and DEFRESOLUTION parameters will determine the actual scale of the resulting
map and hence the size of the symbols on the map. DEFRESOLUTION is by default 72 dpi (dots per inch). If
RESOLUTION is specified to 144 (and DEFRESOLUTION is 72), all dimensions specified in the map file will be
multiplied by 144/72 = 2. This can be used to produce higher resolution images.
Dimensions can be specified using decimals.
Scaling of Symbols
The SYMBOLSCALEDENOM parameter in the LAYER section specifies the scale at which the symbol or text label
is displayed in exactly the dimensions defined in the STYLEs (for instance using SIZE and WIDTH). Observe that all
the parameters concerned with the symbol dimensions (SIZE, WIDTH, ...) are tightly connected to the SYMBOL-
SCALEDENOM parameter. The MAXSIZE and MINSIZE parameters inside the STYLE block limit the scaling of
symbols to the maximum and minimum size specified here (but does not affect the size calculations).
When the scale changes, the elements (defined in STYLEs) of a composite cartographical symbol may change their
positions relative to each other, especially at very small map scales (large scale denominators). They can also slightly
change their shape when they are displayed as tiny little images.
It is not possibile to define the display intervals with MINSCALEDENOM and MAXSCALEDENOM in the STYLE-
section, so this kind of tuning has to be solved at the LAYER level. To do this, create several layers with the same
geometries for different scale levels.
Always observe that cartographical symbols depend a lot on the scale! So be careful with the interaction of content,
symbols and scale when creating projects. All three parameters heavily interact and have to be coordinated to produce
a good map.
In the figure below, point symbols of TYPE truetype, pixmap, ellipse and vector are demonstrated. The precise position
of the point for which the symbol is rendered is shown with a small red dot. A small blue dot is used to show an offset
position.
Figure 5.3: Basic point symbol TYPEs, showing effects of size, offset, angle and outlinecolor
68 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
The TYPE vector defines the shape of a symbol by setting X and Y values in a local two dimensional coordinate
system with X values increasing to the right and Y values increasing downwards.
The coordinates defining the symbol is listed in the POINTS element, which is explicitly ended using END. The
maximum number of points can be increased by changing the parameter MS_MAXVECTORPOINTS in the file map-
symbols.h before compilation. The current default is 100. Note that by setting the end point equal to the start point you
obtain a closed shape (polygon). A vector symbol can consist of several elements (lines, polygons). The coordinates
-99 -99 are used to separate the elements.
When creating symbols of TYPE vector you should observe some style guidelines. Avoid downtilted lines in area
symbols, as they will lead to heavy aliasing effects. Furthermore you should not go below a useful minimum size,
which is relevant for all types of symbols. Keep in mind that for pixel images, every symbol of TYPE vector has to be
rendered using pixels (pixmap symbols may be used directly for drawing).
Note: Current behaviour is for the bounding box of a vector symbol to always have 0,0 (in the SYMBOL coordinate
system) as its upper left corner. This can be used to generate asymmetrical symbols.
To create ellipses (and circles), use the TYPE ellipse. The shape of the ellipse is set in the POINTS elements (X - size
in the horizontal direction, Y - size in the vertical direction). To create a circle, let X and Y have the same value.
You can use symbols from truetype fonts. The symbol settings are defined in the SYMBOL element. Specify the
character or the ASCII number of the character to be used in the CHARACTER parameter. The FONT parameter is
used to specify the font to be used (the alias name from the font file - often “fonts.list”). The FONTSET parameter of
the MAP element must be set for fonts to work.
??With the parameter ANTIALIAS you define whether to apply antialiasing to the symbols or characters. It is recom-
mended to do this especially with more complex symbols and and whenever they don’t fit well into the raster matrix
or show a visible pixel structure.??
In the STYLE section of the LAYER object it is possible to define colours for truetype symbols (as with signatures of
the TYPE vector). You can specify both fill colour and outline colour.
To find out the character number of a symbol use one of the following options:
• Use the software FontMap (Shareware, with free trial version for download, thanks Till!)
• Use the MS Windows truetype map
• Trial and Error :-)
Please note that the numbering of the so-called “symbol fonts” starts at 61440! So if you want to use character T,
you have to use 61440 + 84 = . (ain’t that a pain!!)
You can also place truetype characters and strings on the map using LABEL. The you can control the placing of the text
by using the POSITION parameter [ul|uc|ur|cl|cc|cr|ll|lc|lr], that specifies the position relative to the geometric origin
of the geometry.
Symbols of the TYPE pixmap are simply small raster images. The file name of the raster image is specified in the
IMAGE parameter of the SYMBOL element. MapServer supports the raster formats GIF and PNG for pixmaps.
Observe the colour depth of the images and avoid using 24 bit PNG symbols displayed in 8 bit mode as this may cause
unexpected colour leaps.
When using raster images, the colour cannot be modified in the SYMBOL element subsequently.
You can specify a colour with the TRANPARENT parameter which will not be displayed - i.e. it will be transparent.
As a result, all underlying objects and colours are visible.
Note: The TRANSPARENT parameter for pixmaps only works for the GD renderer (GIF rendering). The AGG
renderer supports natively transparent images, but does not support the TRANSPARENT parameter.
The SIZE parameter defines the height of pixmap symbols when rendered. The pixel structure will show when the
SIZE grows too large. If you are using symbol scaling (SYMBOLSCCALEDENOM is set) and want to prevent this
from happening, you should set the MAXSIZE parameter.
Pixmap symbols can be rotated using the ANGLE parameter.
This code was used to produce the symbols in the point symbol figure.
First, the symbol definitions:
SYMBOL
NAME "o-flag-trans"
TYPE pixmap
IMAGE "o-flag-trans.png"
END # SYMBOL
SYMBOL
NAME "circlef"
TYPE ellipse
FILLED true
POINTS
10 10
END # POINTS
END # SYMBOL
SYMBOL
NAME "P"
TYPE truetype
FONT "arial"
CHARACTER "P"
END # SYMBOL
SYMBOL
NAME "v-line"
TYPE vector
POINTS
0 0
5 10
10 0
END
END
SYMBOL
NAME "v-poly"
TYPE vector
FILLED false
POINTS
0 0
3.5 8
70 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
7 0
5.2 0
3.5 4
1.8 0
0 0
END
END
Then, the layers and styles used for producing the polygon V symbols in the point symbol figure:
LAYER # Vector v - polygon
STATUS DEFAULT
TYPE POINT
FEATURE
POINTS
10 30
END # Points
END # Feature
CLASS
STYLE
SYMBOL "v-poly"
COLOR 0 0 0
END # STYLE
STYLE
SYMBOL "circlef"
COLOR 255 0 0
SIZE 4
END # STYLE
END # CLASS
END # LAYER
END # Points
END # Feature
CLASS
STYLE
SYMBOL "v-poly"
COLOR 0 0 0
SIZE 30
ANGLE 60
END # STYLE
STYLE
SYMBOL "circlef"
COLOR 255 0 0
SIZE 4
END # STYLE
END # CLASS
END # LAYER
72 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
COLOR 255 0 0
SIZE 4
END # STYLE
END # CLASS
END # LAYER
80 30
END # Points
END # Feature
CLASS
STYLE
SYMBOL "v-poly"
SIZE 30
OUTLINECOLOR 0 255 0
END # STYLE
STYLE
SYMBOL "circlef"
COLOR 255 0 0
SIZE 4
END # STYLE
END # CLASS
END # LAYER
Combining symbols
The following figure shows how to combine several basic symbols to create a complex point symbol. The combination
is achieved by adding several STYLEs within one layer. Each STYLE element references one SYMBOL element. All
the basic symbols are centered and overlayed when rendered.
Notice that the SIZE parameter in the STYLE element refers to the height of the symbol (extent in the Y direction).
A standing rectangle will thus display with a smaller area than a lying rectangle, although both have the same SIZE
parameter and the same maximum Y value in the SYMBOL element. When combining several basic point symbols on
top of each other, they will not always be centered correctly due to the integer mathematics required when rendering
raster images. It is recommended not to combine elements with even and odd numbered SIZE parameters, as this tends
to produce larger irregularities.
For displaying line geometries you specify the width of the lines using the WIDTH parameter and the colour using the
COLOR parameter. If no colour is specified, the line will not be rendered. If no width is specified, a thin line (one unit
(pixel) wide) will result.
Overlaying lines
When combining several styles / symbols on a line, they will be positioned on the baseline which is defined by the
geometry of the object. In most cases MapServer correctly centers symbols. The combination of a line displayed in 16
units width and overlayed with a 10 unit width line results in a line symbol with a 3 unit border. If the cartographical
symbol is to contain a centered line with a width of 1 pixel, then the widths should be reconfigured, for example to 11
and 17 units. As a rule of thumb don’t combine even numbered and odd numbered widths.
The PATTERN and GAP parameters can be used to produce styled lines in MapServer.
To create line patterns, use the PATTERN parameter of the STYLE. Here you define dashes by specifying the length
of the first dash, followed by the length of the first gap, then the length of the second dash, followed by the second gap,
and so on. This pattern will be repeated as many times as that pattern will fit into the line. LINECAP can be used to
control how the ends of the dashes are rendered. LINEJOIN can be used to control how sharp bends are rendered. In
the left column of the figure, you will find three examples where PATTERN has been used. Number 2 from below uses
74 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
LINECAP butt, number 3 from below uses LINECAP round (and LINEJOIN miter) and number 4 from below uses
LINECAP butt (and is overlayed over a wider, dark grey line). To produce dots, use 0 for dash length with LINECAP
‘round’.
Styled lines can be specified using GAP and a symbol for styling. In the figure, you will find four examples where
GAP has been used (in the right column). At the bottom a SYMBOL of TYPE ellipse has been used, then a SYMBOL
of TYPE vector, then a SYMBOL of TYPE font and at the top a SYMBOL of TYPE pixmap.
Note: It is currently not possible to specify an offset (start gap) when creating asymmetrical patterns.
The following figure shows how to use styles to define different kinds of line symbols.
Note: For the line at the bottom of the right column, the red dots should have coincided with the black dots, but the
GAP length does not work as expected.
Below you will find the SYMBOLs and STYLEs that were used to produce the line symbols in “Construction of Line
Symbols”. The LAYERs are ordered from bottom to top of the figure.
Styles and symbols for lines
SYMBOL
NAME "circlef"
TYPE ellipse
FILLED true
POINTS
1 1
END # POINTS
76 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
END # SYMBOL
SYMBOL
NAME "P"
TYPE truetype
FONT "arial"
CHARACTER "P"
END # SYMBOL
SYMBOL
NAME "vertline"
TYPE vector
FILLED true
POINTS
0 5
0 10
1.4 10
1.4 5
0 5
END # POINTS
END # SYMBOL
SYMBOL
NAME "o-flag-trans"
TYPE pixmap
IMAGE "o-flag-trans.png"
END # SYMBOL
END # Points
END # Feature
CLASS
STYLE
COLOR 0 0 0
WIDTH 5.0
LINECAP butt
PATTERN 40 5 END
END # STYLE
END # CLASS
END # LAYER
78 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
END # LAYER
POINTS
50 5
70 10
90 10
80 5
END # Points
END # Feature
CLASS
STYLE
COLOR 0 0 0
WIDTH 3.6
END # STYLE
STYLE
COLOR 0 0 0
SYMBOL "circlef"
SIZE 10
GAP 42
END # STYLE
STYLE
COLOR 255 0 0
SYMBOL "circlef"
SIZE 3
GAP 42
END # STYLE
END # CLASS
END # LAYER
80 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
POINTS
50 25
70 30
90 30
80 25
END # Points
END # Feature
CLASS
STYLE
COLOR 0 0 0
WIDTH 6
END # STYLE
STYLE
COLOR 102 0 0
SYMBOL "P"
SIZE 20
#SIZE 70
GAP -30
#OUTLINECOLOR 0 255 0
#WIDTH 4
#OFFSET -10 -99
END # STYLE
END # CLASS
END # LAYER
POINTS
50 45
70 50
90 50
80 45
END # Points
END # Feature
CLASS
STYLE
COLOR 0 0 0
WIDTH 6
END # STYLE
STYLE
COLOR 102 0 0
SYMBOL "o-flag-trans"
SIZE 20
GAP -30
OFFSET -10 -99
END # STYLE
END # CLASS
END # LAYER
By default, all lines (and patterns) will be drawn with rounded ends (extending the lines slightly beyond their ends).
This effect gets more obvious the larger the width of line is. It is possible to alter this behaviour using the LINECAP
parameter of the STYLE. LINECAP butt will give butt ends (stops the line exactly at the end), with no extension of
the line. LINECAP square will give square ends, with an extension of the line. LINECAP round is the default.
LINEJOIN
The different values for the parameter LINEJOIN have the following visual effects. Default is round. miter will follow
line borders until they intersect and fill the resulting area. none will render each segment using linecap butt. The figure
below illustrates the different linejoins.
LINEJOINMAXSIZE
Specify the maximum length of m (only relevant for LINEJOIN type MITER). The value is a multiplication factor
(default 3). The actual max length is calculated as follows:
m - calculated join size
d - line width
m_max = d * LINEJOINMAXSIZE
82 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
In STYLE, an OFFSET parameter can be set to shift symbols in the X and Y direction. The displacement is not
influenced by the direction of the line geometry. Therefore the point symbols used for styling are all shifted in the
same direction, independent of the direction of the line (as defined in style number 2 in the map file example below -
red line in the map image). A positive X value shifts to the right. A positive Y value shifts downwards.
To generate lines that are shifted relative to the original lines, -99 has to be used for the Y value of the OFFSET. Then
the X value defines the distance to the line from the original geometry (perpendicular to the line). A positive X value
will shift to the right (when viewed in the direction of the line), a negative X value will shift to the left.
The example below shows how OFFSET works with the use of -99 (blue and green lines) and without the use of -99
(red line). The thin black line shows the location of the line geometry.
Line number 2 and 5 from below in the right column of the “Construction of Line Symbols” figure is an example of
asymmetrical line styling using a point symbol. This can be achieved either by using an OFFSET (with a Y value of
-99), or by using an asymmetrical point symbol of TYPE vector, as described in the tricks section below. Line number
2 from below is produced using an asymmetrical point symbol - this is best method for placing symbols on lines. Line
number 5 from below is produced using STYLE OFFSET. As can be seen, the symbols are here the rendered on the
offset line, meaning that at sharp bends, some symbols will be placed away from the line.
Areas (polygons) can be filled with symbols to create for instance hatches and graticules.
84 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
The symbols are by default used as tiles, and rendered (without spacing) one after the other in the x and y direction,
filling the whole polygon.
If the SIZE parameter is used in the STYLE, the symbols will be scaled to the specified height.
The GAP parameter of the STYLE can be used to increase the spacing of the symbols.
The AGG renderer uses anti-aliasing by default, so edge effects around the symbols can occure.
Hatch fill
Simple line hatches (e.g. horizontal, vertical and diagonal) can be created by filling the polygon with a hatch symbol.
The SIZE parameter in the STYLE that uses a SYMBOL of type hatch specifies the distance from center to center
between the lines (the default is 1). The WIDTH parameter specifies the width of the lines in the hatch pattern (default
is 1). The ANGLE parameter specifies the direction of the lines (default is 0 - horizontal lines).
The figure demonstrates the use of SIZE (bottom left), WIDTH (bottom left), ANGLE (top right) and overlay (top
right) of hatches.
The table shows excerpts of the map file that was used to produce the figure.
86 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
You can use other shapes than circles. B defines the width and H the height of the raster image. For a regular
arrangment of symbols in a 45 degree angle B = H. For symbols, which are regularly arranged in parallel and without
offset between each other one centered symbol with same x and y distances to the imageborder is enough.
The following figure shows an example of how you can design a pixmap to produce a hatch with wide lines.
To create a 45 degree hatch use:
B = H and x = y
Note: When using the MapServer legend observe that each raster pixmap is displayed only once in the original size
in the middle of the legend box.
The example below shows some pixmap symbols which can be used as area symbols with transparency. The raster
images were created using FreeHand, finished with Photoshop and exported to PNG with special attention regarding
the colour palette. Observe that you have to specify a COLOR in the STYLE section of the CLASS to display raster
pixmaps although it has no influence on the output and colour of the image.
Construction of a horizontally arranged area symbol
88 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
Construction of a hatch
CLASS section SYMBOL definition
CLASS SYMBOL
STYLE NAME "in_hatch"
COLOR 255 255 0 TYPE PIXMAP
END IMAGE "schraffur.png"
STYLE TRANSPARENT 2
SYMBOL "in_hatch" END
COLOR 0 0 0
OUTLINECOLOR 0 0 0
END
END
Polygons can be filled with symbols of TYPE vector. As for the other symbol fills, the pattern will be generated by
using the specified symbol for the tiles. The bounding box of the symbol is used when tiling.
The upper right corner of the bounding box of a symbols of TYPE vector is always (0, 0). The lower left corner of the
bounding is determined by the maximum x and y values of the symbol definition.
Creating vector symbols for polygon fills is done in much the same way as for pixmap symbols. Precision is necessary
to get nice symmetrical symbols.
Both polygon (FILL on) and line (FILL off) vector symbols can be used. For line symbols, the WIDTH parameter of
the STYLE‘will give the line width and the ‘SIZE parameter will specify the height of the symbol.
STYLE ANGLE can be used for polygon fills, but will only rotate each individual symbol, not the pattern as a whole.
To generate rotated patterns is therefore quite demanding.
Below you will find some examples of vector symbols used for polygon fills. The polygon fill is accompanied by the
vector symbol used for the fill. The centre of the vector symbol is indicated with a red dot.
The examples in this section were made for MapServer 4. Some of them may not work with later versions, but they
contain a lot of useful symbol definitions and are therefore provided as reference.
The symbols were created with MAP files and SYMBOL files, which can be download_old_symbols. If you want to
use these MAP files please note, that your MapServer must at least be able to handle 50 symbols. Otherwise you will
get an error while loading the SYMBOL files.
90 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
Basic Symbols
92 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
Complex Symbols
94 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
All line styling must be specified in layer STYLE. The following keywords have been removed from SYMBOL:
STYLE PATTERN GAP LINECAP LINEJOIN LINEJOINSIZE
The following keywords have been added to STYLE:
PATTERN GAP LINECAP LINEJOIN LINEJOINSIZE
The SYMBOL STYLE keyword has been renamed to PATTERN. The cartoline SYMBOL TYPE has been removed.
5.1.8 Tricks
Mapserver does all transformations (offset, rotation) with respect to the symbol center point. The center point is
calculated from the symbol’s bounding box. In some cases it can be useful to change the center point of a symbol.
Currently there is no way of explicitly specifying the center point of a SYMBOL. A mechanism for this (a new keyword
in SYMBOL that specifies the symbol center point) has been suggested in RFC45, but has not been implemented so
far.
When determining the position of the symbol center point, the lower x and y values of the bounding box is always set
to 0.
Here are some examples of what can be achieved by taking advantage of this for point symbols and decorated lines.
There are three examples in the illustration, and each example shows the result with and without the offset trick. At
the top arrows are added to lines using GEOMTRANSFORM start / end. In the middle, tags are added to lines using
GAP and ANGLE. At the bottom, a point symbol is shifted and rotated. The red dots represent the center points, and
the blue dots the offsets.
Below you will find three tables that contain the SYMBOLS and the STYLE mechanisms that were used to genereate
shifted symbols in the illustration.
96 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
98 Chapter 5. Mapfile
MapServer Documentation, Release 6.0
Table 5.5: Symbol tricks - shift - asymmetrical symbols. Unshifted symbol v-line, shifted symbol v-line-offs
SYMBOLs
SYMBOL
NAME "v-line"
TYPE vector
POINTS
0 0
5 10
10 0
END # POINTS
END # SYMBOL
SYMBOL
NAME "v-line-offs"
TYPE vector
POINTS
0 10
5 20
10 10
END # POINTS
END # SYMBOL
Creating advanced line symbols involving dashed lines are difficult due to the incompatibility of the dashed line
mechanisms (PATTERN) and the symbol on line placement mechanisms (GAP). A solution could be to allow GAP
be a list instead of a single number (perhaps renaming to GAPs or DISTANCES), but it would also be necessary to
introduce a new parameter to specify the distance to the first symbol on the line (‘STARTGAP‘?).
GAP does not support two dimensions, so the same gap will have to be used for for the x and the y directions. The
introduction of new parameters - GAPX and GAPY could be a solution to this.
5.1.10 Summing up
We hope that this document will help you to present your data in a cartographically nice manner with MapServer and
explains some basics and possibilities of the concept of MapServer as well as some weaknesses. It would be great to
put together a cartographical symbols library for the profit of everyone. This especially concerns truetype fonts, which
have been developed for some projects and contain some typical signatures for cartographical needs.
You can also view the discussion paper for the improvement of the MapServer Graphic-Kernel (German only).
5.2 CLASS
5.2. CLASS 99
MapServer Documentation, Release 6.0
DEBUG [on|off] Enables debugging of the class object. Verbose output is generated and sent to the standard error
output (STDERR) or the MapServer logfile if one is set using the LOG parameter in the WEB object.
See Also:
MS RFC 28: Redesign of LOG/DEBUG output mechanisms
EXPRESSION [string] Four types of expressions are now supported to define class membership. String compar-
isons, regular expressions, simple logical expressions, and string functions. If no expression is given, then all
features are said to belong to this class.
• String comparisons are case sensitive and are the fastest to evaluate. No special delimiters are neces-
sary although string must be quoted if they contain special characters. (As a matter of good habit, it is
recommended you quote all strings).
• Regular expressions function just like previous versions of MapServer. However, you must now delimit a
regular expression using /regex/. No quotes should be used.
• Logical expressions allow you to build fairly complex tests based on one or more attributes and there-
fore are only available with shapefiles. Logical expressions are delimited by parentheses “(expres-
sion)”. Attribute names are delimited by square brackets “[ATTRIBUTE]”. These names are case
sensitive and must match the items in the shapefile. For example: EXPRESSION ([POPULATION]
> 50000 AND ‘[LANGUAGE]’ eq ‘FRENCH’) ... The following logical operators are supported:
=,>,<,<=,>=,=,or,and,lt,gt,ge,le,eq,ne. As you might expect this level of complexity is slower to process.
• One string function exists: length(). This obviously computes the length of a string. An example follows:
EXPRESSION (length(’[NAME_E]’) < 8)
String comparisons and regular expressions work from the classitem defined at the layer level. You may
mix expression types within the different classes of a layer.
GROUP [string] Allows for grouping of classes. It is only used when a CLASSGROUP at the LAYER level is set.
If the CLASSGROUP parameter is set, only classes that have the same group name would be considered at
rendering time. An example of a layer with grouped classes might contain:
LAYER
...
CLASSGROUP "group1"
...
CLASS
NAME "name1"
GROUP "group1"
...
END
CLASS
NAME "name2"
GROUP "group2"
...
END
CLASS
NAME "name3"
GROUP "group1"
...
END
...
END # layer
KEYIMAGE [filename] Full filename of the legend image for the CLASS. This image is used when building a legend
(or requesting a legend icon via MapScript or the CGI application).
The following parameters allow you to define the symbol, and they are equivalent to their non-overlay counterparts:
• OVERLAYBACKGROUNDCOLOR
• OVERLAYCOLOR
• OVERLAYOUTLINECOLOR
• OVERLAYSIZE
• OVERLAYMINSIZE
• OVERLAYMAXSIZE
• OVERLAYSYMBOL
5.3 CLUSTER
5.3.1 Description
Since version 6.0, MapServer has the ability to combine multiple features from a point layer into single (aggregated)
features based on their relative positions. Only POINT layers are supported. This feature was added through MS RFC
69: Support for clustering of features in point layers.
POINT
MAXDISTANCE [double] Specifies the distance of the search region (rectangle or ellipse) in pixel positions.
REGION [string] Defines the search region around a feature in which the neighbouring features are negotiated. Can
be ‘rectangle’ or ‘ellipse’.
GROUP [string] This expression evaluates to a string and only the features that have the same group value are ne-
gotiated. This parameter can be omitted. The evaluated group value is available in the ‘Cluster:Group’ feature
attribute.
FILTER [string] We can define the FILTER expression filter some of the features from the final output. This expres-
sion evaluates to a boolean value and if this value is false the corresponding shape is filtered out. This expression
is evaluated after the the feature negotiation is completed, therefore the ‘Cluster:FeatureCount’ parameter can
also be used, which provides the option to filter the shapes having too many or to few neighbors within the
search region.
GROUP (expression) # we can define an expression to create separate groups for each value
FILTER (expression) # we can define a logical expression to specify the grouping condition
END
LABELITEM "Cluster:FeatureCount"
CLASS
...
LABEL
...
END
END
...
END
The following example uses a point datasource, in this case in KML format, to display clusters of railway stations.
Two classes are used: one to style and label the cluster, and one to style and label the single railway station.
Note: Since we can’t declare 2 labelitems, for the single railway class we use the TEXT parameter to label the station.
Mapfile Layer
####################
# Lightrail Stations
####################
SYMBOL
NAME "lightrail"
TYPE PIXMAP
IMAGE "../etc/lightrail.png"
END
LAYER
NAME "lightrail"
GROUP "default"
STATUS DEFAULT
TYPE POINT
CONNECTIONTYPE OGR
CONNECTION "lightrail-stations.kml"
DATA "lightrail-stations"
LABELITEM "Cluster:FeatureCount"
CLASSITEM "Cluster:FeatureCount"
###########################
# Define the cluster object
###########################
C L U S T E R
M A X D I S T A N C E 50
R E G I ON "ellipse"
END
################################
# Class1: For the cluster symbol
################################
CLASS
NAME "Clustered Lightrail Stations"
EXPRESSION ("[Cluster:FeatureCount]" != "1")
STYLE
SIZE 30
SYMBOL "citycircle"
COLOR 255 0 0
END
LABEL
FONT s c b
TYPE TRUETYPE
SIZE 8
COLOR 255 255 255
ALIGN CENTER
PRIORITY 10
BUFFER 1
PARTIALS TRUE
POSITION cc
END
END
################################
# Class2: For the single station
################################
CLASS
NAME "Lightrail Stations"
EXPRESSION "1"
STYLE
SIZE 30
SYMBOL "lightrail"
END
TEXT "[Name]"
LABEL
FONT s c b
TYPE TRUETYPE
SIZE 8
COLOR 0 0 0
OUTLINECOLOR 255 255 255
ALIGN CENTER
PRIORITY 9
BUFFER 1
PARTIALS FALSE
POSITION ur
END
END
# the following is used for a query
TOLERANCE 50
UNITS PIXELS
HEADER "../htdocs/templates/cluster_header.html"
FOOTER "../htdocs/templates/cluster_footer.html"
TEMPLATE "../htdocs/templates/cluster_query.html"
END
Map Image
Table of Contents
• Display of International Characters in MapServer
– Credit
– Related Links
– Requirements
– How to Enable in Your Mapfile
* Step 1: Verify ICONV Support and MapServer Version
* Step 2: Verify That Your Files’ Encoding is Supported by ICONV
* Step 3: Add ENCODING Parameter to your LABEL Object
* Step 4: Test with the shp2img utility
– Example Using PHP MapScript
– Notes
5.4.1 Credit
The following functionality was added to MapServer 4.4.0 as a part of a project sponsored by the Information-
technology Promotion Agency (IPA), in Japan. Project members included: Venkatesh Raghavan, Masumoto Shinji,
Nonogaki Susumu, Nemoto Tatsuya, Hirai Naoki (Osaka City University, Japan), Mario Basa, Hagiwara Akira, Niwa
Makoto, Mori Toru (Orkney Inc., Japan), and Hattori Norihiro (E-Solution Service, Inc., Japan).
• MapServer ticket:858
5.4.3 Requirements
The mapfile LABEL object’s parameter named ENCODING can be used to convert strings from its original encoding
system into one that can be understood by the True Type Fonts. The ENCODING parameter accepts the encoding
name as its parameter.
This uses GNU’s libiconv ( http://www.gnu.org/software/libiconv/ ) so theoretically, every string with an encoding
system supported by libiconv can be displayed as labels in MapServer as long as it has a matching font-set.
Execute ‘’mapserv -v’ at the commandline, and verify that your MapServer version >= 4.4.0 and it includes ‘’SUP-
PORTS=ICONV’‘, such as:
> mapserv -v
MapServer version 5.6.5 OUTPUT=GIF OUTPUT=PNG OUTPUT=JPEG OUTPUT=WBMP OUTPUT=PDF OUTPUT=SWF OUTPUT=
SUPPORTS=PROJ SUPPORTS=AGG SUPPORTS=FREETYPE SUPPORTS=ICONV SUPPORTS=FRIBIDI SUPPORTS=WMS_SERVER
SUPPORTS=WMS_CLIENT SUPPORTS=WFS_SERVER SUPPORTS=WFS_CLIENT SUPPORTS=WCS_SERVER SUPPORTS=SOS_SERVER
Since MapServer uses the libiconv library to handle encodings, you can check the list of supported encodings here:
http://www.gnu.org/software/libiconv/
Unix users can also use the iconv -l command on a system with libiconv installed to get the complete list of supported
encodings on that specific system.
Now you can simply add the ENCODING parameter to your mapfile LAYER object, such as:
MAP
...
LAYER
...
CLASS
...
LABEL
...
ENCODING "SHIFT_JIS"
END
END
END
END
One of the benefits of having an “ENCODING” parameter within the LABEL object is that different LAYERS with
different encoding systems can be combined together and display labels within a single map. For example, labels
from a Layer using Shapefile as it source which contains attributes in SHIFT-JIS can be combined with a Layer from
a PostGIS database server with EUC-JP attributes. A sample Mapfile can look like this:
LAYER
NAME "chimei"
DATA c h i m e i
STATUS DEFAULT
TYPE POINT
LABELITEM "NAMAE"
CLASS
NAME "CHIMEI"
STYLE
COLOR 10 100 100
END
LABEL
TYPE TRUETYPE
FONT k o c h i - g o t h i c
COLOR 220 20 20
SIZE 10
POSITION CL
PARTIALS FALSE
BUFFER 0
ENCODING S J I S
END
END
END
LAYER
NAME "chimeipg"
CONNECTION "user=username password=password dbname=gis host=localhost port=5432"
CONNECTIONTYPE postgis
DATA "the_geom from chimei"
STATUS DEFAULT
TYPE POINT
LABELITEM "NAMAE"
CLASS
NAME "CHIMEI PG"
STYLE
COLOR 10 100 100
END
LABEL
TYPE TRUETYPE
FONT k o c h i - m i n c h o
COLOR 20 220 20
SIZE 10
POSITION CL
PARTIALS FALSE
BUFFER 0
ENCODING E UC- J P
END
END
END
For PHP Mapscript, the Encoding parameter is included in the LabelObj Class, so that the encoding parameter of a
layer can be modified such as:
// Loading the php_mapscript library
dl("php_mapscript.so");
5.4.6 Notes
During initial implementation, this functionality was tested using the different Japanese encoding systems: Shift-JIS,
EUC-JP, UTF-8, as well as Thai’s TIS-620 encoding system.
5.5 Expressions
Contents
• Expressions
– Introduction
– Expression Types
– “MapServer expressions”
5.5.1 Introduction
As of version 4.6.1, expressions are used in two places. They’re used to filter layers for specific records in the dataset
and they’re used in CLASS EXPRESSIONs to specify to which items this CLASS does apply to.
Expression are used to match attribute values with certain logical checks. There are three different types of expressions
you can use with MapServer:
• String comparisons: A single attribute is compared with a string value.
• Regular expressions: A single attribute is matched with a regular expression.
• Logical “MapServer expressions”: One or more attributes are compared using logical expressions.
String comparison
String comparison means as the name suggests that attribute values are checked if they are equal to some value. String
comparison are the simplest form of MapServer expressions and the fastest option. To use a string comparison for
filtering a LAYER, both FILTERITEM and FILTER must be set. FILTERITEM is set to the attribute name. FILTER is
set to the value for comparison. The same rule applies to CLASSITEM and EXPRESSION in the CLASS object.
Example for a simple string comparison filter
FILTER "2005"
FILTERITEM "year"
would match all records that have the attribute “year” set to “2005”. The rendered map would appear as if the dataset
would only contain those items that have the “year” set to “2005”.
Similarly, a classification for the items matched above would be done by setting the CLASSITEM in the layer and the
EXPRESSION in the class
LAYER
NAME "example"
CLASSITEM "year"
...
CLASS
NAME "year-2005"
EXPRESSION "2005"
...
END
END
For a reason explained later on the values for both CLASSITEM and FILTERITEM should start neither with an ‘/’ nor
with a ‘(‘ character.
Regular expressions are a standard text pattern matching mechanism from the UNIX world. The functionality of regu-
lar expression matching is provided by the operating system on UNIX systems and therefore slightly operating system
dependent. However their minimum set of features are those defined by the POSIX standard. The documentation of
the particular regular expression library is usually in the “regex” manual page (“man regex”).
Regular expression with MapServer work similarly to string comparison, but allow more complex operation. They are
slower than pure string comparisons, but might be still faster than logical expression. As with the string comparison
use regular expressions, a FILTERITEM or a CLASSITEM has to defined, respectively.
A regular expression typically consists of characters with special meanings and characters that are interpreted as they
are. Alphanumeric characters (A-Z, a-z and 0-9) are taken as they are. Characters with special means are:
• . will match a single character
• [ and ] are used for grouping. For example [A-Z] would match the characters A,B,C,...,X,Y,Z.
• {, }, and * are used to specify how often something should match.
• ^ matches the beginning, $ matches the end of the value.
• The backslash \ is used to take away the special meaning. For example $ would match the dollar sign.
The following LAYER configuration would have all records rendered on the map that have “hotel” in the attribute
named “placename”
LAYER
NAME "regexp-example"
FILTERITEM "placename"
FILTER /hotel/
...
END
Note: The regular expression is case-sensitive, thus records having “Hotel” in them would not have matched.
Example: Match records that have a value for the current century (as of 2005 ;) in the attribute “year”
FILTERITEM "year"
FILTER /^20[0-9][0-9]/
Example: Match all the records that are either purely numerical or empty
FILTER /^[0-9]*$/
Note: If you experience frequently segmentation faults when working with MapServer and regular expressions, it
might be that your current working environment is linked against more than one regular expression library. This can
happen when MapServer is linked with components that bring their own copy, like the Apache httpd or PHP. In these
cases the author has made best experiences with making all those components using the regular expression library of
the operating system (i.e. the one in libc). That involved editing the build files of some of the components, however.
MapServer expressions are the most complex and depending how they are written can become quite slow. They can
match any of the attributes and thus allow filtering and classification depending on more than one attribute. Besides
pure logical operations there are also expressions allow also certain arithmetic, string- and time operations.
To be able to use a MapServer expression for a FILTER or EXPRESSION value, the expression has to be finally of a
logical value.
Logical expressions
Syntactically, a logical expression is everything encapsulated in round brackets. Logical expressions take logical
values as their input and return logical values. A logical expression is either ‘true’ or ‘false’.
• ( ( ... ) AND ( ... ) ) ( ( ... ) && ( ... ) ) ... will become true when both of the two logical expressions in the
innermost brackets are true.
• ( ( ... ) OR ( ... ) ) ( ( ... ) || ( ... ) ) ... will become true when at least one of the two logical expressions in the
innermost brackets is true.
• NOT ( ... ) ! ( ... ) ... will become true, when the logical expression in the brackets becomes false.
• ( “String1” > “String2” ) ( “String1” gt “String2” ) ... will become true when “String1” is lexicographically
larger than “String2”.
• ( “String1” <= “String2” ) ( “String1” le “String2” ) ... will become true when “String1” is not lexicographically
larger than “String2”
• ( “String1” >= “String2” ) ( “String1” ge “String2” ) ... will become true when “String1” is not lexicographically
smaller than “String2”.
• ( “String1” IN “token1,token2,...,tokenN” ) ... will become true when “String1” is in equal one of the given
tokens.
Note:
The separator for those tokens is the comma. That means that you must not add unnecessary white space
to the list and that you cannot compare to tokens that have a comma in it.
• ( “String1” =~ /regexp/ ) ... will become true, when “String1” matches the regular expression “regexp”. This
operation is identical to the regular expression matching described earlier.
There is only one operation for strings that returns a string value:
• “String1” + “String2 ... will return “String1String2”, thus the two string concatenated to each other.
The basic element for the arithmetic operation is the number. There are some purely arithmetic operations that are
returning numbers as their value. They will be covered in the next section.
• ( n1 eq n2 ) ( n1 == n2 ) ( n1 = n2 ) ... will become true when both numbers are equal.
• ( n1 != n2 ) ( n1 ne n2 ) ... will become true when both numbers are not equal.
• ( n1 < n2 ) ( n1 lt n2 ) ... will become true when n1 is smaller than n2
• ( n1 > n2 ) ( n1 gt n2 ) ... will become true when n1 is larger than n2.
• ( n1 <= n2 ) ( n1 le n2 ) ... will become true when n1 is smaller or equal n2
• ( n1 >= n2 ) ( n1 ge n2 ) ... will become true when n1 is larger or equal n2.
• ( n1 IN “number1,number2,...,numberN” ) ... will become true when n1 is equal to one of the given numbers.
As stated in the previous section, MapServer can do purely numerical operations with numbers.
• n1 + n2 ... will become the sum of n1 and n2
• n1 - n2 ... will become n2 subtracted from n1
• n1 * n2 ... will become n1 multiplicated with n2
• n1 / n2> ... will become n1 divided by n2
• -n1 ... will become n1 with negated sign
• n1 ^ n2 ... will become n1 by a power of n2
• length ( “String1” ) ... will become the number of characters of “String1”
Note: When the numerical operations above are used like logical operations, the following rule applies: values equal
to zero will be taken as ‘false’ and everything else will be ‘true’. That means the expression
:: ( 6 + 5 ) ...
would evaluate as true, but
( 5 - 5 )
...
Temporal expressions
MapServer uses an internal time type to do comparison. To convert a keys value into this time type it will check the
list below from the top down if the specified time matches and if so, it will do the conversion.
• YYYY-MM-DDTHH:MM:SSZ (‘Z’ and ‘T’ being the characters itself)</i>
• YYYY-MM-DDTHH:MM:SS (‘T’ being the character itself)</i>
• YYYY-MM-DD HH:MM:SS
• YYYY-MM-DDTHH:MM (‘T’ being the character itself)</i>
• YYYY-MM-DD HH:MM
• YYYY-MM-DDTHH (‘T’ being the character itself)</i>
• YYYY-MM-DD HH
• YYYY-MM-DD
• YYYY-MM
• YYYY
• THH:MM:SSZ (‘Z’ and ‘T’ being the characters itself)</i>
• THH:MM:SS
For temporal values obtained this way, the following operations are supported:
• ( n1 eq n2 ) ( n1 == n2 ) ( n1 = n2 ) ... will become true when both times are equal.
• ( t1 != t2 ) ( t1 ne t2 ) ... will become true when both times are not equal.
• ( t1 < t2 ) ( t1 lt t2 ) ... will become true when t1 is earlier than t2
• ( t1 > t2 ) ( t1 gt t2 ) ... will become true when t1 is later than t2.
• ( t1 <= t2 ) ( t1 le t2 ) ... will become true when t1 is earlier or same t2
• ( n1 >= n2 ) ( n1 ge n2 ) ... will become true when t1 is later or same t2.
To make a meaningful use of the expressions above, we need to get the attribute values into the expressions. That
is done by enclosing the attribute key into square brackets, like this: [KEY]. Then before the expression is evaluated
every occurrence of “[KEY]” will be replaced by the value for attribute “KEY”.
Example: how a simple string comparison would be evaluated. The filter is set to:
There is a attribute “BUILDING_NAME” and its value is “National Government Building”. Thus the expression
actually evaluated is...
"National Government Building" == "National Museum" )
Note: Quotes escaping is not supported in MapServer versions lower than 5.0.
Starting with MapServer 5.0, if your dataset contains double-quotes, you can use a C-like escape sequence in the
expression string. For example if your key “NAME” has the value ‘National “hero” statue’ you could write the
FILTER expression as follows:
FILTER ( "[NAME]" == "National \"hero\" statue" )
...
5.6 FEATURE
Note: POLYGON/POLYLINE layers POINTS must start and end with the same point (i.e. close the feature).
ITEMS Comma separated list of the feature attributes:
ITEMS "value1;value2;value3"
Note: Specifying the same number of items is recommended for each features of the same layer. The item names
should be specified as a PROCESSING option of the layer.
TEXT [string] String to use for labeling this feature.
WKT [string] A geometry expressed in OpenGIS Well Known Text geometry format. This feature is only supported
if MapServer is built with OGR or GEOS support.
WKT "POLYGON((500 500, 3500 500, 3500 2500, 500 2500, 500 500))"
WKT "POINT(2000 2500)"
Note: Inline features should be defined as their own layers in the mapfile. If another CONNECTIONTYPE is
specified in the same layer, MapServer will always use the inline features to draw the layer and ignore the other
CONNECTIONTYPEs.
5.7 FONTSET
Contents
• FONTSET
– Format
5.7.1 Format
The format is very simple. Each line contains 2 items: an alias and the name/path of the font separated by white space.
The alias is simply the name you refer to the font as in your Mapfile (eg. times-bold). The name is the actual name of
the TrueType file. If not full path then it is interpreted as relative to the location of the fontset. Here’s the fontset I use
(the font.list file and all .ttf files are stored in the same sub-directory).
Note: Aliases are case sensitive. Excellent reference information about the TrueType format and online font resources
is available from the FreeType.
arial arial.ttf
arial-bold arialbd.ttf
arial-italic ariali.ttf
arial-bold-italic arialbi.ttf
arial_black ariblk.ttf
comic_sans comic.ttf
comic_sans-bold comicbd.ttf
courier cour.ttf
courier-bold courbd.ttf
courier-italic couri.ttf
courier-bold-italic courbi.ttf
georgia georgia.ttf
georgia-bold georgiab.ttf
georgia-italic georgiai.ttf
georgia-bold-italic georgiaz.ttf
impact impact.ttf
monotype.com monotype.ttf
recreation_symbols recreate.ttf
times times.ttf
times-bold timesbd.ttf
times-italic timesi.ttf
times-bold-italic timesbi.ttf
trebuchet_ms trebuc.ttf
trebuchet_ms-bold trebucbd.ttf
trebuchet_ms-italic trebucit.ttf
trebuchet_ms-bold-italic trebucbi.ttf
verdana verdana.ttf
verdana-bold verdanab.ttf
verdana-italic verdanai.ttf
verdana-bold-italic verdanaz.ttf
5.8 GRID
LABELFORMAT [DD|DDMM|DDMMSS|C format string] Format of the label. “DD” for degrees, “DDMM” for
degrees minutes, and “DDMMSS” for degrees, minutes, seconds. A C-style formatting string is also allowed,
such as “%g°” to show decimal degrees with a degree symbol. The default is decimal display of whatever SRS
you’re rendering the GRID with.
MINARCS [double] The minimum number of arcs to draw. Increase this parameter to get more lines. Optional.
MAXARCS [double] The maximum number of arcs to draw. Decrease this parameter to get fewer lines. Optional.
MININTERVAL [double] The minimum number of intervals to try to use. The distance between the grid lines, in
the units of the grid’s coordinate system. Optional.
MAXINTERVAL [double] The maximum number of intervals to try to use. The distance between the grid lines, in
the units of the grid’s coordinate system. Optional.
MINSUBDIVIDE [double] The minimum number of segments to use when rendering an arc. If the lines should be
very curved, use this to smooth the lines by adding more segments. Optional.
MAXSUBDIVIDE [double] The maximum number of segments to use when rendering an arc. If the graticule should
be very straight, use this to minimize the number of points for faster rendering. Optional, default 256.
The following is an example of a GRID object in use:
LAYER
NAME "grid"
METADATA
"DESCRIPTION" "Grid"
END
TYPE LINE
STATUS ON
CLASS
NAME "Graticule"
COLOR 0 0 0
LABEL
COLOR 255 0 0
FONT "fritqat"
TYPE truetype
SIZE 8
POSITION AUTO
PARTIALS FALSE
BUFFER 5
OUTLINECOLOR 255 255 255
END
END
PROJECTION
"init=epsg:4326"
END
GRID
LABELFORMAT "DDMM"
# LABELFORMAT ’%g°’ # dec degrees with symbol
MAXARCS 10
MAXINTERVAL 10
MAXSUBDIVIDE 2
5.9 INCLUDE
When this directive is encountered parsing switches to the included file immediately. As a result the included file can
be comprised of any valid mapfile syntax. For example:
INCLUDE ’myLayer.map’
Performance does not seem to be seriously impacted with limited use, however in high performance instances you
may want to use includes in a pre-processing step to build a production mapfile. The C pre-processor can also be used
(albeit with a different syntax) and is far more powerful.
5.9.1 Notes
5.9.2 Example
MAP
NAME "include_mapfile"
EXTENT 0 0 500 500
SIZE 250 250
INCLUDE "test_include_symbols.map"
INCLUDE "test_include_layer.map"
END
5.10 JOIN
5.10.1 Description
Joins are defined within a LAYER object. It is important to understand that JOINs are ONLY available once a query
has been processed. You cannot use joins to affect the look of a map. The primary purpose is to enable lookup tables
for coded data (e.g. 1 => Forest) but there are other possible uses.
• DBF/XBase files
• CSV (comma delimited text file)
• PostgreSQL and PostGIS tables
• MySQL tables
CONNECTION [string] Parameters required for the join table’s database connection (not required for DBF or CSV
joins). The following is an example connection for PostgreSQL:
CONNECTION "host=127.0.0.1 port=5432 user=postgres password=postgres dbname=somename"
CONNECTIONTYPE OGR
CONNECTION "MYSQL:mydbname,user=root,password=mysql,port=3306"
CONNECTIONTYPE OGR
CONNECTIONTYPE [string] Type of connection (not required for DBF or CSV joins). For PostgreSQL and
MySQL connections use ‘OGR’.
FOOTER [filename] Template to use after a layer’s set of results have been sent. In other words, this header HTML
will be displayed after the contents of the TEMPLATE HTML.
FROM [item] Join item in the dataset. This is case sensitive.
HEADER [filename] Template to use before a layer’s set of results have been sent. In other words, this header HTML
will be displayed before the contents of the TEMPLATE HTML.
NAME [string] Unique name for this join. Required.
TABLE [filename|tablename] For file-based joins this is the name of XBase or comma delimited file (relative to
the location of the mapfile) to join TO. For PostgreSQL and MySQL support this is the name of the Post-
greSQL/MySQL table to join TO.
TEMPLATE [filename] Template to use with one-to-many joins. The template is processed once for each record
and can only contain substitutions for items in the joined table. Refer to the column in the joined table in your
template like [joinname_columnname], where joinname is the NAME specified for the JOIN object.
TO [item] Join item in the table to be joined. This is case sensitive.
TYPE [ONE-TO-ONE|ONE-TO-MANY] The type of join. Default is one-to-one.
Mapfile Layer
LAYER
NAME "prov_bound"
TYPE POLYGON
STATUS DEFAULT
DATA "prov.shp"
CLASS
NAME "Province"
STYLE
OUTLINECOLOR 120 120 120
COLOR 255 255 0
END
END
TEMPLATE "../htdocs/cgi-query-templates/prov.html"
HEADER "../htdocs/cgi-query-templates/prov-header.html"
FOOTER "../htdocs/cgi-query-templates/footer.html"
JOIN
NAME "test"
TABLE "../data/lookup.dbf"
FROM "ID"
TO "IDENT"
TYPE ONE-TO-ONE
END
END # layer
Ogrinfo
Template
Mapfile Layer
LAYER
NAME "prov_bound"
TYPE POLYGON
STATUS DEFAULT
DATA "prov.shp"
CLASS
NAME "Province"
STYLE
OUTLINECOLOR 120 120 120
COLOR 255 255 0
END
END
TOLERANCE 20
TEMPLATE "../htdocs/cgi-query-templates/prov.html"
HEADER "../htdocs/cgi-query-templates/prov-header.html"
FOOTER "../htdocs/cgi-query-templates/footer.html"
JOIN
NAME "test"
CONNECTION "host=127.0.0.1 port=5432 user=postgres password=postgres dbname=join"
CONNECTIONTYPE ogr
TABLE "lookup"
FROM "ID"
TO "ident"
TYPE ONE-TO-ONE
END
END # layer
Ogrinfo
Template
Note: When testing with MapServer 4.10.0 on Windows this postgresql join caused a mapserv.exe crash. However
when testing this with a MapServer build > 4.10.0 the crash did not occur.
Mapfile Layer
LAYER
NAME "prov_bound"
TYPE POLYGON
STATUS DEFAULT
DATA "prov.shp"
CLASS
NAME "Province"
STYLE
OUTLINECOLOR 120 120 120
COLOR 255 255 0
END
END
TOLERANCE 20
TEMPLATE "../htdocs/cgi-query-templates/prov.html"
HEADER "../htdocs/cgi-query-templates/prov-header.html"
FOOTER "../htdocs/cgi-query-templates/footer.html"
JOIN
NAME "test"
TABLE "../data/lookup.csv"
FROM "ID"
TO "IDENT"
TYPE ONE-TO-ONE
END
END # layer
"IDENT","VAL"
1,12
2,11
3,10
4,9
5,8
6,7
7,6
8,5
9,4
10,3
11,2
12,1
Ogrinfo
Template
Mapfile Layer
LAYER
NAME "prov_bound"
TYPE POLYGON
STATUS DEFAULT
DATA "prov.shp"
CLASS
NAME "Province"
STYLE
OUTLINECOLOR 120 120 120
COLOR 255 255 0
END
END
TOLERANCE 20
TEMPLATE "../htdocs/cgi-query-templates/prov.html"
HEADER "../htdocs/cgi-query-templates/prov-header.html"
FOOTER "../htdocs/cgi-query-templates/footer.html"
JOIN
NAME "test"
CONNECTION "MYSQL:test,user=root,password=mysql,port=3306"
CONNECTIONTYPE ogr
TABLE "lookup"
FROM "ID"
TO "ident"
TYPE ONE-TO-ONE
END
END # layer
Ogrinfo
Template
Note: When testing with MapServer 5.6.5 and MySQL 5.1.49 on Windows this MySQL join caused a mapserv.exe
crash.
5.11 LABEL
ALIGN [left|center|right] Since version 5.4 . Specifies text alignment for multiline labels (see WRAP) Note that
the alignment algorithm is far from precise, so don’t expect fabulous results (especially for right alignment) if
you’re not using a fixed width font.
ANGLE [double|auto|follow|attribute]
• Angle, given in degrees, to draw the label.
• AUTO allows MapServer to compute the angle. Valid for LINE layers only.
• FOLLOW was introduced in version 4.10 and tells MapServer to compute a curved label for appropriate
linear features (see MS RFC 11: Support for Curved Labels for specifics).
• [Attribute] was introduced in version 5.0, to specify the item name in the attribute table to use for an-
gle values. The hard brackets [] are required. For example, if your shapefile’s DBF has a field named
“MYANGLE” that holds angle values for each record, your LABEL object might contain:
LABEL
COLOR 150 150 150
OUTLINECOLOR 255 255 255
FONT "sans"
TYPE truetype
SIZE 6
ANGLE [ M Y ANGLE]
POSITION AUTO
PARTIALS FALSE
END
The associated RFC document for this feature is MS RFC 19: Style & Label attribute binding.
ANTIALIAS [true|false] Should text be antialiased? Note that this requires more available colors, decreases drawing
performance, and results in slightly larger output images. Only useful for GD (gif) rendering. Default is false.
Has no effect for the other renderers (where anti-aliasing can not be turned off).
BACKGROUNDCOLOR [r] [g] [b] Color to draw a background rectangle (i.e. billboard). Off by default. Depre-
cated since version 6.0: Use STYLE object and GEOMTRANSFORM labelpoly.
BACKGROUNDSHADOWCOLOR [r] [g] [b] Color to draw a background rectangle (i.e. billboard) shadow. Off
by default. Deprecated since version 6.0: Use STYLE object and GEOMTRANSFORM labelpoly.
BACKGROUNDSHADOWSIZE [x][y] How far should the background rectangle be offset? Default is 1. Depre-
cated since version 6.0: Use STYLE object and GEOMTRANSFORM labelpoly.
BUFFER [integer] Padding, in pixels, around labels. Useful for maintaining spacing around text to enhance read-
ability. Available only for cached labels. Default is 0.
COLOR [r] [g] [b] | [attribute]
• Color to draw text with.
• [Attribute] was introduced in version 5.0, to specify the item name in the attribute table to use for color
values. The hard brackets [] are required. For example, if your shapefile’s DBF has a field named “MY-
COLOR” that holds color values for each record, your LABEL object might contain:
LABEL
COLOR [ M Y COLOR]
OUTLINECOLOR 255 255 255
FONT "sans"
TYPE truetype
SIZE 6
POSITION AUTO
PARTIALS FALSE
END
The associated RFC document for this feature is MS RFC 19: Style & Label attribute binding.
ENCODING [string] Supported encoding format to be used for labels. If the format is not supported, the label will
not be drawn. Requires the iconv library (present on most systems). The library is always detected if present on
the system, but if not the label will not be drawn.
Required for displaying international characters in MapServer. More information can be found in the Label
Encoding document.
FONT [name|attribute]
• Font alias (as defined in the FONTSET) to use for labeling.
PARTIALS FALSE
END
The associated RFC document for this feature is MS RFC 19: Style & Label attribute binding.
OUTLINEWIDTH [integer] Width of the outline if OUTLINECOLOR has been set. Defaults to 1. Currently only
the AGG renderer supports values greater than 1, and renders these as a ‘halo’ effect: recommended values are
3 or 5.
PARTIALS [true|false] Can text run off the edge of the map? Default is true.
POSITION [ul|uc|ur|cl|cc|cr|ll|lc|lr|auto] Position of the label relative to the labeling point (layers only). First letter
is “Y” position, second letter is “X” position. “Auto” tells MapServer to calculate a label position that will not
interfere with other labels. With points, MapServer selects from the 8 outer positions (i.e. excluding cc). With
polygons, MapServer selects from cc (added in MapServer 5.4), uc, lc, cl and cr as possible positions. With
lines, it only uses lc or uc, until it finds a position that doesn’t collide with labels that have already been drawn.
If all positions cause a conflict, then the label is not drawn (Unless the label’s FORCE a parameter is set to
“true”). “Auto” placement is only available with cached labels.
PRIORITY [integer]|[item_name]|[attribute] The priority parameter (added in v5.0) takes an integer value between
1 (lowest) and 10 (highest). The default value is 1. It is also possible to bind the priority to an attribute
(item_name) using square brackets around the [item_name]. e.g. “PRIORITY [someattribute]”
Labels are stored in the label cache and rendered in order of priority, with the highest priority levels rendered
first. Specifying an out of range PRIORITY value inside a map file will result in a parsing error. An out of range
value set via MapScript or coming from a shape attribute will be clamped to the min/max values at rendering
time. There is no expected impact on performance for using label priorities.
[Attribute] was introduced in version 5.6.
REPEATDISTANCE [integer]
• Introduced in version 5.6. The label will be repeated on every line of a multiline shape and will be repeated
multiple times along a given line at an interval of REPEATDISTANCE pixels.
The associated RFC document for this feature is MS RFC 57: Labeling enhancements: ability to repeat
labels along a line/multiline.
SHADOWCOLOR [r] [g] [b] Color of drop shadow. An label with the same text will be rendered in this color before
the main label is drawn, resulting in a shadow effect on the the label characters. The offset of the renderered
shadow is set with SHADOWSIZE.
SHADOWSIZE [x][y]|[attribute][attribute]|[x][attribute]|[attribute][y] Shadow offset in pixels, see SHADOW-
COLOR.
[Attribute] was introduced in version 6.0, and can be used like:
SHADOWSIZE 2 2
SHADOWSIZE [ s h a d o w s i z e X ] 2
SHADOWSIZE 2 [ s h a d o w s i z e Y ]
SHADOWSIZE [shadowsize] [shadowsize]
SIZE [double]|[tiny|small|medium|large|giant]|[attribute]
• Text size. Use “integer” to give the size in pixels of your TrueType font based label, or any of the other 5
listed keywords to bitmap fonts.
• Starting from version 5.4, the value can also be a fractional value (and not only integer).
• [Attribute] was introduced in version 5.0, to specify the item name in the attribute table to use for size val-
ues. The hard brackets [] are required. For example, if your shapefile’s DBF has a field named “MYSIZE”
that holds size values for each record, your LABEL object might contain:
LABEL
COLOR 150 150 150
OUTLINECOLOR 255 255 255
FONT "sans"
TYPE truetype
SIZE [ M Y SIZE]
POSITION AUTO
PARTIALS FALSE
END
The associated RFC document for this feature is MS RFC 19: Style & Label attribute binding.
STYLE The start of a STYLE object.
Label specific mechanisms of the STYLE object are the GEOMTRANSFORM options:
GEOMTRANSFORM [labelpnt|labelpoly] Creates geometries that can be used for styling the label.
• labelpnt generates a point with its center at the middle of the bounding rectangle of the text.
• labelpoly generates the bounding rectangle for the text, with 1 pixel of padding added in all directions.
The resulting geometries can be styled using the mechanisms available in the STYLE object.
New in version 6.0.
TYPE [bitmap|truetype] Type of font to use. Generally bitmap fonts are faster to draw then TrueType fonts. How-
ever, TrueType fonts are scalable and available in a variety of faces. Be sure to set the FONT parameter if you
select TrueType.
Note that bitmap fonts are only supported with the AGG and GD renderers.
WRAP [character] Character that represents an end-of-line condition in label text, thus resulting in a multi-line label.
Interacts with MAXLENGTH for conditional line wrapping after a given number of characters
5.12 LAYER
A PostGIS connection string is basically a regular PostgreSQL connection string, it takes the form of
“user=nobody password=****** dbname=dbname host=localhost port=5432”
An Oracle connection string: user/pass[@db]
See Also:
See Vector Data for specific connection information for various data sources.
CONNECTIONTYPE [local|sde|ogr|postgis|oraclespatial|wms|wfs|plugin|union] Type of connection. Default is
local. See additional documentation for any other type.
See Also:
See Vector Data for specific connection information for various data sources. See Union Layer for combining
layers, added in MapServer 6.0
Note: mygis is another connectiontype, but it is deprecated; please see the MySQL section of the Vector Data
document for connection details.
DATA [filename]|[sde parameters][postgis table/column][oracle table/column] Full filename of the spatial data to
process. No file extension is necessary for shapefiles. Can be specified relative to the SHAPEPATH option from
the Map Object.
If this is an SDE layer, the parameter should include the name of the layer as well as the geometry column, i.e.
“mylayer,shape,myversion”.
If this is a PostGIS layer, the parameter should be in the form of “<columnname> from <tablename>”, where
“columnname” is the name of the column containing the geometry objects and “tablename” is the name of the
table from which the geometry data will be read.
For Oracle, use “shape FROM table” or “shape FROM (SELECT statement)” or even more complex Oracle
compliant queries! Note that there are important performance impacts when using spatial subqueries however.
Try using MapServer’s FILTER whenever possible instead. You can also see the SQL submitted by forcing an
error, for instance by submitting a DATA parameter you know won’t work, using for example a bad column
name.
See Also:
See Vector Data for specific connection information for various data sources.
DEBUG [off|on|0|1|2|3|4|5] Enables debugging of a layer in the current map.
Debugging with MapServer versions >= 5.0:
Verbose output is generated and sent to the standard error output (STDERR) or the MapServer errorfile if one
is set using the “MS_ERRORFILE” environment variable. You can set the environment variable by using the
CONFIG parameter at the MAP level of the mapfile, such as:
CONFIG "MS_ERRORFILE" "/ms4w/tmp/ms_error.txt"
You can also set the environment variable in Apache by adding the following to your httpd.conf:
SetEnv MS_ERRORFILE "/ms4w/tmp/ms_error.txt"
Once the environment variable is set, the DEBUG mapfile parameter can be used to control the level of debug-
ging output. Here is a description of the possible DEBUG values:
• DEBUG O or OFF - only msSetError() calls are logged to MS_ERRORFILE. No msDebug() output at
all. This is the default and corresponds to the original behavior of MS_ERRORFILE in MapServer 4.x
• DEBUG 1 or ON - includes all output from DEBUG 0 plus msDebug() warnings about common pitfalls,
failed assertions or non-fatal error situations (e.g. missing or invalid values for some parameters, missing
shapefiles in tileindex, timeout error from remote WMS/WFS servers, etc.)
• DEBUG 2 - includes all output from DEBUG 1 plus notices and timing information useful for tuning
mapfiles and applications
• DEBUG 3 - all of DEBUG 2 plus some debug output useful in troubleshooting problems such as WMS
connection URLs being called, database connection calls, etc. This is the recommended level for debug-
ging mapfiles.
• DEBUG 4 - DEBUG 3 plus even more details...
• DEBUG 5 - DEBUG 4 plus any msDebug() output that might be more useful to the developers than to the
users.
You can also set the debug level by using the “MS_DEBUGLEVEL” environment variable.
The DEBUG setting can also be specified for the entire map, by setting the DEBUG parameter in the MAP
object.
For more details on this debugging mechanism, please see MS RFC 28: Redesign of LOG/DEBUG output
mechanisms.
Debugging with MapServer versions < 5:
Verbose output is generated and sent to the standard error output (STDERR) or the MapServer logfile if one is
set using the LOG parameter in the WEB object. Apache users will see timing details for drawing in Apache’s
error_log file. Requires MapServer to be built with the DEBUG=MSDEBUG option (–with-debug configure
option).
DUMP [true|false] Switch to allow MapServer to return data in GML format. Useful when used with WMS GetFea-
tureInfo operations. “false” by default.
EXTENT [minx] [miny] [maxx] [maxy] The spatial extent of the data. In most cases you will not need to specify
this, but it can be used to avoid the speed cost of having MapServer compute the extents of the data. An
application can also possibly use this value to override the extents of the map.
FEATURE Signals the start of a FEATURE object.
FILTER [string] This parameter allows for data specific attribute filtering that is done at the same time spatial filter-
ing is done, but before any CLASS expressions are evaluated. For OGR and shapefiles the string is simply a
mapserver regular expression. For spatial databases the string is a SQL WHERE clause that is valid with respect
to the underlying database.
For example: FILTER ([type]=’road’ and [size]<2)
FILTERITEM [attribute] Item to use with simple FILTER expressions. OGR and shapefiles only.
FOOTER [filename] Template to use after a layer’s set of results have been sent. Multiresult query modes only.
GRID Signals the start of a GRID object.
GROUP [name] Name of a group that this layer belongs to. The group name can then be reference as a regular layer
name in the template files, allowing to do things like turning on and off a group of layers at once.
HEADER [filename] Template to use before a layer’s set of results have been sent. Multiresult query modes only.
JOIN Signals the start of a JOIN object.
LABELANGLEITEM [attribute] (As of MapServer 5.0 this parameter is no longer available. Please see the LABEL
object’s ANGLE parameter) For MapServer versions < 5.0, this is the item name in attribute table to use for
class annotation angles. Values should be in degrees. Deprecated since version 5.0.
LABELCACHE [on|off] Specifies whether labels should be drawn as the features for this layer are drawn, or whether
they should be cached and drawn after all layers have been drawn. Default is on. Label overlap removal, auto
placement etc... are only available when the label cache is active.
LABELITEM [attribute] Item name in attribute table to use for class annotation (i.e. labeling).
LABELMAXSCALEDENOM [double] Minimum scale at which this LAYER is labeled. Scale is given as the
denominator of the actual scale fraction, for example for a map at a scale of 1:24,000 use 24000. Implemented
in MapServer 5.0, to replace the deprecated LABELMAXSCALE parameter.
See Also:
Map Scale
LABELMAXSCALE [double] - deprecated Since MapServer 5.0 the proper parameter to use is LABELMAXS-
CALEDENOM instead. The deprecated LABELMAXSCALE is the minimum scale at which this LAYER is
labeled. Scale is given as the denominator of the actual scale fraction, for example for a map at a scale of
1:24,000 use 24000. Deprecated since version 5.0.
LABELMINSCALEDENOM [double] Maximum scale at which this LAYER is labeled. Scale is given as the de-
nominator of the actual scale fraction, for example for a map at a scale of 1:24,000 use 24000. Implemented in
MapServer 5.0, to replace the deprecated LABELMINSCALE parameter.
See Also:
Map Scale
LABELMINSCALE [double] - deprecated Since MapServer 5.0 the proper parameter to use is LABELMIN-
SCALEDENOM instead. The deprecated LABELMINSCALE is the maximum scale at which this LAYER
is labeled. Scale is given as the denominator of the actual scale fraction, for example for a map at a scale of
1:24,000 use 24000. Deprecated since version 5.0.
LABELREQUIRES [expression] Sets context for labeling this layer, for example:
LABELREQUIRES "![orthoquads]"
means that this layer would NOT be labeled if a layer named “orthoquads” is on. The expression consists of
a boolean expression based on the status of other layers, each [layer name] substring is replaced by a 0 or a 1
depending on that layer’s STATUS and then evaluated as normal. Logical operators AND and OR can be used.
LABELSIZEITEM [attribute] (As of MapServer 5.0 this parameter is no longer available. Please see the LABEL
object’s SIZE parameter) For MapServer versions < 5.0, this is the item name in attribute table to use for class
annotation sizes. Values should be in pixels. Deprecated since version 5.0.
MAXFEATURES [integer] Specifies the number of features that should be drawn for this layer in the CURRENT
window. Has some interesting uses with annotation and with sorted data (i.e. lakes by area).
MAXGEOWIDTH [double] Maximum width, in the map’s geographic units, at which this LAYER is drawn. If
MAXSCALEDENOM is also specified then MAXSCALEDENOM will be used instead. (added in MapServer
5.4.0)
The width of a map in geographic units can be found by calculating the following from the extents:
[maxx] - [minx]
MAXSCALEDENOM [double] Minimum scale at which this LAYER is drawn. Scale is given as the denominator
of the actual scale fraction, for example for a map at a scale of 1:24,000 use 24000. Implemented in MapServer
5.0, to replace the deprecated MAXSCALE parameter.
See Also:
Map Scale
MAXSCALE [double] - deprecated Since MapServer 5.0 the proper parameter to use is MAXSCALEDENOM in-
stead. The deprecated MAXSCALE is the minimum scale at which this LAYER is drawn. Scale is given as the
denominator of the actual scale fraction, for example for a map at a scale of 1:24,000 use 24000. Deprecated
since version 5.0.
METADATA This keyword allows for arbitrary data to be stored as name value pairs. This is used with OGC WMS
to define things such as layer title. It can also allow more flexibility in creating templates, as anything you put
in here will be accessible via template tags.
Example:
METADATA
title "My layer title"
author "Me!"
END
MINGEOWIDTH [double] Minimum width, in the map’s geographic units, at which this LAYER is drawn. If
MINSCALEDENOM is also specified then MINSCALEDENOM will be used instead. (added in MapServer
5.4.0)
The width of a map in geographic units can be found by calculating the following from the extents:
[maxx] - [minx]
MINSCALEDENOM [double] Maximum scale at which this LAYER is drawn. Scale is given as the denominator
of the actual scale fraction, for example for a map at a scale of 1:24,000 use 24000. Implemented in MapServer
5.0, to replace the deprecated MINSCALE parameter.
See Also:
Map Scale
MINSCALE [double] - deprecated Since MapServer 5.0 the proper parameter to use is MINSCALEDENOM in-
stead. The deprecated MINSCALE is the maximum scale at which this LAYER is drawn. Scale is given as the
denominator of the actual scale fraction, for example for a map at a scale of 1:24,000 use 24000. Deprecated
since version 5.0.
NAME [string] Short name for this layer. Limit is 20 characters. This name is the link between the mapfile and web
interfaces that refer to this name. They must be identical. The name should be unique, unless one layer replaces
another at different scales. Use the GROUP option to associate layers with each other.
OFFSITE [r] [g] [b] Sets the color index to treat as transparent for raster layers.
OPACITY [integer|alpha] Sets the opacity level (or the inability to see through the layer) of all classed pixels for
a given layer. The value can either be an integer in the range (0-100) or the named symbol “ALPHA”. A
value of 100 is opaque and 0 is fully transparent. Implemented in MapServer 5.0, to replace the deprecated
TRANSPARENCY parameter.
The “ALPHA” symbol directs the MapServer rendering code to honor the indexed or alpha transparency of
pixmap symbols used to style a layer. This is only needed in the case of RGB output formats, and should be
used only when necessary as it is expensive to render transparent pixmap symbols onto an RGB map image.
PLUGIN [filename] Additional library to load by MapServer, for this layer. This is commonly used to load specific
support for SDE and Microsoft SQL Server layers, such as:
CONNECTIONTYPE PLUGIN
CONNECTION "hostname,port:xxx,database,username,password"
PLUGIN "C:/ms4w/Apache/specialplugins/msplugin_sde_92.dll"
DATA "layername,geometrycolumn,SDE.DEFAULT"
POSTLABELCACHE [true|false] Tells MapServer to render this layer after all labels in the cache have been drawn.
Useful for adding neatlines and similar elements. Default is false.
PROCESSING [string] Passes a processing directive to be used with this layer. The supported processing directives
vary by layer type, and the underlying driver that processes them.
• Attributes Directive - The ITEMS processing option allows to specify the name of attributes for inline
layers or specify the subset of the attributes to be used by the layer, such as:
PROCESSING "ITEMS=itemname1,itemname2,itemname3"
• Connection Pooling Directive - This is where you can enable connection pooling for certain layer layer
types. Connection pooling will allow MapServer to share the handle to an open database or layer con-
nection throughout a single map draw process. Additionally, if you have FastCGI enabled, the connection
handle will stay open indefinitely, or according to the options specified in the FastCGI configuration.
Oracle Spatial, ArcSDE, OGR and PostGIS/PostgreSQL currently support this approach.
PROCESSING "CLOSE_CONNECTION=DEFER"
• OGR Styles Directive - This directive can be used for obtaining label styles through MapScript. For more
information see the MapServer’s OGR document.
PROCESSING "GETSHAPE_STYLE_ITEMS=all"
• Raster Directives - All raster processing options are described in Raster Data. Here we see the SCALE
and BANDs directives used to autoscale raster data and alter the band mapping.
PROCESSING "SCALE=AUTO"
PROCESSING "BANDS=3,2,1"
• MapServer CLASS definition - By specifying the entire CLASS instead of a single style allows to use
further options (like setting expressions, label attributes, multiple styles) on a per feature basis.
• OGR Style String - MapServer support rendering the OGR style string format according to the OGR -
Feature Style Specification documentation. Currently only a few data sources support storing the styles
along with the features (like MapInfo, AutoCAD DXF, Microstation DGN), however those styles can
easily be transferred to many other data sources as a separate attribute by using the ogr2ogr command line
tool as follows:
We can specify the value: “AUTO” in order to have the driver to retrieve the style information. Currently
only the OGR driver supports the “AUTO” setting,
SYMBOLSCALEDENOM [double] The scale at which symbols and/or text appear full size. This allows for dy-
namic scaling of objects based on the scale of the map. If not set then this layer will always appear at the
same size. Scaling only takes place within the limits of MINSIZE and MAXSIZE as described above. Scale is
given as the denominator of the actual scale fraction, for example for a map at a scale of 1:24,000 use 24000.
Implemented in MapServer 5.0, to replace the deprecated SYMBOLSCALE parameter.
See Also:
Map Scale
SYMBOLSCALE [double] - deprecated Since MapServer 5.0 the proper parameter to use is SYMBOLSCALEDE-
NOM instead. The deprecated SYMBOLSCALE is the scale at which symbols and/or text appear full size. This
allows for dynamic scaling of objects based on the scale of the map. If not set then this layer will always appear
at the same size. Scaling only takes place within the limits of MINSIZE and MAXSIZE as described above.
Scale is given as the denominator of the actual scale fraction, for example for a map at a scale of 1:24,000 use
24000. Deprecated since version 5.0.
TEMPLATE [file|url] Used as a global alternative to CLASS TEMPLATE.
TILEINDEX [filename|layername] Name of the tileindex file or layer. A tileindex is similar to an ArcInfo library
index. The tileindex contains polygon features for each tile. The item that contains the location of the tiled data
is given using the TILEITEM parameter. When a file is used as the tileindex for shapefile or raster layers, the
tileindex should be a shapefile. For CONNECTIONTYPE OGR layers, any OGR supported datasource can be
a tileindex. Normally the location should contain the path to the tile file relative to the shapepath, not relative to
the tileindex itself. If the DATA parameter contains a value then it is added to the end of the location. When a
tileindex layer is used, it works similarly to directly referring to a file, but any supported feature source can be
used (ie. postgres, oracle).
Note: All files in the tileindex should have the same coordinate system, and for vector files the same set of
attributes in the same order.
TILEITEM [attribute] Item that contains the location of an individual tile, default is “location”.
TOLERANCE [double] Sensitivity for point based queries (i.e. via mouse and/or map coordinates). Given in TOL-
ERANCEUNITS. If the layer is a POINT or a LINE, the default is 3. For all other layer types, the default is 0.
To restrict polygon searches so that the point must occur in the polygon set the tolerance to zero.
TOLERANCEUNITS [pixels|feet|inches|kilometers|meters|miles|nauticalmiles|dd] Units of the TOLERANCE
value. Default is pixels. Nauticalmiles was added in MapServer 5.6.
TRANSPARENCY [integer|alpha] - deprecated Since MapServer 5.0 the proper parameter to use is OPACITY.
The deprecated TRANSPARENCY parameter sets the transparency level of all classed pixels for a given layer.
The value can either be an integer in the range (0-100) or the named symbol “ALPHA”. Although this parameter
is named “transparency”, the integer values actually parameterize layer opacity. A value of 100 is opaque and 0
is fully transparent.
The “ALPHA” symbol directs the MapServer rendering code to honor the indexed or alpha transparency of
pixmap symbols used to style a layer. This is only needed in the case of RGB output formats, and should be
used only when necessary as it is expensive to render transparent pixmap symbols onto an RGB map image.
Deprecated since version 5.0.
See Also:
OPACITY
TRANSFORM [true|false ul|uc|ur|lc|cc|lr|ll|lc|lr] Tells MapServer whether or not a particular layer needs to be
transformed from some coordinate system to image coordinates. Default is true. This allows you to create
shapefiles in image/graphics coordinates and therefore have features that will always be displayed in the same
location on every map. Ideal for placing logos or text in maps. Remember that the graphics coordinate system
has an origin in the upper left hand corner of the image, contrary to most map coordinate systems.
Version 4.10 introduces the ability to define features with coordinates given in pixels (or percentages, see
UNITS), most often inline features, relative to something other than the UL corner of an image. That is what
‘TRANSFORM FALSE’ means. By setting an alternative origin it allows you to anchor something like a copy-
right statement to another portion of the image in a way that is independent of image size.
TYPE [point|line|polygon|circle|annotation|raster|query|chart] Specifies how the data should be drawn. Need not
be the same as the shapefile type. For example, a polygon shapefile may be drawn as a point layer, but a point
shapefile may not be drawn as a polygon layer. Common sense rules. Annotation means that a label point
will be calculated for the features, but the feature itself will not be drawn although a marker symbol can be
optionally drawn. this allows for advanced labeling like numbered highway shields. Points are labeled at that
point. Polygons are labeled first using a centroid, and if that doesn’t fall in the polygon a scanline approach
is used to guarantee the label falls within the feature. Lines are labeled at the middle of the longest arc in the
visible portion of the line. Query only means the layer can be queried but not drawn.
In order to differentiate between POLYGONs and POLYLINEs (which do not exist as a type), simply respec-
tively use or omit the COLOR keyword when classifying. If you use it, it’s a polygon with a fill color, otherwise
it’s a polyline with only an OUTLINECOLOR.
A circle must be defined by a a minimum bounding rectangle. That is, two points that define the smallest square
that can contain it. These two points are the two opposite corners of said box.
The following is an example using inline points to draw a circle:
LAYER
NAME ’inline_circles’
TYPE CIRCLE
STATUS ON
FEATURE
POINTS
74.01 -53.8
110.7 -22.16
END
END
CLASS
STYLE
COLOR 0 0 255
END
END
END
See Also:
For CHART layers, see the Dynamic Charting HowTo.
UNITS [feet|inches|kilometers|meters|miles|nauticalmiles|dd|pixels|percentages] Units of the layer. Percentages
was added in MapServer 4.10 and is mostly geared for inline features. Nauticalmiles was added in MapServer
5.6.
5.13 LEGEND
The size of the legend image is NOT known prior to creation so be careful not to hard-code width and height in the
<IMG> tag in the template file.
IMAGECOLOR [r] [g] [b] Color to initialize the legend with (i.e. the background).
INTERLACE [on|off] Default is [on]. This keyword is now deprecated in favor of using the FORMATOPTION
“INTERLACE=ON” line in the OUTPUTFORMAT declaration. Deprecated since version 4.6.
LABEL Signals the start of a LABEL object
OUTLINECOLOR [r] [g] [b] Color to use for outlining symbol key boxes.
POSITION [ul|uc|ur|ll|lc|lr] Where to place an embedded legend in the map. Default is lr.
KEYSIZE [x][y] Size of symbol key boxes in pixels. Default is 20 by 10.
KEYSPACING [x][y] Spacing between symbol key boxes ([y]) and labels ([x]) in pixels. Default is 5 by 5.
POSTLABELCACHE [true|false] Tells MapServer to render this legend after all labels in the cache have been
drawn. Useful for adding neatlines and similar elements. Default is false.
STATUS [on|off|embed] Is the legend image to be created.
TEMPLATE [filename] HTML legend template file.
See Also:
HTML Legends with MapServer
TRANSPARENT [on|off] Should the background color for the legend be transparent. This flag is now deprecated in
favor of declaring transparency within OUTPUTFORMAT declarations. Default is off. Deprecated since version
4.6.
5.14 MAP
ANGLE [double] Angle, given in degrees, to rotate the map. Default is 0. The rendered map will rotate in a clockwise
direction. The following are important notes:
• Requires a PROJECTION object specified at the MAP level and for each LAYER object (even if all layers
are in the same projection).
• Requires MapScript (SWIG, PHP MapScript). Does not work with CGI mode.
• If using the LABEL object’s ANGLE or the LAYER object’s LABELANGLEITEM parameters as well,
these parameters are relative to the map’s orientation (i.e. they are computed after the MAP object’s
ANGLE). For example, if you have specified an ANGLE for the map of 45, and then have a layer LA-
BELANGLEITEM value of 45, the resulting label will not appear rotated (because the resulting map is
rotated clockwise 45 degrees and the label is rotated counter-clockwise 45 degrees).
• More information can be found on the MapRotation Wiki Page.
CONFIG [key] [value] This can be used to specify several values at run-time, for both MapServer and GDAL/OGR
libraries. Developers: values will be passed on to CPLSetConfigOption(). Details on GDAL/OGR options
are found in their associated driver documentation pages (GDAL/OGR). The following options are available
specifically for MapServer:
CGI_CONTEXT_URL [value] The CONFIG parameter can be used to enable loading a map context from a
URL. See the Map Context HowTo for more info.
MS_ENCRYPTION_KEY [filename] The CONFIG parameter can be used to specify an encryption key that
is used with MapServer’s msencypt utility.
MS_ERRORFILE [filename] The CONFIG parameter can be used to write MapServer errors to a file (as of
MapServer 5.0). With MapServer 5.x, a full path (absolute reference) is required, including the filename.
Starting with MapServer 6.0, a filename with relative path can be passed via this CONFIG directive, in
which case the filename is relative to the mapfile location. Note that setting MS_ERRORFILE via an
environment variable always requires an absolute path since there would be no mapfile to make the path
relative to. For more on this see the DEBUG parameter below.
MS_NONSQUARE [yes|no] The CONFIG parameter can be used to allow non-square WMS requests.
ON_MISSING_DATA [FAIL|LOG|IGNORE] The CONFIG parameter can be used to tell MapServer how
to handle missing data in tile indexes (as of MapServer 5.3-dev, r8015). Previous MapServer versions
required a compile-time switch (“IGNORE_MISSING_DATA”), but this is no longer required.
FAIL This will cause MapServer to throw an error and exit (to crash, in other words) on a missing file in
a tile index. This is the default.
LOG This will cause MapServer to log the error message for a missing file in a tile index, and continue
with the map creation. Note: DEBUG parameter and CONFIG “MS_ERRORFILE” need to be set for
logging to occur, so please see the DEBUG parameter below for more information.
IGNORE This will cause MapServer to not report or log any errors for missing files, and map creation
will occur normally.
PROJ_LIB [path] The CONFIG parameter can be used to define the location of your EPSG files for the Proj.4
library. Setting the [key] to PROJ_LIB and the [value] to the location of your EPSG files will force
PROJ.4 to use this value. Using CONFIG allows you to avoid setting environment variables to point to
your PROJ_LIB directory. Here are some examples:
1. Unix
2. Windows
DATAPATTERN [regular expression] This defines a regular expression to be applied to requests to change DATA
parameters via URL requests (i.e. map_layername_data=...). If a pattern doesn’t exist then web users can’t
monkey with support files via URLs. This allows you to isolate one application from another if you desire, with
the default operation being very conservative. See also TEMPLATEPATTERN.
DEBUG [off|on|0|1|2|3|4|5] Enables debugging of all of the layers in the current map.
Debugging with MapServer versions >= 5.0:
Verbose output is generated and sent to the standard error output (STDERR) or the MapServer errorfile if one
is set using the “MS_ERRORFILE” environment variable. You can set the environment variable by using the
CONFIG parameter
at the MAP level of the mapfile, such as:
CONFIG "MS_ERRORFILE" "/ms4w/tmp/ms_error.txt"
You can also set the environment variable in Apache by adding the following to your httpd.conf:
SetEnv MS_ERRORFILE "/ms4w/tmp/ms_error.txt"
Once the environment variable is set, the DEBUG mapfile parameter can be used to control the level of debug-
ging output. Here is a description of the possible DEBUG values:
• DEBUG O or OFF - only msSetError() calls are logged to MS_ERRORFILE. No msDebug() output at
all. This is the default and corresponds to the original behavior of MS_ERRORFILE in MapServer 4.x
• DEBUG 1 or ON - includes all output from DEBUG 0 plus msDebug() warnings about common pitfalls,
failed assertions or non-fatal error situations (e.g. missing or invalid values for some parameters, missing
shapefiles in tileindex, timeout error from remote WMS/WFS servers, etc.)
• DEBUG 2 - includes all output from DEBUG 1 plus notices and timing information useful for tuning
mapfiles and applications
• DEBUG 3 - all of DEBUG 2 plus some debug output useful in troubleshooting problems such as WMS
connection URLs being called, database connection calls, etc. This is the recommended level for debug-
ging mapfiles.
• DEBUG 4 - DEBUG 3 plus even more details...
• DEBUG 5 - DEBUG 4 plus any msDebug() output that might be more useful to the developers than to the
users.
You can also set the debug level by using the “MS_DEBUGLEVEL” environment variable.
The DEBUG setting can also be specified for a layer, by setting the DEBUG parameter in the LAYER object.
For more details on this debugging mechanism, please see the Debugging MapServer document.
Debugging with MapServer versions < 5:
Verbose output is generated and sent to the standard error output (STDERR) or the MapServer logfile if one is
set using the LOG parameter in the WEB object. Apache users will see timing details for drawing in Apache’s
error_log file. Requires MapServer to be built with the DEBUG=MSDEBUG option (–with-debug configure
option).
EXTENT [minx] [miny] [maxx] [maxy] The spatial extent of the map to be created. In most cases you will need to
specify this, although MapServer can sometimes (expensively) calculate one if it is not specified.
FONTSET [filename] Filename of fontset file to use. Can be a path relative to the mapfile, or a full path.
IMAGECOLOR [r] [g] [b] Color to initialize the map with (i.e. background color). When transparency is enabled
(TRANSPARENT ON) for the typical case of 8-bit pseudocolored map generation, this color will be marked as
transparent in the output file palette. Any other map components drawn in this color will also be transparent, so
for map generation with transparency it is best to use an otherwise unused color as the background color.
IMAGEQUALITY [int] Deprecated Use FORMATOPTION “QUALITY=n” in the OUTPUTFORMAT declaration
to specify compression quality for JPEG output. Deprecated since version 4.6.
IMAGETYPE [gif|png|jpeg|wbmp|gtiff|swf|userdefined] Output format to generate. See details in the OUTPUT-
FORMAT section for available formats. The name here must match the ‘NAME’ of a user defined or internally
generated OUTPUTFORMAT section.
INTERLACE [on|off] Deprecated Use FORMATOPTION “INTERLACE=ON” in the OUTPUTFORMAT declara-
tion to specify if the output images should be interlaced. Deprecated since version 4.6.
LAYER Signals the start of a LAYER object.
LEGEND Signals the start of a LEGEND object.
MAXSIZE [integer] Sets the maximum size of the map image. This will override the default value. For example,
setting this to 2048 means that you can have up to 2048 pixels in both dimensions (i.e. max of 2048x2048).
NAME [name] Prefix attached to map, scalebar and legend GIF filenames created using this mapfile. It should be
kept short.
PROJECTION Signals the start of a PROJECTION object.
QUERYMAP Signals the start of a QUERYMAP object.
REFERENCE Signals the start of a REFERENCE MAP object.
RESOLUTION [int] Sets the pixels per inch for output, only affects scale computations and nothing else, default is
72.
SCALEDENOM [double] Computed scale of the map. Set most often by the application. Scale is given as the
denominator of the actual scale fraction, for example for a map at a scale of 1:24,000 use 24000. Implemented
in MapServer 5.0, to replace the deprecated SCALE parameter.
See Also:
Map Scale
SCALE [double] - deprecated Since MapServer 5.0 the proper parameter to use is SCALEDENOM instead. The
deprecated SCALE is the computed scale of the map. Set most often by the application. Scale is given as the
denominator of the actual scale fraction, for example for a map at a scale of 1:24,000 use 24000. Deprecated
since version 5.0.
SCALEBAR Signals the start of a SCALEBAR object.
SHAPEPATH [filename] Path to the directory holding the shapefiles or tiles. There can be further subdirectories
under SHAPEPATH.
SIZE [x][y] Size in pixels of the output image (i.e. the map).
STATUS [on|off] Is the map active? Sometimes you may wish to turn this off to use only the reference map or scale
bar.
SYMBOLSET [filename] Filename of the symbolset to use. Can be a path relative to the mapfile, or a full path.
SYMBOL Signals the start of a SYMBOL object.
TEMPLATEPATTERN [regular expression] This defines a regular expression to be applied to requests to change
TEMPLATE parameters via URL requests (i.e. map_layername_template=...). If a pattern doesn’t exist then
web users can’t monkey with support files via URLs. This allows you to isolate one application from another if
you desire, with the default operation being very conservative. See also DATAPATTERN.
TRANSPARENT [on|off] Use FORMATOPTION “TRANSPARENT=ON” in the OUTPUTFORMAT declaration
to specify if the output images should be transparent. Deprecated since version 4.6.
UNITS [feet|inches|kilometers|meters|miles|nauticalmiles|dd] Units of the map coordinates. Used for scalebar and
scale computations. Nauticalmiles was added in MapServer 5.6.
WEB Signals the start of a WEB object.
5.15 OUTPUTFORMAT
A map file may have zero, one or more OUTPUTFORMAT object declarations, defining available output formats
supported including formats like PNG, GIF, JPEG, GeoTIFF, SVG, PDF and KML.
If OUTPUTFORMAT sections declarations are not found in the map file, the following implicit declarations will be
made. Only those for which support is compiled in will actually be available. The GeoTIFF depends on building with
GDAL support, and the PDF and SVG depend on building with cairo support.
OUTPUTFORMAT
NAME "png"
DRIVER AGG/PNG
MIMETYPE "image/png"
IMAGEMODE RGB
EXTENSION "png"
END
OUTPUTFORMAT
NAME gif
DRIVER "GD/GIF"
MIMETYPE "image/gif"
IMAGEMODE PC256
EXTENSION "gif"
END
OUTPUTFORMAT
NAME p n g 8
DRIVER "AGG/PNG8"
MIMETYPE "image/png; mode=8bit"
IMAGEMODE RGB
EXTENSION "png"
FORMATOPTION "QUANTIZE_FORCE=on"
FORMATOPTION "QUANTIZE_COLORS=256"
END
OUTPUTFORMAT
NAME jpeg
DRIVER "AGG/JPEG"
MIMETYPE "image/jpeg"
IMAGEMODE RGB
EXTENSION "jpg"
END
OUTPUTFORMAT
NAME s v g
DRIVER "CAIRO/SVG"
MIMETYPE "image/svg+xml"
IMAGEMODE RGB
EXTENSION "svg"
END
OUTPUTFORMAT
NAME pdf
DRIVER "CAIRO/PDF"
MIMETYPE "application/x-pdf"
IMAGEMODE RGB
EXTENSION "pdf"
END
OUTPUTFORMAT
NAME GTiff
DRIVER "GDAL/GTiff"
MIMETYPE "image/tiff"
IMAGEMODE RGB
EXTENSION "tif"
END
OUTPUTFORMAT
NAME k m l
DRIVER "KML"
MIMETYPE "application/vnd.google-earth.kml.xml"
IMAGEMODE RGB
EXTENSION "kml"
END
OUTPUTFORMAT
NAME k m z
DRIVER "KMZ"
MIMETYPE "application/vnd.google-earth.kmz"
IMAGEMODE RGB
EXTENSION "kmz"
END
OUTPUTFORMAT
NAME "cairopng"
DRIVER C A I R O /PNG
MIMETYPE "image/png"
IMAGEMODE RGB
EXTENSION "png"
END
NAME [name] The name to use use in the IMAGETYPE keyword of the map file to select this output format.
This name is also used in metadata describing wxs formats allowed, and can be used (sometimes along with
mimetype) to select the output format via keywords in OGC requests. (optional)
DRIVER [name] The name of the driver to use to generate this output format. Some driver names include the defini-
tion of the format if the driver supports multiple formats. For AGG, the possbile driver names are “AGG/PNG”
and “AGG/JPEG”. For GD the possible driver names are “GD/Gif” and “GD/PNG”. For output through OGR the
OGR driver name is appended, such as “OGR/Mapinfo File”. For output through GDAL the GDAL shortname
for the format is appended, such as “GDAL/GTiff”. Note that PNG, JPEG and GIF output can be generated with
either GDAL or GD (GD is generally more efficient). TEMPLATE should be used for template based output.
(mandatory)
IMAGEMODE [PC256/RGB/RGBA/INT16/FLOAT32/FEATURE] Selects the imaging mode in which the output
is generated. Does matter for non-raster formats like Flash. Not all formats support all combinations. For
instance GD supports only PC256. (optional)
• PC256: Produced a pseudocolored result with up to 256 colors in the palette (legacy MapServer mode).
Only supported for GD/GIF and GD/PNG.
• RGB: Render in 24bit Red/Green/Blue mode. Supports all colors but does not support transparency.
• RGBA: Render in 32bit Red/Green/Blue/Alpha mode. Supports all colors, and alpha based transparency.
All features are rendered against an initially transparent background.
• BYTE: Render raw 8bit pixel values (no presentation). Only works for RASTER layers (through GDAL)
and WMS layers currently.
• INT16: Render raw 16bit signed pixel values (no presentation). Only works for RASTER layers (through
GDAL) and WMS layers currently.
• FLOAT32: Render raw 32bit floating point pixel values (no presentation). Only works for RASTER layers
(through GDAL) and WMS layers currently.
• FEATURE: Output is a non-image result, such as features written via templates or OGR.
MIMETYPE [type] Provide the mime type to be used when returning results over the web. (optional)
EXTENSION [type] Provide the extension to use when creating files of this type. (optional)
TRANSPARENT [ON/OFF] Indicates whether transparency should be enabled for this format. Note that trans-
parency does not work for IMAGEMODE RGB output. Not all formats support transparency (optional). When
transparency is enabled for the typical case of 8-bit pseudocolored map generation, the IMAGECOLOR color
will be marked as transparent in the output file palette. Any other map components drawn in this color will
also be transparent, so for map generation with transparency it is best to use an otherwise unused color as the
background color.
FORMATOPTION [option] Provides a driver or format specific option. Zero or more FORMATOPTION statement
may be present within a OUTPUTFORMAT declaration. (optional)
• AGG/JPEG: The “QUALITY=n” option may be used to set the quality of jpeg produced (value from
0-100).
• GD/PNG: The “INTERLACE=[ON/OFF]” option may be used to turn interlacing on or off.
• GD/GIF: The “INTERLACE=[ON/OFF]” option may be used to turn interlacing on or off.
5.16 PROJECTION
To set up projections you must define two projection objects: one for the output image (in the MAP object) and one for
each layer (in the LAYER objects) to be projected. MapServer relies on the Proj.4 library for projections. Projection
objects therefore consist of a series of PROJ.4 keywords, which are either specified within the object directly or
referred to in an EPSG file. An EPSG file is a lookup file containing projection parameters, and is part of the PROJ.4
library.
The following two examples both define the same projection (UTM zone 15, NAD83), but use 2 different methods:
Example 1: Inline Projection Parameters
PROJECTION
"proj=utm"
"ellps=GRS80"
"datum=NAD83"
"zone=15"
"units=m"
"north"
"no_defs"
END
Note: For a list of all of the possible PROJ.4 projection parameters, see the PROJ.4 parameters page.
Example 2: EPSG Projection Use
PROJECTION
"init=epsg:26915"
END
Note: This refers to an EPSG lookup file that contains a ‘26915’ code with the full projection parameters. “epsg” in
this instance is case-sensitive because it is referring to a file name. If your file system is case-sensitive, this must be
lower case, or MapServer (Proj.4 actually) will complain about not being able to find this file.
Note: See http://spatialreference.org/ref/epsg/26915 for more information on this coordinate system.
The next two examples both display how to possibly define unprojected lat/longs (“geographic”):
Example 3: Inline Projection Parameters
PROJECTION
"proj=latlong"
"ellps=WGS84"
"datum=WGS84"
END
• If all of your data in the mapfile is in the same projection, you DO NOT have to specify any projection objects.
MapServer will assume that all of the data is in the same projection.
• Think of the MAP-level projection object as your output projection. The EXTENT and UNITS values at the
MAP-level must be in the output projection units. Also, if you have layers in other projections (other than the
MAP-level projection) then you must define PROJECTION objects for those layers, to tell MapServer what
projections they are in.
• If you specify a MAP-level projection, and then only one other LAYER projection object, MapServer will
assume that all of the other layers are in the specified MAP-level projection.
• Always refer to the EPSG file in lowercase, because it is a lowercase filename and on Linux/Unix systems this
parameter is case sensitive.
• If you get projection errors, refer to the Errors to check if your exact error has been discussed.
• Search the MapServer-users email list archives, odds are that someone has faced your exact issue before.
• See the PROJ.4 user guides for complete descriptions of supported projections and coordinate systems.
• Refer to the Cartographical Map Projections page for background information on projections.
5.17 QUERYMAP
COLOR [r] [g] [b] Color in which features are highlighted. Default is yellow.
SIZE [x][y] Size of the map in pixels. Defaults to the size defined in the map object.
STATUS [on|off] Is the query map to be drawn?
STYLE [normal|hilite|selected] Sets how selected features are to be handled. Layers not queried are drawn as usual.
• Normal: Draws all features according to the settings for that layer.
• Hilite: Draws selected features using COLOR. Non-selected features are drawn normally.
• Selected: draws only the selected features normally.
5.18 REFERENCE
Three types of reference maps are supported. The most common would be one showing the extent of a map in an
interactive interface. It is also possible to request reference maps as part of a query. Point queries will generate an
image with a marker (see below) placed at the query point. Region based queries will depict the extent of the area of
interest. Finally, feature based queries will display the selection feature(s) used.
COLOR [r] [g] [b] Color in which the reference box is drawn. Set any component to -1 for no fill. Default is red.
EXTENT [minx][miny][maxx][maxy] The spatial extent of the base reference image.
IMAGE [filename] Full filename of the base reference image. Must be a GIF image.
MARKER [integer|string] Defines a symbol (from the symbol file) to use when the box becomes too small (see
MINBOXSIZE and MAXBOXSIZE below). Uses a crosshair by default.
MARKERSIZE [integer] Defines the size of the symbol to use instead of a box (see MARKER above).
MINBOXSIZE [integer] If box is smaller than MINBOXSIZE (use box width or height) then use the symbol defined
by MARKER and MARKERSIZE.
MAXBOXSIZE [integer] If box is greater than MAXBOXSIZE (use box width or height) then draw nothing (Often
the whole map gets covered when zoomed way out and it’s perfectly obvious where you are).
OUTLINECOLOR [r] [g] [b] Color to use for outlining the reference box. Set any component to -1 for no outline.
SIZE [x][y] Size, in pixels, of the base reference image.
STATUS [on|off] Is the reference map to be created? Default it off.
5.19 SCALEBAR
Scalebars currently do not make use of TrueType fonts. The size of the scalebar image is NOT known prior to
rendering, so be careful not to hard-code width and height in the <IMG> tag in the template file. Future versions will
make the image size available.
ALIGN [left|center|right] Defines how the scalebar is aligned within the scalebar image. Default is center. Available
in versions 5.2 and higher. New in version 5.2.
BACKGROUNDCOLOR [r] [g] [b] Color to use for scalebar background, not the image background.
COLOR [r] [g] [b] Color to use for drawing all features if attribute tables are not used.
IMAGECOLOR [r] [g] [b] Color to initialize the scalebar with (i.e. background).
INTERLACE [true|false] Should output images be interlaced? Default is [on]. This keyword is now deprecated in
favour of using the FORMATOPTION “INTERLACE=ON” line in the OUTPUTFORMAT declaration. Depre-
cated since version 4.6.
INTERVALS [integer] Number of intervals to break the scalebar into. Default is 4.
LABEL Signals the start of a LABEL object
OUTLINECOLOR [r] [g] [b] Color to use for outlining individual intervals. Set any component to -1 for no outline
which is the default.
POSITION [ul|uc|ur|ll|lc|lr] Where to place an embedded scalebar in the image. Default is lr.
POSTLABELCACHE [true|false] For use with embedded scalebars only. Tells the MapServer to embed the scale-
bar after all labels in the cache have been drawn. Default is false.
SIZE [x][y] Size in pixels of the scalebar. Labeling is not taken into account.
STATUS [on|off|embed] Is the scalebar image to be created, and if so should it be embedded into the image? Default
is off. (Please note that embedding scalebars require that you define a markerset. In essence the scalebar
becomes a custom marker that is handled just like any other annotation.)
STYLE [integer] Chooses the scalebar style. Valid styles are 0 and 1.
TRANSPARENT [on|off] Should the background color for the scalebar be transparent. This flag is now deprecated
in favor of declaring transparency within OUTPUTFORMAT declarations. Default is off. Deprecated since
version 4.6.
UNITS [feet|inches|kilometers|meters|miles|nauticalmiles] Output scalebar units, default is miles. Used in con-
junction with the map’s units to develop the actual graphic. Note that decimal degrees are not valid scalebar
units. Nauticalmiles was added in MapServer 5.6.
5.20 STYLE
Style holds parameters for symbolization and styling. Multiple styles may be applied within a CLASS or LABEL.
This object appeared in 4.0 and the intention is to separate logic from looks. The final intent is to have named styles
(Not yet supported) that will be re-usable through the mapfile. This is the way of defining the appearance of an object
(a CLASS or a LABEL).
ANGLE [double|attribute|AUTO] Angle, given in degrees, to rotate the symbol (counter clockwise). Default is 0
(no rotation). If you have an attribute that specifies angles in a clockwise direction (compass direction), you
have to adjust the angle attribute values before they reach Mapserver (360-ANGLE), as it is not possible to use
a mathematical expression for ANGLE.
• For points, it specifies the rotation of the symbol around its center.
• For decorated lines, the behaviour depends on the value of the GAP element.
– For negative GAP values it specifies the rotation of the decoration symbol relative to the direction of
the line. An angle of 0 means that the symbol’s x-axis is oriented along the direction of the line.
– For non-negativ (or absent) GAP values it specifies the rotation of the decoration symbol around its
center. An angle of 0 means that the symbol is not rotated.
• For polygons, it specifies the angle of the lines in a HATCH symbol (0 - horizontal lines), or it specifies
the rotation of the symbol used to generate the pattern in a polygon fill (it does not specify the rotation of
the fill as a whole). For its use with hatched lines, see Example #7 in the symbology examples.
• [attribute] was introduced in version 5.0, to specify the attribute to use for angle values. The hard brackets
[] are required. For example, if your data source has an attribute named “MYROTATE” that holds angle
values for each feature, your STYLE object for hatched lines might contain:
STYLE
SYMBOL ’hatch-test’
COLOR 255 0 0
ANGLE [ M Y R O T A T E ]
SIZE 4.0
WIDTH 3.0
END
The associated RFC document for this feature is MS RFC 19: Style & Label attribute binding.
• The AUTO keyword was added in version 5.4, and currently only applies when coupled with the GEOM-
TRANSFORM keyword.
ANGLEITEM [string] ANGLE[attribute] must now be used instead. Deprecated since version 5.0.
ANTIALIAS [true|false] Should TrueType fonts be antialiased. Only useful for GD (gif) rendering. Default is false.
Has no effect for the other renderers (where anti-aliasing can not be turned off).
BACKGROUNDCOLOR [r] [g] [b] Color to use for non-transparent symbols.
COLOR [r] [g] [b] | [attribute]
• Color to use for drawing features. r, g and b shall be integers [0..255]. To specify green, the following is used:
COLOR 0 255 0
• [attribute] was introduced in version 5.0, to specify the attribute to use for color values. The hard brackets []
are required. For example, if your data set has an attribute named “MYPAINT” that holds color values for each
record, use: object for might contain:
COLOR [ M Y P A I N T ]
The associated RFC document for this feature is MS RFC 19: Style & Label attribute binding.
GAP [double] GAP specifies the distance between SYMBOLs (center to center) for decorated lines and polygon fills
in layer SIZEUNITS. For polygon fills, GAP specifies the distance between SYMBOLs in both the X and the Y
direction. For lines, the centers of the SYMBOLs are placed on the line. As of MapServer 5.0 this also applies
to PixMap symbols.
When scaling of symbols is in effect (SYMBOLSCALEDENOM is specified for the LAYER), GAP specifies the
distance in layer SIZEUNITS at the map scale 1:SYMBOLSCALEDENOM.
• For lines, the first symbol will be placed GAP/2 from the start of the line.
• For lines, a negative GAP value will cause the symbols’ X axis to be aligned relative to the tangent of the
line.
• For lines, a positive GAP value aligns the symbols’ X axis relative to the X axis of the output device.
• For lines, a GAP of 0 (the default value) will cause the symbols to be rendered edge to edge
• For polygons, a missing GAP or a GAP of 0 will cause the symbols to be rendered edge to edge.
Symbols can be rotated using ANGLE. New in version 6.0: moved from SYMBOL
Note: The behaviour of GAP has not been stable over time. It has specified the amount of space between
the symbols, and also something in between the amount of space between the symbols and the center to center
distance. The goal is to have GAP specify the center to center distance, but in version 6.0 it is the amount of
space between the symbols that is specified.
GEOMTRANSFORM [bbox|end|labelpnt|labelpoly|start|vertices] Used to indicate that the current feature will be
transformed before the actual style is applied. Introduced in version 5.4.
• bbox: produces the bounding box of the geometry.
• end: produces the last point of the geometry. When used with ANGLE AUTO, it can for instance be used
to render an arrowhead.
• labelpnt: used for LABEL styles. It produces a point that is placed at the label’s reference point.
• labelpoly: used for LABEL styles. Produces a polygon that covers the label plus a 1 pixel padding.
• start: produces the first point of the current geometry. When used with ANGLE AUTO, it can for instance
be used to render arrow tail on line segments.
• vertices: produces all the intermediate vertices (points) of the underlying geometry (the start and end are
excluded). When used with ANGLE AUTO, the marker is oriented by the half angle formed by the two
adjacent line segments.
LINECAP [butt|round|square] Sets the line cap type for lines. Default is round. See Cartographical Symbol Con-
struction with MapServer for explanation and examples. New in version 6.0: moved from SYMBOL
LINEJOIN [round|miter|bevel] Sets the line join type for lines. Default is round. See Cartographical Symbol
Construction with MapServer for explanation and examples. New in version 6.0: moved from SYMBOL
LINEJOINMAXSIZE [int]
Sets the max length of the miter LINEJOIN type. The value represents a coefficient which multiplies a
current symbol size. Default is 3. See Cartographical Symbol Construction with MapServer for explana-
tion and examples. New in version 6.0: moved from SYMBOL
MAXSIZE [double] Maximum size in layer SIZEUNITS to draw a symbol. Default is 500. Starting from version
5.4, the value can also be a decimal value (and not only integer).
MAXWIDTH [double] Maximum width in layer SIZEUNITS to draw the line work. Default is 32. Starting from
version 5.4, the value can also be a decimal value (and not only integer).
MINSIZE [double] Minimum size in layer SIZEUNITS to draw a symbol. Default is 0. Starting from version 5.4,
the value can also be a decimal value (and not only integer).
MINWIDTH [double] Minimum width in layer SIZEUNITS to draw the line work. Default is 0. Starting from
version 5.4, the value can also be a decimal value (and not only integer).
OFFSET [x][y] Geometry offset values in layer SIZEUNITS.
When scaling of symbols is in effect (SYMBOLSCALEDENOM is specified for the LAYER), OFFSET gives
offset values in layer SIZEUNITS at the map scale 1:SYMBOLSCALEDENOM.
An OFFSET of 20 40 will shift the geometry 20 SIZEUNITS to the left and 40 SIZEUNITS down before render-
ing.
For lines, an OFFSET of n -99 will produce a line geometry that is shifted n SIZEUNITS perpendicular to the
original line geometry. A positive n shifts the line to the right when seen along the direction of the line. A
negative n shifts the line to the left when seen along the direction of the line.
OPACITY [integer|attribute] Opacity to draw the current style (applies to 5.2+, AGG Rendering Specifics only, does
not apply to pixmap symbols)
• [attribute] was introduced in version 5.6, to specify the attribute to use for opacity values.
OUTLINECOLOR [r] [g] [b] | [attribute]
• Color to use for outlining polygons and certain marker symbols (ellipse, vector and truetype). Has no effect for
lines. The width of the outline can be specified using WIDTH. If no WIDTH is specified, an outline of one pixel
will be drawn. r, g and b shall be integers [0..255]. To specify green, the following is used:
OUTLINECOLOR 0 255 0
WIDTH 3.0
• [attribute] was introduced in version 5.0, to specify the attribute to use for color values. The hard brackets []
are required. For example, if your data set has an attribute named “MYPAINT” that holds color values for each
record, use: object for might contain:
OUTLINECOLOR [ M Y P A I N T ]
The associated RFC document for this feature is MS RFC 19: Style & Label attribute binding.
PATTERN [double on] [double off] [double on] [double off] ... END
Currently used to defines a dash pattern for line work (lines, polygon outlines, ...). The numbers (doubles)
specify the lengths of the dashes and gaps of the dash pattern in layer SIZEUNITS.
When scaling of symbols is in effect (SYMBOLSCALEDENOM is specified for the LAYER), the numbers
specify the lengths of the dashes and gaps in layer SIZEUNITS at the map scale 1:SYMBOLSCALEDE-
NOM.
To specify a dashed line that is 5 units wide, with dash lengths of 5 units and gaps of 5 units, the following
style can be used:
STYLE
COLOR 0 0 0
WIDTH 5.0
LINECAP BUTT
PATTERN 5.0 5.0 END
END
WIDTH 3.0
END
The associated RFC document for this feature is MS RFC 19: Style & Label attribute binding.
• Starting from version 5.4, the value can also be a decimal value (and not only integer).
SIZEITEM [string] SIZE [attribute] must now be used instead. Deprecated since version 5.0.
SYMBOL [integer|string|filename|attribute] The symbol name or number to use for all features if attribute tables
are not used. The number is the index of the symbol in the symbol file, starting at 1, the 5th symbol in the file
is therefore symbol number 5. You can also give your symbols names using the NAME keyword in the symbol
definition file, and use those to refer to them. Default is 0, which results in a single pixel, single width line, or
solid polygon fill, depending on layer type.
You can also specify a GIF or PNG filename. The path is relative to the location of the mapfile.
[attribute] was introduced in version 5.6, to use an attribute to specify the symbol name. The hard brackets []
are required.
WIDTH [double|attribute]
WIDTH refers to the thickness of line work drawn, in layer SIZEUNITS. Default is 1.0.
When scaling of symbols is in effect (SYMBOLSCALEDENOM is specified for the LAYER), WIDTH
refers to the thickness of the line work in layer SIZEUNITS at the map scale 1:SYMBOLSCALEDENOM.
• If used with SYMBOL and OUTLINECOLOR, WIDTH specifies the width of the symbol outlines.
This applies to SYMBOL TYPE vector (polygons), ellipse and truetype.
• For lines, WIDTH specifies the width of the line.
• For polygons, if used with OUTLINECOLOR, WIDTH specifies the thickness of the polygon outline.
• For a symbol of SYMBOL TYPE hatch, WIDTH specifies the thickness of the hatched lines. For its
use with hatched lines, see Example #7 in the symbology examples.
• [attribute] was added in version 5.2 to specify the attribute to use for the width value. The hard
brackets [] are required.
• Starting from version 5.4, the value can also be a decimal value (and not only integer).
5.21 SYMBOL
• Symbol definitions can be included within the main map file or, more commonly, in a separate file. Symbol
definitions in a separate file are designated using the SYMBOLSET keyword, as part of the MAP object. This
recommended setup is ideal for re-using symbol definitions across multiple MapServer applications.
• There are 3 main types of symbols in MapServer: Markers, Lines and Shadesets.
• Symbol 0 is always the degenerate case for a particular class of symbol. For points, symbol 0 is a single pixel,
for shading (i.e. filled polygons) symbol 0 is a solid fill, and for lines, symbol 0 is a single pixel wide line.
• Symbol definitions contain no color information, colors are set within STYLE objects.
• For MapServer versions < 5 there is a maximum of 64 symbols per file. This can be changed by editing
mapsymbol.h and changing the value of MS_MAXSYMBOLS at the top of the file. As of MapServer 5.0 there
is no symbol limit.
• More information can be found in the Construction of Cartographic Symbols document.
ANTIALIAS [true|false] Should TrueType fonts be antialiased. Only useful for GD (gif) rendering. Default is false.
Has no effect for the other renderers (where anti-aliasing can not be turned off).
CHARACTER [char] Character used to reference a particular TrueType font character. You’ll need to figure out the
mapping from the keyboard character to font character.
FILLED [true|false] Sets the symbol to be filled with a user defined color (See the STYLE object). For marker
symbols, if OUTLINECOLOR was specified then the symbol is outlined with it.
FONT [string] Name of TrueType font to use as defined in the FONTSET.
GAP [int] This keyword has been moved to STYLE in version 6.0. Deprecated since version 6.0.
IMAGE [string] Image (GIF or PNG) to use as a marker or brush for type PIXMAP symbols.
NAME [string] Alias for the symbol. To be used in CLASS STYLE objects.
LINECAP [butt|round|square|triangle] This keyword has been moved to STYLE in version 6.0. Deprecated since
version 6.0.
LINEJOIN [round|miter|bevel] This keyword has been moved to STYLE in version 6.0. Deprecated since version
6.0.
LINEJOINMAXSIZE [int] This keyword has been moved to STYLE in version 6.0. Deprecated since version 6.0.
PATTERN [num on] [num off] [num on] ... END This keyword has been moved to STYLE in version 6.0. Depre-
cated since version 6.0.
POINTS [x y] [x y] ... END
Signifies the start of a sequence of points that make up a symbol of TYPE vector or that define the x and y
radius of a symbol of TYPE ellipse. The end of this section is signified with the keyword END. The x and
y values can be given using decimal numbers. The maximum x and y values define the bounding box of
the symbol. The size (actually height) of a symbol is defined in the STYLE. You can create non-contiguous
paths by inserting “-99 -99” at the appropriate places.
x values increase to the right, y values increase downwards.
For symbols of TYPE ellipse, a single point is specified that defines the x and y radius of the ellipse.
Circles are created when x and y are equal.
Note: If a STYLE using this symbol doesn’t contain an explicit size, then the default symbol size will
be based on the range of “y” values in the point coordinates. e.g. if the y coordinates of the points in the
symbol range from 0 to 5, then the default size for this symbol will be assumed to be 5.
STYLE [num on] [num off] [num on] ... END Renamed to PATTERN in MapServer 5.0. Deprecated since version
5.0.
TRANSPARENT [color index] Sets a transparent color for the input image for pixmap symbols, or determines
whether all shade symbols should have a transparent background. For shade symbols it may be desirable to
have background features “show through” a transparent hatching pattern, creating a more complex map. By
default a symbol’s background is the same as the parent image (i.e. color 0). This is user configurable.
TYPE [ellipse|hatch|pixmap|simple|truetype|vector]
• ellipse: radius values in the x and y directions define an ellipse.
• hatch: produces hatched lines throughout the (polygon) shape.
• pixmap: a user supplied image will be used as the symbol.
• simple: default symbol type (1 pixel point, 1 pixel line, solid fill).
• truetype: TrueType font to use as defined in the MAP FONTSET.
• vector: a vector drawing is used to define the shape of the symbol.
Table of Contents
• Symbology Examples
– Example 1. Dashed Line
– Example 2. TrueType font marker symbol
– Example 3. Vector triangle marker symbol
– Example 4. Non-contiguous vector marker symbol (Cross)
– Example 5. Circle vector symbol
– Example 6. Downward diagonal fill
– Example 7. Using the Symbol Type HATCH (new in 4.6)
– Example 8. Styled lines using GAP
This example creates a dashed line that is 5 SIZEUNITS wide, with 10 SIZEUNITS on, 5 off, 5 on, 10 off ...
LAYER
...
CLASS
...
STYLE
COLOR 0 0 0
WIDTH 5
LINECAP butt
PATTERN 10 5 5 10 END
END
END
END
This example symbol is a star, used to represent the national capital, hence the name. The font name in defined in
the FONTSET file. The code number “114” varies, you can use MS Windows’ character map to figure it out, or
guestimate.
SYMBOL
NAME "natcap"
TYPE TRUETYPE
FONT "geo"
FILLED true
ANTIALIAS true # only necessary for GD rendering
CHARACTER "r"
END
This example is fairly straight forward. Note that to have 3 sides you need 4 points, hence the first and last points are
identical. The triangle is not filled.
SYMBOL
NAME "triangle"
TYPE vector
POINTS
0 4
2 0
4 4
0 4
END
END
This example draws a cross, that is 2 lines (vectors) that are not connected end-to-end (Like the triangle in the previous
example). The negative values separate the two.
SYMBOL
NAME "cross"
TYPE vector
POINTS
2.0 0.0
2.0 4.0
-99 -99
0.0 2.0
4.0 2.0
END
END
This example creates a simple filled circle. Using non-equal values for the point will give you an actual ellipse.
SYMBOL
NAME "circle"
TYPE ellipse
FILLED true
POINTS
1 1
END
END
This example creates a symbol that can be used to create a downward diagonal fill for polygons.
SYMBOL
NAME "downwarddiagonalfill"
TYPE vector
TRANSPARENT 0
POINTS
0 1
1 0
END
END
As of MapServer 4.6, you can use the symbol type HATCH to produce hatched lines. The following will display
hatched lines at a 45 degree angle, 10 SIZEUNITS apart (center to center), and 3 SIZEUNITS wide.
Symbol definition:
SYMBOL
NAME ’hatch-test’
TYPE HATCH
END
Layer definition:
LAYER
...
CLASS
...
STYLE
SYMBOL ’hatch-test’
COLOR 255 0 0
ANGLE 45
SIZE 10
WIDTH 3
END
END
END
Other parameters available for HATCH are: MINSIZE, MAXSIZE, MINWIDTH, and MAXWIDTH.
Layer definition:
LAYER
...
CLASS
...
STYLE
WIDTH 5
COLOR 0 0 0
END
STYLE
SYMBOL ’ellipse2’
COLOR 0 0 0
ANGLE 30
SIZE 15
GAP -30
END
END
END
5.23 Templating
Table of Contents
• Templating
– Introduction
– Format
– Example Template
5.23.1 Introduction
Notes
• Templates must contain the magic string ‘mapserver template’ in the first line of the template. Often this takes
the form of an HTML, javascript or XML comment. This line is not written to the client. The magic string is
not case sensitive.
• All CGI parameters can be referenced in template substitutions, MapServer specific parameters as well as user
defined ones. In principle parameters are handed through by the MapServer 1:1. This feature is essential for
implementing MapServer applications.
The reference below only lists special template substitution strings which are needed to obtain information
modified by the MapServer, e.g. a new scale, query results, etc.
• Template substitution strings are case sensitive.
• Attribute item substitutions must be the same case as the item names in the dbase file.
• ArcView and ArcInfo generally produce dbase files with item names that are all uppercase. Appropriate URL
encoding (i.e. ‘ ‘ to ‘+’) is applied when templates are URLs.
• Some substitutions are also available in escaped form (i.e. URL encoded).
As an example this is needed when generating links within a template. This might pass the current mapextent to a new
MapServer call. [mapext] is substituted by a space delimited set of lower left and upper right coordinates. This would
break the URL. [mapext_esc] is substituted by a proper encoded set.
5.23.2 Format
Templates are simply HTML files or URL strings that contains special characters that are replaced by mapserv each
time the template is processed. The simple substitution allows information such as active layers or the spatial extent
to be passed from the user to mapserv and back again. Most often the new values are dumped into form variables that
will be passed on again. The list of special characters and form variables is given below. HTML templates can include
just about anything including JavaScript and Java calls.
In HTML files, the attribute values can be inside quotes(“”). Writing attribute values inside quotes allows you to set
special characters in value that you couldn’t use normaly (ie: ],=,” and space). To write a single quote in a attribute
value, just use two quotes (“”).
General
[web_meta data key],[web_meta data key_esc] Web object meta data access (e.g [web_projection]
Also available as escaped version.
[errmsg], [errmsg_esc] Current error stack output. Various error messages are delimited by semi-colons.
Also available as escaped version.
File Reference
[img] Path (relative to document root) of the new image, just the image name if IMAGE_URL is not set in the mapfile.
In a map interface template, [img] is substituted with the path to the map image. In a query results template, it
is substituted with the path to the querymap image (if a QUERYMAP object is defined in the Mapfile).
[ref] Path (relative to document root) of the new reference image.
[legend] Path (relative to document root) of new legend image rendered by the MapServer.
Since version 3.5.1 a new HTML Legend template is provided by MapServer. If a template is defined in the
Mapfile the [legend] string is replaced by the processed legend as. See the HTML Legends with MapServer for
details.
[scalebar] Path (relative to document root) of new scalebar image.
[queryfile] Path to the query file (if savequery was set as a CGI Parameter).
[map] Path to the map file (if savemap was set as a CGI Parameter).
Image Geometry
[center] Computed image center in pixels. Useful for setting imgxy form variable when map sizes change.
[center_x], [center_y] Computed image center X or Y coordinate in pixels.
[mapsize], [mapsize_esc] Current image size in cols and rows (separated by spaces).
Also available as escaped version.
[mapwidth], [mapheight] Current image width or height.
[scaledenom] Current image scale. The exact value is not appropriate for user information but essential for some
applications. The value can be rounded e.g. using JavaScript or server side post processing.
[scale] - deprecated Since MapServer 5.0 the proper parameter to use is [scaledenom] instead. The deprecated [scale]
is the current image scale. The exact value is not appropriate for user information but essential for some appli-
cations. The value can be rounded e.g. using JavaScript or server side post processing.
[cellsize] Size of an pixel in the current image in map units. Useful for distance measurement tools in user interfaces.
Map Geometry
• escape= Escape the coordinates returned. Default is “none”. Valid values are:
– “url” Use URL escape codes to encode the coordinates returned.
– “none” Do not escape.
• expand= Expand the bounds of the extents by a specific value. Specified in map coordinates. For example,
[mapext] might return:
• format= Format of the coordinates. Default is “$minx $miny $maxx $maxy”. For example, to add
commas to the coordinates you would use:
[mapext format="$minx,$miny,$maxx,$maxy"]
• precision= The number of decimal places to output for coordinates (default is 0).
[minx], [miny], [maxx], [maxy] Minimum / maximum X or Y coordinate of new map extent.
[dx], [dy] The differences of minimum / maximum X or Y coordinate of new map extent.
Useful for creating cachable extents (i.e. 0 0 dx dy) with legends and scalebars
[rawext], [rawext_esc] Raw mapextent, that is the extent before fitting to a window size (separated by spaces). In
cases where input came from imgbox (via Java or whatever) rawext refers to imgbox coordinates transformed
to map units. Useful for spatial query building.
Also available as escaped version. (rawext_esc is deprecated in MapServer 5.2. You should use the “escape=”
argument instead)
The default template [rawext] returns coordinates in the format of: mixx miny maxx maxy
Available arguments:
• escape= Escape the coordinates returned. Default is “none”. Valid values are:
– “url” Use URL escape codes to encode the coordinates returned.
– “none” Do not escape.
• expand= Expand the bounds of the extents by a specific value. Specified in map coordinates. For example,
[rawext] might return:
• format= Format of the coordinates. Default is “$minx $miny $maxx $maxy”. For example, to add
commas to the coordinates you would use:
[rawext format="$minx,$miny,$maxx,$maxy"]
• precision= The number of decimal places to output for coordinates (default is 0).
[rawminx], [rawminy], [rawmaxx], [rawmaxy] Minimum / maximum X or Y coordinate of a raw map/search ex-
tent.
The following substitutions are only available if the MapServer was compiled with PROJ support and a PROJECTION
is defined in the Mapfile.
[maplon], [maplat] Longitude / latitude value of mouse click. Available only when projection enabled.
[mapext_latlon], [mapext_latlon_esc] Full mapextent (separated by spaces). Available only when projection en-
abled.
Also available as escaped version. (mapext_latlon_esc is deprecated in MapServer 5.2. You should use the
“escape=” argument instead)
The default template [mapext_latlon] returns coordinates in the format of: mixx miny maxx maxy
Available arguments:
• escape= Escape the coordinates returned. Default is “none”. Valid values are:
– “url” Use URL escape codes to encode the coordinates returned.
– “none” Do not escape.
• expand= Expand the bounds of the extents by a specific value. Specified in map coordinates. For example,
[mapext_latlon] might return:
• format= Format of the coordinates. Default is “$minx $miny $maxx $maxy”. For example, to add
commas to the coordinates you would use:
[mapext_latlon format="$minx,$miny,$maxx,$maxy"]
• precision= The number of decimal places to output for coordinates (default is 0).
[minlon], [minlat], [maxlon] [maxlat] Minimum / maximum longitude or latitude value of mapextent. Available
only when projection enabled.
[refext], [refext_esc] Reference map extent (separated by spaces).
This template has been added with version 4.6 on behalf of an enhancement request. See the thread in the
MapServer ticket#1102 for potential use cases.
Also available as escaped version. (refext_esc is deprecated in MapServer 5.2. You should use the “escape=”
argument instead)
The default template [refext] returns coordinates in the format of: mixx miny maxx maxy
Available arguments:
• escape= Escape the coordinates returned. Default is “none”. Valid values are:
– “url” Use URL escape codes to encode the coordinates returned.
– “none” Do not escape.
• expand=
Expand the bounds of the extents by a specific value. Specified in map coordinates. For example,
[refext] might return:
• format= Format of the coordinates. Default is “$minx $miny $maxx $maxy”. For example, to add
commas to the coordinates you would use:
[refwext format="$minx,$miny,$maxx,$maxy"]
• precision= The number of decimal places to output for coordinates (default is 0).
Layer
[layers] | [layers_esc] All active layers space delimited. Used for a “POST” request.
Also available as escaped version.
[toggle_layers] | [toggle_layers_esc] List of all layers that can be toggled, i.e. all layers defined in the Mapfile which
status is currently not default.
Also available as escaped version.
[layername_check | select] Used for making layers persistent across a map creation session. String is replaced with
the keyword “checked”, “selected” or “” if layername is on. Layername is the name of a layer as it appears in
the Mapfile. Does not work for default layers.
[layername_meta data key] Layer meta data access (e.g. [streets_build] the underscore is essential).
Zoom
[zoom_minzoom to maxzoom_check|select] Used for making the zoom factor persistent. Zoom values can range
from -25 to 25 by default. The string is replaced with the HTML keyword “checked”, “selected” or “” depending
on the current zoom value.
E.g. if the zoom is 12, a [zoom_12_select] is replaced with “selected”, while a [zoom_13_select] in the same
HTML template file is not.
[zoomdir_-1|0|1_check|select] Used for making the zoom direction persistent. Use check with a radio control or
select with a selection list. See the demo for an example. The string is replaced with the HTML keyword
“checked”, “selected” or “” depending on the current value of zoomdir.
Query
The following substitutions are only available when the template is processed as a result of a query.
[shpext], [shpext_esc] Extent of current shape plus a 5 percent buffer. Available only when processing query results.
The default template [shpext] returns coordinates in the format of: mixx miny maxx maxy
Available arguments:
• escape= Escape the coordinates returned. Default is “none”. Valid values are:
– “url” Use URL escape codes to encode the coordinates returned.
– “none” Do not escape.
• expand= Expand the bounds of the extents by a specific value. Specified in map coordinates. For example,
[shpext] might return:
• format= Format of the coordinates. Default is “$minx $miny $maxx $maxy”. For example, to add
commas to the coordinates you would use:
[shpext format="$minx,$miny,$maxx,$maxy"]
• precision= The number of decimal places to output for coordinates (default is 0).
[shpminx], [shpminy], [shpmaxx], [shpmaxy] Minimum / maximum X or Y coordinate of shape extent. Available
only when processing query results.
[shpmid] Middle of the extent of current shape. Available only when processing query results.
[shpmidx], [shpmidy] X or Y coordinate of middle of the extent of the current shape. Available only when processing
query results.
[shpidx] Index value of the current shape. Available only when processing query results.
[shpclass] Classindex value of the current shape. Available only when processing query results.
[shpxy formatting options] The list of shape coordinates, with list formatting options, especially useful for SVG.
The default template [shpxy] returns a comma separated list of space delimited of coordinates (i.e. x1 y1, x2 y2,
x3 y3).
Available only when processing query results.
Available attributes (h = header, f=footer, s=separator):
• cs= Coordinate separator, default is comma (“,”).
• xh=, xf= Characters to put before and after the x coordinates (defaults are xh=”” and xf=” “).
• yh= yf= Characters to put before and after the y coordinates (defaults are no characters).
• ph=, pf=, ps= Characters to put before and after and separators between feature parts (e.g. holes, defaults
are no characters).
• sh=, sf= Characters to put before and after a feature (defaults are no
characters)
• precision= The number of decimal places to output for coordinates (default is 0).
• proj= The output projection definition for the coordinates (default is none), a special value of “image”
will convert to image coordinates.
As a simple example:
[shpxy xh="(" yf=")"] will result in: (x1 y1),(x2 y2),(x3 y3)
[tileindex] Index value of the current tile. If no tiles used for the current shape this is replaced by “-1”. Available only
when processing query results.
[item formatting options] An attribute table “item”, with list formatting options. The “name” attribute is required.
Available only when processing query results.
Available attributes:
• name = The name of an attribute, case insenstive. (required)
• precision = The number of decimal places to use for numeric data. Use of this will force display as a
number and will lead to unpredicable results with non-numeric data.
• pattern = Regular expression to compare the value of an item against. The tag is output only if there is a
match.
• uc = Set this attribute to “true” to convert the attribute value to upper case.
• lc = Set this attribute to “true” to convert the attribute value to lower case.
• commify = Set this attribute to “true” to add commas to a numeric value. Again, only useful with numeric
data.
• escape = Default escaping is for HTML, but you can escape for inclusion in a URL (=url), or not escape
at all (=none).
• format = A format string used to output the attribute value. The token “$value” is used to place the value
in a more complex presentation. Default is to output only the value.
• nullformat = String to output if the attribute value is NULL, empty or doesn’t match the pattern (if de-
fined). If not set and any of these conditions occur the item tag is replaced with an empty string.
As a simple example:
[item name="area" precision="2" commify="2" format="Area is $value"]
[attribute name],[attrribute name_esc],[attribute item name_raw] Attribute name from the data table of a queried
layer. Only attributes for the active query layers are accessible. Case must be the same as what is stored in the
data file. ArcView, for example, uses all caps for shapefile field names. Available only when processing query
results.
By default the attributes are encoded especially for HTML representation. In addition the escaped version (for
use in URLs) as well as the raw data is available.
[Join name_attribute name],[Join name_attribute name_esc], [Join name_attribute name_raw] One-to-one
joins: First the join name (as specified in the Mapfile has to be given, second the tables fields can be accessed
similar to the layers attribute data. Available only when processing query results.
By default the attributes are encoded especially for HTML representation. In addition the escaped version (for
use in URLs) as well as the raw data is available.
[join_Join name] One-to-many joins: The more complex variant. If the join type is multiple (one-to-many) the
template is replaced by the set of header, template file and footer specified in the Mapfile.
[metadata_meta data key], [metadata_meta data key_esc] Queried layer meta data access (e.g [meta-
data_projection]
Also available as escaped version.
For query modes that allow for multiple result sets, the following string substitutions are available. For FEATURESE-
LECT and FEATURENSELECT modes the totals a re adjusted so as not to include the selection layer. The selection
layer results ARE available for display to the user.
[nr] Total number of results. Useful in web header and footers. Available only when processing query results.
[nl] Number of layers returning results. Useful in web header and footers. Available only when processing query
results.
[nlr] Total number of results within the current layer. Useful in web header and footers. Available only when pro-
cessing query results.
[rn] Result number within all layers. Starts at 1. Useful in web header and footers. Available only when processing
query results.
[lrn] Result number within the current layer. Starts at 1. Useful in query templates. Available only when processing
query results.
[cl] Current layer name. Useful in layer headers and footers. Available only when processing query results.
A small example to give an idea how to work with templates. Note that it covers MapServer specific templates (e.g.
the [map], [mapext]) and user defined templates (e.g. [htmlroot] or [program]) used to store application settings.
1 <!-- MapServer Template -->
2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
3 "http://www.w3.org/TR/html4/transitional.dtd">
4 <html>
5 <head>
6 <title>MapServer Template Sample</title>
7 </head>
8
9 <body>
10 MapServer Template Sample<br>
11
43 <b>Map Controls</b><br>
44 Set your zoom option:<br>
45 <select name="zoom" size="1">
46 <option value="2" [ z o o m _ 2 _ s e l e c t ] > Zoom in 2 times
47 <option value="1" [ z o o m _ 1 _ s e l e c t ] > Recenter Map
48 <option value="-2" [ z o o m _ - 2 _ s e l e c t ] > Zoom out 2 times
49 </select>
50 <br>
51
63 </form>
64
65 </body>
66 </html>
Table of Contents
• Union Layer
– Description
– Requirements
– Mapfile Configuration
– Feature attributes
– Classes and Styles
– Projections
– Examples
* Mapfile Example
* PHP MapScript Example
5.24.1 Description
Since version 6.0, MapServer has the ability to display features from multiple layers (called ‘source layers’) in a single
mapfile layer. This feature was added through MS RFC 68: Support for combining features from multiple layers.
5.24.2 Requirements
This is a native MapServer option that doesn’t use any external libraries to support it.
In the LAYER definition you may refer to any attributes supported by each of the source layers. In addition to the
source layer attributes the union layer provides the following additional attributes:
1. Combine:SourceLayerName - The name of the source layer the feature belongs to
2. Combine:SourceLayerGroup - The group of the source layer the feature belongs to
During the selection / feature query operations only the ‘Combine:SourceLayerName’ and ‘Com-
bine:SourceLayerGroup’ attributes are provided by default. The set of the provided attributes can manually be
overridden (and further attributes can be exposed) by using the ITEMS processing option (refer to the example above).
We can define the symbology and labelling for the union layers in the same way as for any other layer by specifying the
classes and styles. In addition the STYLEITEM AUTO option is also supported for the union layer, which provides to
display the features as specified at the source layers. The source layers may also use the STYLEITEM AUTO setting
if the underlying data source provides that.
5.24.6 Projections
For speed, it is recommended to always use the same projection for the union layer and source layers. However
MapServer will reproject the source layers to the union layer if requested. (for more information on projections in
MapServer refer to PROJECTION)
5.24.7 Examples
Mapfile Example
The follow example contains 3 source layers in different formats, and one layer (yellow) in a different projection.
The union layer uses the STYLEITEM “AUTO” parameter to draw the styles from the source layers. (in this case
MapServer will reproject the yellow features, in EPSG:4326, for the union layer, which is in EPSG:3978).
MAP
...
PROJECTION
"init=epsg:3978"
END
...
LAYER
NAME ’unioned’
TYPE POLYGON
STATUS DEFAULT
CONNECTIONTYPE U N I ON
CONNECTION "red,green,yellow"
STYLEITEM "AUTO"
# Define an empty class that will be filled at runtime from the color and
# styles read from each source layer.
CLASS
END
PROJECTION
"init=epsg:3978"
END
END
LAYER
NAME ’red’
TYPE POLYGON
STATUS OFF
DATA ’nb.shp’
CLASS
NAME ’red’
STYLE
OUTLINECOLOR 0 0 0
COLOR 255 85 0
END
END
END
LAYER
NAME ’green’
TYPE POLYGON
STATUS OFF
CONNECTIONTYPE OGR
CONNECTION ’ns.mif’
CLASS
NAME ’green’
STYLE
OUTLINECOLOR 0 0 0
COLOR 90 218 71
END
END
END
LAYER
NAME ’yellow’
TYPE POLYGON
STATUS OFF
CONNECTIONTYPE OGR
CONNECTION ’pei.gml’
CLASS
NAME ’yellow’
STYLE
OUTLINECOLOR 0 0 0
COLOR 255 255 0
END
END
PROJECTION
"init=epsg:4326"
END
END
END # Map
<?php
// open map
$oMap = ms_newMapObj( "D:/ms4w/apps/osm/map/osm.map" );
?>
This feature is only available in the CGI version of MapServer through a mapfile pre-processor. If you are using
MapScript, you will have to code the substitution logic into your application yourself (By writing your own pre-
processor).
5.26 WEB
BROWSEFORMAT [mime-type] Format of the interface output, using MapServer CGI. (added to MapServer 4.8.0)
The default value is “text/html”. Example:
BROWSEFORMAT "image/svg+xml"
EMPTY [url] URL to forward users to if a query fails. If not defined the value for ERROR is used.
ERROR [url] URL to forward users to if an error occurs. Ugly old MapServer error messages will appear if this is
not defined
FOOTER [filename] Template to use AFTER anything else is sent. Multiresult query modes only.
HEADER [filename] Template to use BEFORE everything else has been sent. Multiresult query modes only.
IMAGEPATH [path] Path to the temporary directory fro writing temporary files and images. Must be writable by
the user the web server is running as. Must end with a / or depending on your platform.
IMAGEURL [path] Base URL for IMAGEPATH. This is the URL that will take the web browser to IMAGEPATH
to get the images.
LEGENDFORMAT [mime-type] Format of the legend output, using MapServer CGI. (added to MapServer 4.8.0)
The default value is “text/html”. Example:
LEGENDFORMAT "image/svg+xml"
LOG [filename] Since MapServer 5.0 the recommeded parameters to use for debugging are the MAP object’s CON-
FIG and DEBUG parameters instead (see the Debugging MapServer document).
File to log MapServer activity in. Must be writable by the user the web server is running as. Deprecated since
version 5.0.
MAXSCALEDENOM [double] Minimum scale at which this interface is valid. When a user requests a map at
a smaller scale, MapServer automatically returns the map at this scale. This effectively prevents user from
zooming too far out. Scale is given as the denominator of the actual scale fraction, for example for a map at a
scale of 1:24,000 use 24000. Implemented in MapServer 5.0, to replace the deprecated MAXSCALE parameter.
Deprecated since version 5.0.
MAXSCALE [double] - deprecated Since MapServer 5.0 the proper parameter to use is MAXSCALEDENOM in-
stead. The deprecated MAXSCALE is the minimum scale at which this interface is valid. When a user requests
a map at a smaller scale, MapServer automatically returns the map at this scale. This effectively prevents user
from zooming too far out. Scale is given as the denominator of the actual scale fraction, for example for a map
at a scale of 1:24,000 use 24000.
See Also:
Map scale
MAXTEMPLATE [file|url] Template to be used if below the minimum scale for the app (the denominator of the
requested scale is larger than MAXSCALEDENOM), useful for nesting apps.
METADATA This keyword allows for arbitrary data to be stored as name value pairs. This is used with OGC WMS
to define things such as layer title. It can also allow more flexibility in creating templates, as anything you put
in here will be accessible via template tags. Example:
METADATA
title "My layer title"
author "Me!"
END
MINSCALEDENOM [double] Maximum scale at which this interface is valid. When a user reqests a map at a larger
scale, MapServer automatically returns the map at this scale. This effectively prevents the user from zooming
in too far. Scale is given as the denominator of the actual scale fraction, for example for a map at a scale of
1:24,000 use 24000. Implemented in MapServer 5.0, to replace the deprecated MINSCALE parameter.
See Also:
Map scale
MINSCALE [double] - deprecated Since MapServer 5.0 the proper parameter to use is MINSCALEDENOM in-
stead. The deprecated MINSCALE is the maximum scale at which this interface is valid. When a user reqests a
map at a larger scale, MapServer automatically returns the map at this scale. This effectively prevents the user
from zooming in too far. Scale is given as the denominator of the actual scale fraction, for example for a map at
a scale of 1:24,000 use 24000. Deprecated since version 5.0.
MINTEMPLATE Template to be used if above the maximum scale for the app (the denominator of the requested
scale is smaller than MINSCALEDENOM), useful for nesting apps.
QUERYFORMAT [mime-type] Format of the query output. (added to MapServer 4.8.0) This works for
mode=query (using query templates in CGI mode), but not for mode=browse. The default value is “text/html”.
Example:
QUERYFORMAT "image/svg+xml"
TEMPLATE [filename|url] Template file or URL to use in presenting the results to the user in an interactive mode
(i.e. map generates map and so on ... )
5.27 Notes
MapScript
Release 6.0
Date May 12, 2011
6.1 Introduction
This is language agnostic documentation for the MapScript interface to MapServer generated by SWIG. This document
is intended for developers and to serve as a reference for writers of more extensive, language specific documentation
located at Mapfile
6.1.1 Appendices
Classes will be documented in alphabetical order in the manner outlined below. Attributes and methods will be
formatted as definition lists with the attribute or method as item, the type or return type as classifier, and a concise
description. To make the document as agnostic as possible, we refer to the following types: int, float, and string. There
are yet no mapscript methods that return arrays or sequences or accept array or sequence arguments.
We will use the SWIG term immutable to indicate that an attribute’s value is read-only.
6.1.3 fooObj
fooObj Attributes
171
MapServer Documentation, Release 6.0
Attribute name are completely lower case. Multiple words are packed together like outlinecolor.
Note that because of the way that mapscript is generated many confusing, meaningless, and even dangerous attributes
are creeping into objects. See outputFormatObj.refcount for example. Until we get a grip on the structure members
we are exposing to SWIG this problem will continue to grow.
fooObj Methods
There’s no point in duplicating the MapServer Mapfile Reference, which remains the primary reference for mapscript
class attributes.
Contents
• SWIG MapScript API Reference
– Introduction
* Appendices
* Documentation Elements
* fooObj
* Additional Documentation
– MapScript Functions
– MapScript Classes
* classObj
* colorObj
* errorObj
* fontSetObj
* hashTableObj
* imageObj
* intarray
* labelCacheMemberObj
* labelCacheObj
* labelObj
* layerObj
* legendObj
* lineObj
* mapObj
* markerCacheMemberObj
* outputFormatObj
* OWSRequest
* pointObj
* projectionObj
* rectObj
* referenceMapObj
* resultCacheMemberObj
* resultCacheObj
* scalebarObj
* shapefileObj
* shapeObj
* styleObj
* symbolObj
* symbolSetObj
* webObj
6.2.1 Introduction
This is language agnostic documentation for the mapscript interface to MapServer generated by SWIG. This document
is intended for developers and to serve as a reference for writers of more extensive, language specific documentation
in DocBook format for the MDP.
Appendices
Documentation Elements
Classes will be documented in alphabetical order in the manner outlined below. Attributes and methods will be
formatted as definition lists with the attribute or method as item, the type or return type as classifier, and a concise
description. To make the document as agnostic as possible, we refer to the following types: int, float, and string. There
are yet no mapscript methods that return arrays or sequences or accept array or sequence arguments.
We will use the SWIG term immutable to indicate that an attribute’s value is read-only.
fooObj
fooObj Attributes
fooObj Methods
Additional Documentation
There’s no point in duplicating the MapServer Mapfile Reference, which remains the primary reference for mapscript
class attributes.
msCleanup() [void] msCleanup() attempts to recover all dynamically allocated resources allocated by MapServer
code and dependent libraries. It it used primarily for final cleanup in scripts that need to do memory leak testing
to get rid of “noise” one-time allocations. It should not normally be used by production code.
msGetVersion() [string] Returns a string containing MapServer version information, and details on what optional
components are built in. The same report as produced by “mapserv -v”.
msGetVersionInt() [int] Returns the MapServer version number (x.y.z) as an integer (x*10000 + y*100 + z). (New
in v5.0) e.g. V5.4.3 would return 50403.
msResetErrorList() [void] Clears the current error stack.
msIO_installStdoutToBuffer() [void] Installs a mapserver IO handler directing future stdout output to a memory
buffer.
msIO_installStdinFromBuffer() [void] Installs a mapserver IO handler directing future stdin reading (ie. post re-
quest capture) to come from a buffer.
msIO_resetHandlers() [void] Resets the default stdin and stdout handlers in place of “buffer” based handlers.
msIO_getStdoutBufferString() [string] Fetch the current stdout buffer contents as a string. This method does not
clear the buffer.
msIO_getStdoutBufferBytes() [binary data] Fetch the current stdout buffer contents as a binary buffer. The exact
form of this buffer will vary by mapscript language (eg. string in Python, byte[] array in Java and C#, unhandled
in perl)
msIO_stripStdoutBufferContentType() [string] Strip the Content-type header off the stdout buffer if it has one, and
if a content type is found it is return (otherwise NULL/None/etc).
msIO_stripStdoutBufferContentHeaders(): void Strip all Content-* headers off the stdout buffer if it has ones.
classObj
The other important associations for classObj are with styleObj, labelObj, and hashTableObj.
+-------+ 1 0..* +-------+
| Class | ---------> | Style |
+-------+ +-------+
+-------+ 1 1 +-----------+
| Class | ---------> | HashTable |
+-------+ | -- |
| metadata |
+-----------+
Multiple class styles are now supported in 4.1. See the styleObj section for details on use of multiple class styles.
classObj Attributes
classObj Methods
new classObj( [ layerObj parent_layer=NULL ] ) [classObj] Create a new child classObj instance at the tail (high-
est index) of the class array of the parent_layer. A class can be created outside the context of a parent layer by
omitting the single constructor argument.
clone( ) [classObj] Return an independent copy of the class without a parent layer.
createLegendIcon( mapObj map, layerObj layer, int width, int height ) [imageObj] Draw and return a new leg-
end icon.
drawLegendIcon( mapObj map, layerObj layer, int width, int height, imageObj image, int dstx, int dsty ) [int]
Draw the legend icon onto image at dstx, dsty. Returns MS_SUCCESS or MS_FAILURE.
getExpressionString() [string] Return a string representation of the expression enclosed in the quote characters ap-
propriate to the expression type.
getFirstMetaDataKey() [string] Returns the first key in the metadata hash table. With getNextMetaDataKey(), pro-
vides an opaque iterator over keys.
getMetaData( string key ) [string] Return the value of the classObj metadata at key.
getNextMetaDataKey( string lastkey ) [string] Returns the next key in the metadata hash table or NULL if lastkey
is the last valid key. If lastkey is NULL, returns the first key of the metadata hash table.
Note: getFirstMetaDataKey(), getMetaData(), and getNextMetaDataKey() are deprecated and will be removed in a
future version. Replaced by direct metadata access, see hashTableObj.
getStyle( int index ) [styleObj] Return a reference to the styleObj at index in the styles array.
See the styleObj section for more details on multiple class styles.
getTextString() [string] Return a string representation of the text enclosed in the quote characters appropriate to the
text expression type (logical or simple string).
insertStyle( styleObj style [, int index=-1 ] ) [int] Insert a copy of style into the styles array at index index. Default
is -1, or the end of the array. Returns the index at which the style was inserted.
moveStyleDown( int index ) [int] Swap the styleObj at index with the styleObj index + 1.
moveStyleUp( int index ) [int] Swap the styleObj at index with the styleObj index - 1.
removeStyle( int index ) [styleObj] Remove the styleObj at index from the styles array and return a copy.
setExpression( string expression ) [int] Set expression string where expression is a MapServer regular, logical or
string expression. Returns MS_SUCCESS or MS_FAILUIRE.
setMetaData( string key, string value ) [int] Insert value into the classObj metadata at key. Returns MS_SUCCESS
or MS_FAILURE.
Note: setMetaData() is deprecated and will be removed in a future version. Replaced by direct metadata access, see
hashTableObj.
setText( string text ) [int] Set text string where text is a MapServer text expression. Returns MS_SUCCESS or
MS_FAILUIRE.
Note: Older versions of MapScript (pre-4.8) featured the an undocumented setText() method that required a layerObj
be passed as the first argument. That argument was completely bogus and has been removed.
colorObj
Since the 4.0 release, MapServer colors are instances of colorObj. A colorObj may be a lone object or an attribute of
other objects and have no other associations.
colorObj Attributes
colorObj Methods
new colorObj( [ int red=0, int green=0, int blue=0, int pens=-4 ] ) [colorObj] Create a new instance. The color ar-
guments are optional.
setRGB( int red, int green, int blue ) [int] Set all three RGB components. Returns MS_SUCCESS or
MS_FAILURE.
setHex( string hexcolor ) [int] Set the color to values specified in case-independent hexadecimal notation. Calling
setHex(‘#ffffff’) assigns values of 255 to each color component. Returns MS_SUCCESS or MS_FAILURE.
toHex() [string] Complement to setHex, returning a hexadecimal representation of the color components.
errorObj
This class allows inspection of the MapServer error stack. Only needed for the Perl module as the other language
modules expose the error stack through exceptions.
errorObj Attributes
errorObj Methods
next [errorObj] Returns the next error in the stack or NULL if the end has been reached.
fontSetObj
fontSetObj Attributes
fontSetObj Methods
None
hashTableObj
A hashTableObj is a very simple mapping of case-insensitive string keys to single string values. Map, Layer, and Class
metadata have always been hash hables and now these are exposed directly. This is a limited hash that can contain no
more than 41 values.
hashTableObj Attributes
hashTableObj Methods
imageObj
imageObj Attributes
imageObj Methods
new imageObj( int width, int height [, outputFormatObj format=NULL [, string filename=NULL ] ] )
[imageObj] Create new instance of imageObj. If filename is specified, an imageObj is created from the
file and any specified width, height, and format parameters will be overridden by values of the image in
filename. Otherwise, if format is specified an imageObj is created using that format. See the format attribute
above for details. If filename is not specified, then width and height should be specified.
getBytes() [binary data] Returns the image contents as a binary buffer. The exact form of this buffer will vary by
mapscript language (eg. string in Python, byte[] array in Java and C#, unhandled in perl)
getSize() [int] Resturns the size of the binary buffer representing the image buffer.
Note: the getSize method is inefficient as it does a call to getBytes and then computes the size of the byte array. The
byte array is then immediately discarded. In most cases it is more efficient to call getBytes directly.
save( string filename [, mapObj parent_map=NULL ] ) [int] Save image to filename. The optional parent_map
parameter must be specified if saving GeoTIFF images.
write( [ FILE file=NULL ] ) [int] Write image data to an open file descriptor or, by default, to stdout. Returns
MS_SUCCESS or MS_FAILURE.
Note: This method is current enabled for Python and C# only. C# supports writing onto a Stream object. User-
contributed typemaps are needed for Perl, Ruby, and Java.
Note: The free() method of imageObj has been deprecated. In MapServer revisions 4+ all instances of imageObj will
be properly disposed of by the interpreter’s garabage collector. If the application can’t wait for garabage collection,
then the instance can simply be deleted or undef’d.
intarray
An intarray is a utility class generated by SWIG useful for manipulating map layer draw-
ing order. See mapObj::getLayersDrawingOrder for discussion of mapscript use and see
http://www.swig.org/Doc1.3/Library.html#Library_nn5 for a complete reference.
intarray Attributes
None
intarray Methods
new intarray( int numitems ) [intarray] Returns a new instance of the specified length.
labelCacheMemberObj
labelCacheMemberObj Attributes
labelCacheMemberObj Methods
None.
Note: No real scripting control over labeling currently, but there may be some interesting new possibilities if users
have control over labeling text, position, and status.
labelCacheObj
Set of a map’s cached labels. Has no other existence other than as a ‘labelcache’ attribute of a mapObj. Associated
with labelCacheMemberObj and markerCacheMemberObj.
+------------+ 1 0..* +-------------------+
| LabelCache | ---------> | LabelCacheMember |
+------------+ + ----------------- +
| MarkerCacheMember |
+-------------------+
labelCacheObj Attributes
labelCacheObj Methods
labelObj
labelObj Attributes
maxsize [int] Maximum height in pixels for scaled labels. See symbolscale attribute of layerObj.
mindistance [int] Minimum distance in pixels between duplicate labels.
minfeaturesize [int] Features of this size of greater will be labeled.
minsize [int] Minimum height in pixels.
offsetx [int] Horizontal offset of label.
offsety [int] Vertical offset of label.
outlinecolor [colorObj] Color of one point outline.
partials [int] MS_TRUE (default) or MS_FALSE. Whether or not labels can flow past the map edges.
position [int] MS_UL, MS_UC, MS_UR, MS_CL, MS_CC, MS_CR, MS_LL, MS_LC, MS_LR, or MS_AUTO.
shadowcolor [colorObj] Color of drop shadow.
shadowsizex [int] Horizontal offset of drop shadow in pixels.
shadowsizey [int] Vertical offset of drop shadow in pixels.
size [int] Annotation height in pixels.
type [int] MS_BITMAP or MS_TRUETYPE.
wrap [string] Character on which legend text will be broken to make multi-line legends.
labelObj Methods
None
layerObj
A layerObj is associated with mapObj. In the most recent revision, an intance of layerObj can exist outside of a
mapObj.
+-------+ 0..* 0..1 +-----+
| Layer | <--------> | Map |
+-------+ +-----+
and hashTableObj
+-------+ 1 1 +-----------+
| Layer | ---------> | HashTable |
+-------+ | -- |
| metadata |
+-----------+
layerObj Attributes
bandsitem [string] The attribute from the index file used to select the source raster band(s) to be used. Normally
NULL for default bands processing.
classitem [string] The attribute used to classify layer data.
connection [string] Layer connection or DSN.
connectiontype [int] See MS_CONNECTION_TYPE in mapserver.h for possible values. When setting the connec-
tion type setConnectionType() should be used in order to initialize the layer vtable properly.
data [string] Layer data definition, values depend upon connectiontype.
debug [int] Enable debugging of layer. MS_ON or MS_OFF (default).
dump [int] Switch to allow mapserver to return data in GML format. MS_TRUE or MS_FALSE. Default is
MS_FALSE.
extent [rectObj] optional limiting extent for layer features.
filteritem [string] Attribute defining filter.
footer [string] TODO
group [string] Name of a group of layers.
header [string] TODO
index [int immutable] Index of layer within parent map’s layers array.
labelangleitem [string] Attribute defining label angle.
labelcache [int] MS_ON or MS_OFF. Default is MS_ON.
labelitem [string] Attribute defining feature label text.
labelmaxscale [float] Maximum scale at which layer will be labeled.
labelminscale [float] Minimum scale at which layer will be labeled.
labelrequires [string] Logical expression.
labelsizeitem [string] Attribute defining label size.
map [mapObj immutable] Reference to parent map.
maxfeatures [int] Maximum number of layer features that will be drawn. For shapefile data this means the first N
features where N = maxfeatures.
maxscale [float] Maximum scale at which layer will be drawn.
metadata [hashTableObj immutable] Layer metadata.
minscale [float] Minimum scale at which layer will be drawn.
name [string] Unique identifier for layer.
numclasses [int immutable] Number of layer classes.
numitems [int immutable] Number of layer feature attributes (items).
numjoins [int immutable] Number of layer joins.
numprocessing [int immutable] Number of raster processing directives.
offsite [colorObj] transparent pixel value for raster layers.
postlabelcache [int] MS_TRUE or MS_FALSE. Default is MS_FALSE.
layerObj Methods
new layerObj( [ mapObj parent_map=NULL ] ) [layerObj] Create a new layerObj in parent_map. The layer index
of the new layerObj will be equal to the parent_map numlayers - 1. The parent_map arg is now optional and
Layers can exist outside of a Map.
addFeature( shapeObj shape ) [int] Add a new inline feature on a layer. Returns -1 on error. TODO: Is this similar
to inline features in a mapfile? Does it work for any kind of layer or connection type?
addProcessing( string directive ) [void] Adds a new processing directive line to a layer, similar to the PROCESSING
directive in a map file. Processing directives supported are specific to the layer type and underlying renderer.
applySLD( string sld, string stylelayer ) [int] Apply the SLD document to the layer object. The matching between
the sld document and the layer will be done using the layer’s name. If a namedlayer argument is passed (argu-
ment is optional), the NamedLayer in the sld that matchs it will be used to style the layer. See SLD HOWTO
for more information on the SLD support.
applySLDURL( string sld, string stylelayer ) [int] Apply the SLD document pointed by the URL to the layer object.
The matching between the sld document and the layer will be done using the layer’s name. If a namedlayer
argument is passed (argument is optional), the NamedLayer in the sld that matchs it will be used to style the
layer. See SLD HOWTO for more information on the SLD support.
clearProcessing() [int] Clears the layer’s raster processing directives. Returns the subsequent number of directives,
which will equal MS_SUCCESS if the directives have been cleared.
clone() [layerObj] Return an independent copy of the layer with no parent map.
close() [void] Close the underlying layer.
capabilities. MapServer WMS servers support only “MIME” (and should support “GML.1” soon). Returns “”
and outputs a warning if layer is not a WMS layer or if it is not queriable.
insertClass( classObj class [, int index=-1 ] ) [int] Insert a copy of the class into the layer at the requested index.
Default index of -1 means insertion at the end of the array of classes. Returns the index at which the class was
inserted.
isVisible( ) [int] Returns MS_TRUE or MS_FALSE after considering the layer status, minscale, and maxscale within
the context of the parent map.
moveClassDown( int class ) [int] The class specified by the class index will be moved up into the array of layers.
Returns MS_SUCCESS or MS_FAILURE. ex. moveClassDown(1) will have the effect of moving class 1 down
to postion 2, and the class at position 2 will be moved to position 1.
moveClassUp( int class ) [int] The class specified by the class index will be moved up into the array of layers. Re-
turns MS_SUCCESS or MS_FAILURE. ex. moveClassUp(1) will have the effect of moving class 1 up to
postion 0, and the class at position 0 will be moved to position 1.
nextShape( ) [shapeObj] Called after msWhichShapes has been called to actually retrieve shapes within a given area
returns a shape object or MS_FALSE
example of usage :
mapObj map = new mapObj("d:/msapps/gmap-ms40/htdocs/gmap75.map");
layerObj layer = map.getLayerByName(’road’);
int status = layer.open();
status = layer.whichShapes(map.extent);
shapeObj shape;
while ((shape = layer.nextShape()) != null)
{
...
}
layer.close();
open() [void] Opens the underlying layer. This is required before operations like getFeature() will work, but is not
required before a draw or query call.
Note: promote() is eliminated in MapServer 4.4.
queryByAttributes( mapObj map, string qitem, string qstring, int mode ) [int] Query layer for shapes that inter-
sect current map extents. qitem is the item (attribute) on which the query is performed, and qstring is the expres-
sion to match. The query is performed on all the shapes that are part of a CLASS that contains a TEMPLATE
value or that match any class in a layer that contains a LAYER TEMPLATE value.
Note that the layer’s FILTER/FILTERITEM are ignored by this function. Mode is MS_SINGLE or
MS_MULTIPLE depending on number of results you want. Returns MS_SUCCESS if shapes were found
or MS_FAILURE if nothing was found or if some other error happened.
queryByFeatures( mapObj map, int slayer ) [int] Perform a query set based on a previous set of results from an-
other layer. At present the results MUST be based on a polygon layer. Returns MS_SUCCESS if shapes were
found or MS_FAILURE if nothing was found or if some other error happened
queryByIndex( mapObj map, int shapeindex, int tileindex [, int bAddToQuery=MS_FALSE ]) [int] Pop a
query result member into the layer’s result cache. By default clobbers existing cache. Returns MS_SUCCESS
or MS_FAILURE.
queryByPoint( mapObj map, pointObj point, int mode, float buffer ) [int] Query layer at point location specified
in georeferenced map coordinates (i.e. not pixels). The query is performed on all the shapes that are part of a
CLASS that contains a TEMPLATE value or that match any class in a layer that contains a LAYER TEMPLATE
value. Mode is MS_SINGLE or MS_MULTIPLE depending on number of results you want. Passing buffer <=0
defaults to tolerances set in the map file (in pixels) but you can use a constant buffer (specified in ground units)
instead. Returns MS_SUCCESS if shapes were found or MS_FAILURE if nothing was found or if some other
error happened.
queryByRect( mapObj map, rectObj rect ) [int] Query layer using a rectangle specified in georeferenced map co-
ordinates (i.e. not pixels). The query is performed on all the shapes that are part of a CLASS that contains
a TEMPLATE value or that match any class in a layer that contains a LAYER TEMPLATE value. Returns
MS_SUCCESS if shapes were found or MS_FAILURE if nothing was found or if some other error happened.
queryByShape( mapObj map, shapeObj shape ) [int] Query layer based on a single shape, the shape has to be a
polygon at this point. Returns MS_SUCCESS if shapes were found or MS_FAILURE if nothing was found or
if some other error happened
removeClass( int index ) [classObj] Removes the class indicated and returns a copy, or NULL in the case of a failure.
Note that subsequent classes will be renumbered by this operation. The numclasses field contains the number
of classes available.
removeMetaData( string key ) [int] Delete the metadata hash at key. Returns MS_SUCCESS or MS_FAILURE.
Note: removeMetaData() is deprecated and will be removed in a future version. Replaced by direct metadata access,
see hashTableObj.
setConnectionType(int connectiontype, string library_str) [int] Changes the connectiontype of the layer and recre-
ates the vtable according to the new connection type. This method should be used instead of setting the con-
nectiontype parameter directly. In case when the layer.connectiontype = MS_PLUGIN the library_str parameter
should also be specified so as to select the library to load by mapserver. For the other connection types this
parameter is not used.
setExtent( float minx, float miny, float maxx, float maxy ) [int] Sets the extent of a layer. Returns MS_SUCCESS
or MS_FAILURE.
setFilter( string filter ) [int] Sets a filter expression similarly to the FILTER expression in a map file. Returns
MS_SUCCESS on success or MS_FAILURE if the expression fails to parse.
setMetaData( string key, string value ) [int] Assign value to the metadata hash at key. Return MS_SUCCESS or
MS_FAILURE.
Note: setMetaData() is deprecated and will be removed in a future version. Replaced by direct metadata access, see
hashTableObj.
setProcessingKey( string key, string value ) [void] Adds or replaces a processing directive of the form “key=value”.
Unlike the addProcessing() call, this will replace an existing processing directive for the given key value. Pro-
cessing directives supported are specific to the layer type and underlying renderer.
setProjection( string proj4 ) [int] Set the layer projection using a PROJ.4 format projection definition (ie.
“+proj=utm +zone=11 +datum=WGS84” or “init=EPSG:26911”). Returns MS_SUCCESS or MS_FAILURE.
setWKTProjection( string wkt ) [int] Set the layer projection using OpenGIS Well Known Text format. Returns
MS_SUCCESS or MS_FAILURE.
int whichShapes( rectObj rect ) [int] Performs a spatial, and optionally an attribute based feature search. The func-
tion basically prepares things so that candidate features can be accessed by query or drawing functions (eg using
nextShape function). Returns MS_SUCCESS or MS_FAILURE.
resultsGetShape(int shapeindex [, int tileindex = -1]) [shapeObj] Retrieve shapeObj from a layer’s resultset by in-
dex. Tileindex is optional and is used only for tiled shapefiles, Simply omit or pass tileindex = -1 for other data
sources. Added in MapServer 5.6.0 due to the one-pass query implementation.
legendObj
legendObj Attributes
legendObj Methods
None
lineObj
lineObj Attributes
lineObj Methods
add(pointObj point) [int] Add point to the line. Returns MS_SUCCESS or MS_FAILURE.
get(int index) [pointObj] Return reference to point at index.
project(projectionObj proj_in, projectionObj proj_out) [int] Transform line in place from proj_in to proj_out. Re-
turns MS_SUCCESS or MS_FAILURE.
set(int index, pointObj point) [int] Set the point at index to point. Returns MS_SUCCESS or MS_FAILURE.
mapObj
outputFormatObj.
+-----+ 1 1..* +--------------+
| Map | ---------> | OutputFormat |
+-----+ +------------- +
mapObj Attributes
mapObj Methods
new mapObj( [ string filename=” ] ) [mapObj] Create a new instance of mapObj. Note that the filename is now
optional.
appendOutputFormat( outputFormatObj format ) [int] Attach format to the map’s output format list. Returns the
updated number of output formats.
Note: This method is poorly named and too indirect. It is preferrable to use the getSymbolByName method of
symbolSetObj, which really does return a symbolObj reference, or use the index method of symbolSetObj to get a
symbol’s index number.
insertLayer( layerObj layer [, int nIndex=-1 ] ) [int] Insert a copy of layer into the Map at index nIndex. The de-
fault value of nIndex is -1, which means the last possible index. Returns the index of the new Layer, or -1 in the
case of a failure.
loadMapContext( string filename [, int useUniqueNames=MS_FALSE ] ) [int] Load an OGC map context file to
define extents and layers of a map.
loadOWSParameters( OWSRequest request [, string version=‘1.1.1’ ] ) [int] Load OWS request parameters
(BBOX, LAYERS, &c.) into map. Returns MS_SUCCESS or MS_FAILURE.
loadQuery( string filename ) [int] Load a saved query. Returns MS_SUCCESS or MS_FAILURE.
moveLayerDown( int layerindex ) [int] Move the layer at layerindex down in the drawing order array, meaning that
it is drawn later. Returns MS_SUCCESS or MS_FAILURE.
moveLayerUp( int layerindex ) [int] Move the layer at layerindex up in the drawing order array, meaning that it is
drawn earlier. Returns MS_SUCCESS or MS_FAILURE.
nextLabel( ) [labelCacheMemberObj] Return the next label from the map’s labelcache, allowing iteration over labels.
Note: nextLabel() is deprecated and will be removed in a future version. Replaced by getLabel().
getLabel( int labelindex ) [labelCacheMemberObj] Return label at specified index from the map’s labelcache.
OWSDispatch( OWSRequest req ) [int] Processes and executes the passed OpenGIS Web Services request on the
map. Returns MS_DONE (2) if there is no valid OWS request in the req object, MS_SUCCESS (0) if an OWS
request was successfully processed and MS_FAILURE (1) if an OWS request was not successfully processed.
OWS requests include WMS, WFS, WCS and SOS requests supported by MapServer. Results of a dispatched
request are written to stdout and can be captured using the msIO services (ie. msIO_installStdoutToBuffer() and
msIO_getStdoutBufferString())
prepareImage( ) [imageObj] Returns an imageObj initialized to map extents and outputformat.
prepareQuery( ) [void] TODO this function only calculates the scale or am I missing something?
processLegendTemplate( string names[], string values[], int numitems ) [string] Process MapServer legend tem-
plate and return HTML.
processQueryTemplate( string names[], string values[], int numitems ) [string] Process MapServer query tem-
plate and return HTML.
processTemplate( int generateimages, string names[], string values[], int numitems ) [string] Process MapServer
template and return HTML.
Note: None of the three template processing methods will be useable unless the proper typemaps are implemented in
the module for the target language. Currently the typemaps are not implemented.
queryByFeatures( int layerindex ) [int] Query map layers, result sets contain features that intersect or are con-
tained within the features in the result set of the MS_LAYER_POLYGON type layer at layerindex. Returns
MS_SUCCESS or MS_FAILURE.
queryByPoint( pointObj point, int mode, float buffer ) [int] Query map layers, result sets contain one or more
features, depending on mode, that intersect point within a tolerance buffer. Returns MS_SUCCESS or
MS_FAILURE.
queryByRect( rectObj rect ) [int] Query map layers, result sets contain features that intersect or are contained within
rect. Returns MS_SUCCESS or MS_FAILURE.
queryByShape( shapeObj shape ) [int] Query map layers, result sets contain features that intersect or are contained
within shape. Returns MS_SUCCESS or MS_FAILURE.
setWKTProjection( string wkt ) [int] Sets map projection from OGC definition wkt.
zoomPoint( int zoomfactor, pointObj imgpoint, int width, int height, rectObj extent, rectObj maxextent )
[int] Zoom by zoomfactor to imgpoint in pixel units within the image of height and width dimensions and
georeferenced extent. Zooming can be constrained to a maximum maxextent. Returns MS_SUCCESS or
MS_FAILURE.
zoomRectangle( rectObj imgrect, int width, int height, rectObj extent, rectObj maxextent ) : int Zoom to a pixel
coordinate rectangle in the image of width and height dimensions and georeferencing extent. Zooming can be
constrained to a maximum maxextent. The imgrect rectangle contains the coordinates of the LL and UR coordi-
nates in pixel: the maxy in the rect object should be < miny value. Returns MS_SUCCESS or MS_FAILURE.
------- UR (values in the rect object : maxx, maxy)
| |
| |
| |
------
LL (values in the rectobject minx, miny)
zoomScale( float scale, pointObj imgpoint, int width, int height, rectObj extent, rectObj maxextent) [int] Like
the previous methods, but zooms to the point at a specified scale.
markerCacheMemberObj
markerCacheMemberObj Attributes
markerCacheMemberObj Methods
None.
outputFormatObj
outputFormatObj Attributes
bands [int] The number of bands in the raster. Only used for the “raw” modes, MS_IMAGEMODE_BYTE,
MS_IMAGEMODE_INT16, and MS_IMAGEMODE_FLOAT32. Normally set via the BAND_COUNT for-
matoption ... this field should be considered read-only.
driver [string] A string such as ‘GD/PNG’ or ‘GDAL/GTiff’.
extension [string] Format file extension such as ‘png’.
imagemode [int] MS_IMAGEMODE_PC256, MS_IMAGEMODE_RGB, MS_IMAGEMODE_RGBA,
MS_IMAGEMODE_INT16, MS_IMAGEMODE_FLOAT32, MS_IMAGEMODE_BYTE, or
MS_IMAGEMODE_NULL.
mimetype [string] Format mimetype such as ‘image/png’.
name [string] A unique identifier.
renderer [int] MS_RENDER_WITH_GD, MS_RENDER_WITH_SWF, MS_RENDER_WITH_RAWDATA,
MS_RENDER_WITH_PDF, or MS_RENDER_WITH_IMAGEMAP. Normally set internally based on the
driver and some other setting in the constructor.
transparent [int] MS_ON or MS_OFF.
outputFormatObj Methods
new outputFormatObj( string driver [, string name=driver ] ) [outputFormatObj] Create new instance. If name is
not provided, the value of driver is used as a name.
getOption( string key [, string value=”” ] ) [string] Return the format option at key or value if key is not a valid hash
index.
setExtension( string extension ) [void] Set file extension for output format such as ‘png’ or ‘jpg’. Method could
probably be deprecated since the extension attribute is mutable.
setMimetype( string mimetype ) [void] Set mimetype for output format such as ‘image/png’ or ‘image/jpeg’.
Method could probably be deprecated since the mimetype attribute is mutable.
setOption( string key, string value ) [void] Set the format option at key to value. Format options are mostly driver
specific.
validate() [int] Checks some internal consistency issues, and returns MS_TRUE if things are OK and MS_FALSE if
there are problems. Some problems are fixed up internally. May produce debug output if issues encountered.
OWSRequest
Not associated with other mapscript classes. Serves as a message intermediary between an application and
MapServer’s OWS capabilities. Using it permits creation of lightweight WMS services:
wms_map = mapscript.mapObj(’wms.map’)
wms_request = mapscript.OWSRequest()
OWSRequest Attributes
NumParams [int immutable] Number of request parameters. Eventually should be changed to numparams lowercase
like other attributes.
postrequest [string] TODO
type [int] MS_GET_REQUEST or MS_POST_REQUEST.
OWSRequest Methods
pointObj
pointObj Attributes
m [float] Measure. Meaningful only for measured shapefiles. Given value -2e38 if not otherwise assigned to indicate
“nodata”.
x [float] Easting
y [float] Northing
z [float] Elevation
pointObj Methods
new pointObj( [ float x=0.0, float y=0.0, float z=0.0, float m=-2e38 ] ) [pointObj] Create new instance. Easting,
northing, and measure arguments are optional.
distanceToPoint( pointObj point ) [float] Returns the distance to point.
distanceToSegment( pointObj point1, pointObj point2 ) [float] Returns the minimum distance to a hypothetical
line segment connecting point1 and point2.
distanceToShape( shapeObj shape ) [float] Returns the minimum distance to shape.
draw( mapObj map, layerObj layer, imageObj image, int classindex, string text ) [int] Draw the point using the
styles defined by the classindex class of layer and labeled with string text. Returns MS_SUCCESS or
MS_FAILURE.
project( projectionObj proj_in, projectionObj proj_out ) [int] Reproject point from proj_in to proj_out. Transfor-
mation is done in place. Returns MS_SUCCESS or MS_FAILURE.
setXY( float x, float y [, float m=2e-38 ] ) [int] Set spatial coordinate and, optionally, measure values simultaneously.
The measure will be set only if the value of m is greater than the ESRI measure no-data value of 1e-38. Returns
MS_SUCCESS or MS_FAILURE.
setXYZ( float x, float y, float z [, float m=-2e38 ] ) [int] Set spatial coordinate and, optionally, measure values si-
multaneously. The measure will be set only if the value of m is greater than the ESRI measure no-data value of
-1e38. Returns MS_SUCCESS or MS_FAILURE.
setXYZM( float x, float y, float z, float m ) [int] Set spatial coordinate and, optionally, measure values simultane-
ously. The measure will be set only if the value of m is greater than the ESRI measure no-data value of -1e38.
Returns MS_SUCCESS or MS_FAILURE.
toString() [string] Return a string formatted like
{ ’x’: %f , ’y’: %f, ’z’: %f }
with the coordinate values substituted appropriately. Python users can get the same effect via the pointObj
__str__ method
>>> p = mapscript.pointObj(1, 1)
>>> str(p)
{ ’x’: 1.000000 , ’y’: 1.000000, ’z’: 1.000000 }
projectionObj
This class is not really fully implemented yet. MapServer’s Maps and Layers have Projection attributes, and these
are C projectionObj structures, but are not directly exposed by the mapscript module. Currently we have to do some
round-a-bout logic like this
point.project(projectionObj(mapobj.getProjection(),
projectionObj(layer.getProjection())
projectionObj Attributes
projectionObj Methods
new projectionObj( string proj4 ) [projectionObj] Create new instance of projectionObj. Input parameter proj4 is a
PROJ.4 definition string such as “init=EPSG:4269”.
getUnits() [int] Returns the units of a projection object. Returns -1 on error.
rectObj
A rectObj may be a lone object or an attribute of another object and has no other associations.
rectObj Attributes
rectObj Methods
new rectObj( [ float minx=-1.0, float miny=-1.0, float maxx=-1.0, float maxy=-1.0, int imageunits=MS_FALSE ] )
[rectObj] Create new instance. The four easting and northing arguments are optional and default to -1.0. Note
the new optional fifth argument which allows creation of rectangles in image (pixel/line) units which are also
tested for validity.
draw( mapObj map, layerObj layer, imageObj img, int classindex, string text ) [int] Draw rectangle into img us-
ing style defined by the classindex class of layer. The rectangle is labeled with the string text. Returns
MS_SUCCESS or MS_FAILURE.
getCenter() [pointObj] Return the center point of the rectagle.
project( projectionObj proj_in, projectionObj proj_out ) [int] Reproject rectangle from proj_in to proj_out.
Transformation is done in place. Returns MS_SUCCESS or MS_FAILURE.
toPolygon() [shapeObj] Convert to a polygon of five vertices.
toString() [string] Return a string formatted like
{ ’minx’: %f , ’miny’: %f , ’maxx’: %f , ’maxy’: %f }
with the bounding values substituted appropriately. Python users can get the same effect via the rectObj __str__
method
>>> r = mapscript.rectObj(0, 0, 1, 1)
>>> str(r)
{ ’minx’: 0 , ’miny’: 0 , ’maxx’: 1 , ’maxy’: 1 }
referenceMapObj
referenceMapObj Attributes
referenceMapObj Methods
None
resultCacheMemberObj
Has no associations with other MapScript classes and has no methods. By using several indexes, a resultCacheMem-
berObj refers to a single layer feature.
resultCacheMemberObj Attributes
classindex [int immutable] The index of the layer class into which the feature has been classified.
shapeindex [int immutable] Index of the feature within the layer.
tileindex [int immutable] Meaningful for tiled layers only, index of the shapefile data tile.
resultCacheObj
See querying-HOWTO.txt for extra guidance in using the new 4.4 query API.
resultCacheObj Attributes
resultCacheObj Methods
getResult( int i ) [resultCacheObj] Returns the result at index i, like layerObj::getResult, or NULL if index is outside
the range of results.
scalebarObj
scalebarObj Attributes
scalebarObj Methods
None
shapefileObj
shapefileObj Attributes
shapefileObj Methods
new shapefileObj( string filename [, int type=-1 ] ) [shapefileObj] Create a new instance. Omit the type argument
or use a value of -1 to open an existing shapefile.
add( shapeObj shape ) [int] Add shape to the shapefile. Returns MS_SUCCESS or MS_FAILURE.
get( int i, shapeObj shape ) [int] Get the shapefile feature from index i and store it in shape. Returns MS_SUCCESS
or MS_FAILURE.
getShape( int i ) [shapeObj] Returns the shapefile feature at index i. More effecient than get.
TODO
shapeObj
Each feature of a layer’s data is a shapeObj. Each part of the shape is a closed lineObj.
+-------+ 1 1..* +------+
| Shape | --------> | Line |
+-------+ +------+
shapeObj Attributes
shapeObj Methods
new shapeObj( int type ) [shapeObj] Return a new shapeObj of the specified type. See the type attribute above. No
attribute values created by default. initValues should be explicitly called to create the required number of values.
add( lineObj line ) [int] Add line (i.e. a part) to the shape. Returns MS_SUCCESS or MS_FAILURE.
boundary() [shapeObj] Returns the boundary of the existing shape. Requires GEOS support. Returns NULL/undef
on failure.
buffer( int distance ) [shapeObj] Returns a new buffered shapeObj based on the supplied distance (given in the co-
ordinates of the existing shapeObj). Requires GEOS support. Returns NULL/undef on failure.
contains( pointObj point ) [int] Returns MS_TRUE if the point is inside the shape, MS_FALSE otherwise.
contains( shapeObj shape2 ) [int] Returns MS_TRUE if shape2 is entirely within the shape. Returns -1 on error and
MS_FALSE otherwise. Requires GEOS support.
convexHull() [shapeObj] Returns the convex hull of the existing shape. Requires GEOS support. Returns
NULL/undef on failure.
copy( shapeObj shape_copy ) [int] Copy the shape to shape_copy. Returns MS_SUCCESS or MS_FAILURE.
clone() [shapeObj] Return an independent copy of the shape.
crosses( shapeObj shape2 ) [int] Returns MS_TRUE if shape2 crosses the shape. Returns -1 on error and
MS_FALSE otherwise. Requires GEOS support.
difference( shapeObj shape ) [shapeObj] Returns the computed difference of the supplied and existing shape. Re-
quires GEOS support. Returns NULL/undef on failure.
disjoint( shapeObj shape2 ) [int] Returns MS_TRUE if shape2 and the shape are disjoint. Returns -1 on error and
MS_FALSE otherwise. Requires GEOS support.
distanceToPoint( pointObj point ) [float] Return distance to point.
distanceToShape( shapeObj shape ) [float] Return the minimum distance to shape.
draw( mapObj map, layerObj layer, imageObj img ) [int] Draws the individual shape using layer. Returns
MS_SUCCESS or MS_FAILURE.
equals( shapeObj shape2 ) [int] Returns MS_TRUE if the shape and shape2 are equal (geometry only). Returns -1
on error and MS_FALSE otherwise. Requires GEOS support.
fromWKT( char \*wkt ) [shapeObj] Returns a new shapeObj based on a well-known text representation of a geom-
etry. Requires GEOS support. Returns NULL/undef on failure.
get( int index ) [lineObj] Returns a reference to part at index. Reference is valid only during the life of the shapeObj.
getArea() [double] Returns the area of the shape (if applicable). Requires GEOS support.
getCentroid() [pointObj] Returns the centroid for the existing shape. Requires GEOS support. Returns NULL/undef
on failure.
getLength() [double] Returns the length (or perimeter) of a shape. Requires GEOS support.
getValue( int i ) [string] Return the shape attribute at index i.
initValues( int numvalues ) [void] Allocates memory for the requested number of values.
intersects( shapeObj shape ) [int] Returns MS_TRUE if the two shapes intersect, MS_FALSE otherwise. Note, does
not require GEOS support but will use GEOS functions if available.
intersection( shapeObj shape ) [shapeObj] Returns the computed intersection of the supplied and existing shape.
Requires GEOS support. Returns NULL/undef on failure.
overlaps( shapeObj shape2 ) [int] Returns MS_TRUE if shape2 overlaps shape. Returns -1 on error and MS_FALSE
otherwise. Requires GEOS support.
project( projectionObj proj_in, projectionObj proj_out ) [int] Reproject shape from proj_in to proj_out. Trans-
formation is done in place. Returns MS_SUCCESS or MS_FAILURE.
setBounds [void] Must be called to calculate new bounding box after new parts have been added.
TODO: should return int and set msSetError.
setValue( int i, string value ) [int] Set the shape value at index i to value.
symDifference( shapeObj shape ) [shapeObj] Returns the computed symmetric difference of the supplied and exist-
ing shape. Requires GEOS support. Returns NULL/undef on failure.
touches( shapeObj shape2 ) [int] Returns MS_TRUE if the shape and shape2 touch. Returns -1 on error and
MS_FALSE otherwise. Requires GEOS support.
toWKT() [string] Returns the well-known text representation of a shapeObj. Requires GEOS support. Returns
NULL/undef on failure.
Union( shapeObj shape ) [shapeObj] Returns the union of the existing and supplied shape. Shapes must be of the
same type. Requires GEOS support. Returns NULL/undef on failure.
within( shapeObj shape2 ) [int] Returns MS_TRUE if the shape is entirely within shape2. Returns -1 on error and
MS_FALSE otherwise. Requires GEOS support.
styleObj
An instance of styleObj can exist outside of a classObj container and be explicitly inserted into the classObj for use in
mapping.
new_style = new styleObj()
the_class.insertStyle(new_style)
It is important to understand that insertStyle inserts a copy of the styleObj instance, not a reference to the instance
itself.
The older use case
new_style = new styleObj(the_class)
remains supported. These will be the only ways to access the styles of a class. Programmers should no longer directly
access the styles attribute.
styleObj Attributes
angle [double] Angle, given in degrees, to draw the line work. Default is 0. For symbols of Type HATCH, this is the
angle of the hatched lines.
angleitem [string] Attribute/field that stores the angle to be used in rendering. Angle is given in degrees with 0
meaning no rotation.
antialias [int] MS_TRUE or MS_FALSE. Should TrueType fonts be antialiased.
backgroundcolor [colorObj] Background pen color.
color [colorObj] Foreground or fill pen color.
mincolor [colorObj] Attribute for Color Range Mapping (MS RFC 6: Color Range Mapping of Continuous Feature
Values). mincolor, minvalue, maxcolor, maxvalue define the range for mapping a continuous feature value to a
continuous range of colors when rendering the feature on the map.
minsize [int] Minimum pen or symbol width for scaling styles.
minvalue [double] Attribute for Color Range Mapping (MS RFC 6: Color Range Mapping of Continuous Feature
Values). mincolor, minvalue, maxcolor, maxvalue define the range for mapping a continuous feature value to a
continuous range of colors when rendering the feature on the map.
minwidth [int] Minimum width of the symbol.
maxcolor [colorObj] Attribute for Color Range Mapping (MS RFC 6: Color Range Mapping of Continuous Feature
Values). mincolor, minvalue, maxcolor, maxvalue define the range for mapping a continuous feature value to a
continuous range of colors when rendering the feature on the map.
maxsize [int] Maximum pen or symbol width for scaling.
maxvalue [double] Attribute for Color Range Mapping (MS RFC 6: Color Range Mapping of Continuous Feature
Values). mincolor, minvalue, maxcolor, maxvalue define the range for mapping a continuous feature value to a
continuous range of colors when rendering the feature on the map.
maxwidth [int] Maximum width of the symbol.
offsetx [int] Draw with pen or symbol offset from map data.
offsety [int] Draw with pen or symbol offset from map data.
outlinecolor [colorObj] Outline pen color.
rangeitem [string] Attribute/field that stores the values for the Color Range Mapping (MS RFC 6: Color Range
Mapping of Continuous Feature Values).
size [int] Pixel width of the style’s pen or symbol.
sizeitem [string] Attribute/field that stores the size to be used in rendering. Value is given in pixels.
symbol [int] The index within the map symbolset of the style’s symbol.
symbolname [string immutable] Name of the style’s symbol.
width [int] Width refers to the thickness of line work drawn, in pixels. Default is 1. For symbols of Type HATCH,
the with is how thick the hatched lines are.
styleObj Methods
new styleObj( [ classObj parent_class ] ) [styleObj] Returns new default style Obj instance. The parent_class is
optional.
clone [styleObj] Returns an independent copy of the style with no parent class.
setSymbolByName(mapObj map, string symbolname) [int] Setting the symbol of the styleObj given the reference
of the map object and the symbol name.
symbolObj
A styleObj will often refer to a symbolObj by name or index, but this is not really an object association, is it?
symbolObj Attributes
symbolObj Methods
new symbolObj( string symbolname [, string imagefile ] ) [symbolObj] Create new default symbol named name.
If imagefile is specified, then the symbol will be of type MS_SYMBOL_PIXMAP.
getImage() [imageObj] Returns a pixmap symbol’s imagery as an imageObj.
getPoints() [lineObj] Returns the symbol points as a lineObj.
setImage( imageObj image ) [int] Set a pixmap symbol’s imagery from image.
setPoints( lineObj line ) [int] Sets the symbol points from the points of line. Returns the updated number of points.
setStyle( int index, int value ) [int] Set the style at index to value. Returns MS_SUCCESS or MS_FAILURE.
symbolSetObj
symbolSetObj Attributes
symbolSetObj Methods
new symbolSetObj( [ string symbolfile ] ) [symbolSetObj] Create new instance. If symbolfile is specified, symbols
will be loaded from the file.
appendSymbol( symbolObj symbol ) [int] Add a copy of symbol to the symbolset and return its index.
getSymbol( int index ) [symbolObj] Returns a reference to the symbol at index.
getSymbolByName( string name ) [symbolObj] Returns a reference to the symbol named name.
index( string name ) [int] Return the index of the symbol named name or -1 in the case that no such symbol is found.
removeSymbol( int index ) [symbolObj] Remove the symbol at index and return a copy of the symbol.
save( string filename ) [int] Save symbol set to a file. Returns MS_SUCCESS or MS_FAILURE.
webObj
Has no other existence than as an attribute of a mapObj. Serves as a container for various run-time web application
definitions like temporary file paths, template paths, etc.
webObj Attributes
webObj Methods
None.
Contents
• PHP MapScript
– Introduction
– Versions Supported
– How to Get More Information on PHP MapScript
– Important Note
– Constants
– Functions
– Classes
* classObj
* colorObj
* errorObj
* gridObj
* hashTableObj
* imageObj
* labelcacheMemberObj
* labelcacheObj
* labelObj
* layerObj
* legendObj
* lineObj
* mapObj
* outputformatObj
* OwsrequestObj
* pointObj
* projectionObj
* querymapObj
* rectObj
* referenceMapObj
* resultObj
* scalebarObj
* shapefileObj
* shapeObj
* styleObj
* symbolObj
* webObj
* clusterObj
• Memory Management
6.3.1 Introduction
This is a PHP module that makes MapServer’s MapScript functionalities available in a PHP Dynamically Loadable
Library. In simple terms, this module will allow you to use the powerful PHP scripting language to dynamically create
and modify map images in MapServer.
PHP 5.2.0 or more recent is required; since MapServer 6.0, support for PHP 4, PHP 5.0 and PHP 5.1 have been
dropped. PHP MapScript was originally developed for PHP 3.0.14, and after MapServer 3.5 support for PHP 3 was
dropped.
The module has been tested and used on Linux, Solaris, *BSD, and Windows.
• For installation questions regarding the PHP MapScript module, see PHP MapScript Installation.
• The MapServer Wiki has information on this module, that was contributed by users.
• New PHP MapScript users should read the php_example document.
• The project’s home is the PHP/MapScript page on MapTools.org.
• Also, see the MapScript, and the Mapfile sections of this site.
• Refer to the main PHP site for their official documentation.
• Constant names and class member variable names are case-sensitive in PHP.
6.3.5 Constants
6.3.6 Functions
string ms_GetVersion() Returns the MapServer version and options in a string. This string can be parsed to find out
which modules were compiled in, etc.
int ms_GetVersionInt() Returns the MapServer version number (x.y.z) as an integer (x*10000 + y*100 + z). (New
in v5.0) e.g. V5.4.3 would return 50403.
array ms_TokenizeMap(string map_file_name) Preparses a mapfile through the MapServer parser and return an ar-
ray with one item for each token from the mapfile. Strings, logical expressions, regex expressions and comments
are returned as individual tokens.
void ms_ioinstallstdouttobuffer() Installs a mapserver IO handler directing future stdout output to a memory buffer.
void ms_ioinstallstdinfrombuffer() Installs a mapserver IO handler directing future stdin reading (ie. post request
capture) to come from a buffer.
void ms_iogetstdoutbufferstring() Fetch the current stdout buffer contents as a string. This method does not clear
the buffer.
int ms_iogetStdoutBufferBytes() Writes the current buffer to stdout. The PHP header() function should be used to
set the documents’s content-type prior to calling the function. Returns the number of bytes written if output is
sent to stdout. See MapScript Wrappers for WxS Services for more info.
void ms_ioresethandlers() Resets the default stdin and stdout handlers in place of “buffer” based handlers.
void ms_iostripstdoutbuffercontenttype() Strip the Content-type header off the stdout buffer if it has one, and if a
content type is found it is return. Otherwise return false.
6.3.7 Classes
classObj
Constructor
Class Objects can be returned by the layerObj class, or can be created using:
new classObj(layerObj layer [, classObj class])
The second argument class is optional. If given, the new class created will be a copy of this class.
Members
Type Name
string name
string title
int type
int status (MS_ON, MS_OFF or MS_DELETE)
double minscaledenom
double maxscaledenom
string template
labelObj label
int numstyles (read-only)
string keyimage
string group
hashTableObj metadata
Methods
int movestyledown(int index) The style specified by the style index will be moved down into the array of classes.
Returns MS_SUCCESS or MS_FAILURE. ex class->movestyledown(0) will have the effect of moving style 0
up to position 1, and the style at position 1 will be moved to position 0.
int deletestyle(int index) Delete the style specified by the style index. If there are any style that follow the deleted
style, their index will decrease by 1.
Note: if you are using the numstyles parameter while using the deletestyle function on the class object you need to
refetch a new class object.
Example :
//class has 2 styles
$class = $oLayer->getclass(0);
$class->deletestyle(1);
echo $class->numstyles; : will echo 2
$class = $oLayer->getclass(0);
echo $class->numstyles; : will echo 1
int getMetaData(string name) Fetch class metadata entry by name. Returns “” if no entry matches the name. Note
that the search is case sensitive.
Note: getMetaData’s query is case sensitive.
int setMetaData(string name, string value) Set a metadata entry for the class. Returns
MS_SUCCESS/MS_FAILURE.
int removeMetaData(string name) Remove a metadata entry for the class. Returns MS_SUCCESS/MS_FAILURE.
void free() Free the object properties and break the internal references. Note that you have to unset the php variable
to free totally the resources.
colorObj
Constructor
Members
Type Name
int red
int green
int blue
Methods
void setRGB(int red, int green, int blue) Set red, green, blue values.
errorObj
Instances of errorObj are created internally by MapServer as errors happen. Errors are managed as a chained list with
the first item being the most recent error. The head of the list can be fetched using ms_GetErrorObj(), and the list can
be cleared using ms_ResetErrorList()
Functions
Members
Type Name
int code //See error code constants above
string routine
string message
Method
errorObj next() Returns the next errorObj in the list, or NULL if we reached the end of the list.
Example: This example draws a map and reports all errors generated during the draw() call, errors can potentially
come from multiple layers.
ms_ResetErrorList();
$img = $map->draw();
$error = ms_GetErrorObj();
while($error && $error->code != MS_NOERR)
{
printf("Error in %s: %s<br>\n", $error->routine, $error->message);
$error = $error->next();
}
gridObj
Constructor
The grid is always embedded inside a layer object defined as a grid (layer->connectiontype = MS_GRATICULE) (for
more docs : http://trac.osgeo.org/mapserver/wiki/MapServerGrid)
A layer can become a grid layer by adding a grid object to it using : ms_newGridObj(layerObj layer)
$oLayer = ms_newlayerobj($oMap);
$oLayer->set("name", "GRID");
ms_newgridobj($oLayer);
$oLayer->grid->set("labelformat", "DDMMSS");
Members
Type Name
double minsubdivide
double maxsubdivide
double minarcs
double maxacrs
double mininterval
double maxinterval
string labelformat
Methods
hashTableObj
Constructor
Instance of hashTableObj is always embedded inside the classObj, layerObj, mapObj and webObj. It is uses a read
only.
$hashTable = $oLayer->metadata;
$key = null;
while ($key = $hashTable->nextkey($key))
echo "Key: ".$key." value: ".$hashTable->get($key)."<br/>";
Methods
string get(string key) Fetch class metadata entry by name. Returns “” if no entry matches the name. Note that the
search is case sensitive.
int set(string key, string value) Set a metadata entry in the hashTable. Returns MS_SUCCESS/MS_FAILURE.
int remove(string key) Remove a metadata entry in the hashTable. Returns MS_SUCCESS/MS_FAILURE.
void clear() Clear all items in the hashTable (To NULL).
string nextkey(string previousKey) Return the next key or first key if previousKey = NULL. Return NULL if no
item is in the hashTable or end of hashTable is reached
imageObj
Constructor
Members
Type Name
int width (read-only)
int height (read-only)
int resolution (read-only)
int resolutionfactor (read-only)
string imagepath
string imageurl
Methods
int saveImage([string filename, MapObj oMap]) Writes image object to specified filename. Passing no filename
or an empty filename sends output to stdout. In this case, the PHP header() function should be used to set the
document’s content-type prior to calling saveImage(). The output format is the one that is currently selected
in the map file. The second argument oMap is not manadatory. It is usful when saving to formats like GTIFF
that needs georeference informations contained in the map file. On success, it returns either MS_SUCCESS if
writing to an external file, or the number of bytes written if output is sent to stdout.
string saveWebImage() Writes image to temp directory. Returns image URL. The output format is the one that is
currently selected in the map file.
void pasteImage(imageObj srcImg, int transparentColorHex [[, int dstX, int dstY], int angle]) Copy srcImg on
top of the current imageObj. transparentColorHex is the color (in 0xrrggbb format) from srcImg that should
be considered transparent (i.e. those pixels won’t be copied). Pass -1 if you don’t want any transparent color.
If optional dstx,dsty are provided then it defines the position where the image should be copied (dstx,dsty =
top-left corner position). The optional angle is a value between 0 and 360 degrees to rotate the source image
counterclockwise. Note that if an angle is specified (even if its value is zero) then the dstx and dsty coordinates
specify the CENTER of the destination area. Note: this function works only with 8 bits GD images (PNG or
GIF).
labelcacheMemberObj
Members
Type Name
int classindex (Read-Only)
int featuresize (Read-Only)
int layerindex (Read-Only)
int numstyles (Read-Only)
int shapeindex (Read-Only)
int status (Read-Only)
int markerid (Read-Only)
string text (Read-Only)
int tileindex (Read-Only)
Method
None
labelcacheObj
Accessible only through the mapObj (map->labelcache). This object is only used to give the possiblity to free the label
cache (map->labelcache->freeCache())
Method
boolean freeCache() Free the label cache. Always returns MS_SUCCESS. Ex : (map->labelcache->freeCache();
labelObj
Constructor
Members
Type Name
string font
int type
colorObj color
colorObj outlinecolor
int outlinewidth
colorObj shadowcolor
int shadowsizex
int shadowsizey
colorObj backgroundcolor
colorObj backgroundshadowcolor
int backgroundshadowsizex
int backgroundshadowsizey
int size
int minsize
int maxsize
int position
int offsetx
int offsety
double angle
int autoangle
int autofollow
int buffer
int antialias
int wrap
int minfeaturesize
int autominfeaturesize
Continued on next page
Methods
This would bind the color parameter with the data (ie will extract the value of the color from the field called
“FIELD_NAME_COLOR”
string getBinding(const labelbinding) Get the attribute binding for a specified label property. Returns NULL if there
is no binding for this property.
Example:
$oLabel->setbinding(MS_LABEL_BINDING_COLOR, "FIELD_NAME_COLOR");
echo $oLabel->getbinding(MS_LABEL_BINDING_COLOR); // FIELD_NAME_COLOR
int removeBinding(const labelbinding) Remove the attribute binding for a specfiled style property.
Example:
$oStyle->removebinding(MS_LABEL_BINDING_COLOR);
void free() Free the object properties and break the internal references. Note that you have to unset the php variable
to free totally the resources.
layerObj
Constructor
Layer Objects can be returned by the mapObj class, or can be created using:
layerObj ms_newLayerObj(MapObj map [, layerObj layer])
A second optional argument can be given to ms_newLayerObj() to create the new layer as a copy of an existing layer.
If a layer is given as argument then all members of a this layer will be copied in the new layer created.
Members
Type Name
int numclasses (read-only)
int index (read-only)
int status (MS_ON, MS_OFF, MS_DEFAULT or MS_DELETE)
int debug
string classitem
string classgroup
string name
string group
string data
int type
int dump
double tolerance
int toleranceunits
int sizeunits
double symbolscaledenom
double minscaledenom
double maxscaledenom
double labelminscaledenom
double labelmaxscaledenom
int maxfeatures
int startindex
colorObj offsite
int annotate
int transform
int labelcache
int postlabelcache
string labelitem
string tileitem
string tileindex
string header
string footer
string connection
int connectiontype (read-only, use setConnectionType() to set it)
string filteritem
string template
int opacity
string styleitem
gridObj grid //only available on a layer defined as grid (MS_GRATICULE)
int num_processing
string requires
string labelrequires
hashTableObj metadata
hashTableObj bindvals
projectionObj projection
clusterObj cluster
Methods
int setWKTProjection(string proj_params) Same as setProjection(), but takes an OGC WKT projection definition
string as input.
Note: setWKTProjection requires GDAL support
int getNumResults() Returns the number of results from this layer in the last query.
resultObj getResult(int index) Returns a resultObj by index from a layer object with index in the range 0 to
numresults-1. Returns a valid object or FALSE(0) if index is invalid.
int open() Open the layer for use with getShape(). Returns MS_SUCCESS/MS_FAILURE.
int whichshapes(rectobj) Performs a spatial, and optionally an attribute based feature search. The function basically
prepares things so that candidate features can be accessed by query or drawing functions (eg using nextshape
function). Returns MS_SUCCESS or MS_FAILURE.
shapeobj nextShape() Called after msWhichShapes has been called to actually retrieve shapes within a given area.
Returns a shape object or NULL on error.
$map = ms_newmapobj("d:/msapps/gmap-ms40/htdocs/gmap75.map");
$layer = $map->getLayerByName(’road’);
$status = $layer->open();
$status = $layer->whichShapes($map->extent);
while ($shape = $layer->nextShape())
{
echo $shape->index ."<br>\n";
}
$layer->close();
array getProcessing() Returns an array containing the processing strings. If there are no processing strings, it returns
an empty array.
void clearProcessing() Clears all the processing strings.
string executeWFSGetfeature() Executes a GetFeature request on a WFS layer and returns the name of the tempo-
rary GML file created. Returns an empty string on error.
int applySLD(string sldxml, string namedlayer) Apply the SLD document to the layer object. The matching be-
tween the sld document and the layer will be done using the layer’s name. If a namedlayer argument is passed
(argument is optional), the NamedLayer in the sld that matchs it will be used to style the layer. See SLD HowTo
for more information on the SLD support.
int applySLDURL(string sldurl, string namedlayer) Apply the SLD document pointed by the URL to the layer ob-
ject. The matching between the sld document and the layer will be done using the layer’s name. If a namedlayer
argument is passed (argument is optional), the NamedLayer in the sld that matchs it will be used to style the
layer. See SLD HowTo for more information on the SLD support.
string generateSLD() Returns an SLD XML string based on all the classes found in the layers.
int moveclassup(int index) The class specified by the class index will be moved up into the array of layers. Re-
turns MS_SUCCESS or MS_FAILURE. ex layer->moveclassup(1) will have the effect of moving class 1 up to
position 0, and the class at position 0 will be moved to position 1.
int moveclassdown(int index) The class specified by the class index will be moved down into the array of layers.
Returns MS_SUCCESS or MS_FAILURE. ex layer->moveclassdown(0) will have the effect of moving class 0
up to position 1, and the class at position 1 will be moved to position 0.
classObj removeClass(int index) Removes the class indicated and returns a copy, or NULL in the case of a failure.
Note that subsequent classes will be renumbered by this operation. The numclasses field contains the number
of classes available.
boolean isVisible() Returns MS_TRUE/MS_FALSE depending on whether the layer is currently visible in the map
(i.e. turned on, in scale, etc.).
int setConnectionType(int connectiontype [,string plugin_library]) Changes the connectiontype of the layer and
recreates the vtable according to the new connection type. This method should be used instead of setting the
connectiontype parameter directly. In the case when the layer.connectiontype = MS_PLUGIN the plugin_library
parameter should also be specified so as to select the library to load by MapServer. For the other connection
types this parameter is not used.
shapeObj getShape(resultObj result]) If the resultObj passed has a valid resultindex, retrieve shapeObj from a
layer’s resultset. (You get it from the resultObj returned by getResult() for instance). Otherwise, it will do
a single query on the layer to fetch the shapeindex
$map = new mapObj("gmap75.map");
$l = $map->getLayerByName("popplace");
$l->queryByRect($map->extent);
for ($i=0; $i<$l->getNumResults();$i++){
$s = $l->getShape($l->getResult($i));
echo $s->getValue($l,"Name");
echo "\n";
}
array getGridIntersectionCoordinates() Returns an array containing the grid intersection coordinates. If there are
no coordinates, it returns an empty array.
void free() Free the object properties and break the internal references. Note that you have to unset the php variable
to free totally the resources.
legendObj
Constructor
Instances of legendObj are always are always embedded inside the mapObj.
Members
Type Name
int height
int width
int keysizex
int keysizey
int keyspacingx
int keyspacingy
colorObj outlinecolor //Color of outline of box, -1 for no outline
int status //MS_ON, MS_OFF, MS_EMBED
int position //for embeded legends, MS_UL, MS_UC, ...
int postlabelcache //MS_TRUE, MS_FALSE
labelObj label
colorObj imagecolor
string template
Methods
lineObj
Constructor
new lineObj()
Members
Type Name
int numpoints (read-only)
Methods
int add(pointObj point) Add a point to the end of line. Returns MS_SUCCESS/MS_FAILURE.
int addXY(double x, double y [, double m]) Add a point to the end of line. Returns MS_SUCCESS/MS_FAILURE.
Note: the 3rd parameter m is used for measured shape files only. It is not mandatory.
int addXYZ(double x, double y, double z [, double m]) Add a point to the end of line. Returns
MS_SUCCESS/MS_FAILURE.
Note: the 4th parameter m is used for measured shape files only. It is not mandatory.
PointObj point(int i) Returns a reference to point number i.
int project(projectionObj in, projectionObj out) Project the line from “in” projection (1st argument) to “out” pro-
jection (2nd argument). Returns MS_SUCCESS/MS_FAILURE.
mapObj
Constructor
Members
Type Name
int numlayers (read-only)
string name
string mappath
int status
int debug
int width (see setSize())
int height (see setSize())
int maxsize
outputformatObj outputformat
double resolution (pixels per inch, defaults to 72)
double defresolution (pixels per inch, defaults to 72)
rectObj extent;
double cellsize
int units (map units type)
double scaledenom (read-only, set by drawMap())
Continued on next page
Methods
int set(string property_name, new_value) Set map object property to new value.
int getsymbolbyname(string symbol_name) Returns the symbol index using the name.
symbol getsymbolobjectbyid(int symbolid) Returns the symbol object using a symbol id. Refer to the symbol object
reference section for more details.
void preparequery() Calculate the scale of the map and set map->scaledenom.
imageObj prepareImage() Return a blank image object.
imageObj draw() Render map and return an image object or NULL on error.
imageObj drawQuery() Render a query map and return an image object or NULL on error.
imageObj drawLegend() Render legend and return an image object.
imageObj drawReferenceMap() Render reference map and return an image object.
imageObj drawScaleBar() Render scale bar and return an image object.
int embedlegend(imageObj image) embeds a legend. Actually the legend is just added to the label cache so you
must invoke drawLabelCache() to actually do the rendering (unless postlabelcache is set in which case it is
drawn right away). Returns MS_SUCCESS or MS_FAILURE on error.
int embedScalebar(imageObj image) embeds a scalebar. Actually the scalebar is just added to the label cache so
you must invoke drawLabelCache() to actually do the rendering (unless postlabelcache is set in which case it is
drawn right away). Returns MS_SUCCESS or MS_FAILURE on error.
int drawLabelCache(imageObj image) Renders the labels for a map. Returns MS_SUCCESS or MS_FAILURE on
error.
labelcacheMemberObj getLabel(int index) Returns a labelcacheMemberObj from the map given an index value
(0=first label) Labelcache has to be enabled.
while ($oLabelCacheMember = $oMap->getLabel($i)) {
/* do something with the labelcachemember */
++$i;
}
layerObj getLayer(int index) Returns a layerObj from the map given an index value (0=first layer)
layerObj getLayerByName(string layer_name) Returns a layerObj from the map given a layer name. Returns
NULL if layer doesn’t exist.
colorObj getcolorbyindex(int iCloIndex) Returns a colorObj corresponding to the color index in the palette
void setExtent(double minx, double miny, double maxx, double maxy) Set the map extents using the georef ex-
tents passed in argument. Returns MS_SUCCESS or MS_FAILURE on error.
int setCenter(pointObj center) Set the map center to the given map point. Returns MS_SUCCESS or
MS_FAILURE.
int offsetExtent(double x, double y) Offset the map extent based on the given distances in map coordinates. Returns
MS_SUCCESS or MS_FAILURE.
int scaleExtent(double zoomfactor, double minscaledenom, double maxscaledenom) Scale the map extent using
the zoomfactor and ensure the extent within the minscaledenom and maxscaledenom domain. If minscale-
denom and/or maxscaledenom is 0 then the parameter is not taken into account. Returns MS_SUCCESS or
MS_FAILURE.
int setRotation(double rotation_angle) Set map rotation angle. The map view rectangle (specified in EXTENTS)
will be rotated by the indicated angle in the counter- clockwise direction. Note that this implies the rendered
map will be rotated by the angle in the clockwise direction. Returns MS_SUCCESS or MS_FAILURE.
int setSize(int width, int height) Set the map width and height. This method updates the internal geotransform and
other data structures required for map rotation so it should be used instead of setting the width and height
members directly. Returns MS_SUCCESS or MS_FAILURE.
int zoompoint(int nZoomFactor, pointObj oPixelPos, int nImageWidth, int nImageHeight, rectObj oGeorefExt)
Zoom to a given XY postion. Returns MS_SUCCESS or MS_FAILURE on error.
Parameters are :
• Zoom factor : positive values do zoom in, negative values zoom out. Factor of 1 will recenter.
• Pixel position (pointObj) : x, y coordinates of the click, with (0,0) at the top-left
• Width : width in pixel of the current image.
• Height : Height in pixel of the current image.
• Georef extent (rectObj) : current georef extents.
• MaxGeoref extent (rectObj) : (optional) maximum georef extents. If provided then it will be impos-
sible to zoom/pan outside of those extents.
int zoomrectangle(rectObj oPixelExt, int nImageWidth, int nImageHeight, rectObj oGeorefExt) Set the map
extents to a given extents. Returns MS_SUCCESS or MS_FAILURE on error.
Parameters are :
• oPixelExt (rect object) : Pixel Extents
• Width : width in pixel of the current image.
• Height : Height in pixel of the current image.
• Georef extent (rectObj) : current georef extents.
int zoomscale(double nScaleDenom, pointObj oPixelPos, int nImageWidth, int nImageHeight, rectObj oGeorefExt [, rectObj oM
Zoom in or out to a given XY position so that the map is displayed at specified scale. Returns MS_SUCCESS
or MS_FAILURE on error.
Parameters are :
• ScaleDenom : Scale denominator of the scale at which the map should be displayed.
• Pixel position (pointObj) : x, y coordinates of the click, with (0,0) at the top-left
• Width : width in pixel of the current image.
• Height : Height in pixel of the current image.
• Georef extent (rectObj) : current georef extents.
• MaxGeoref extent (rectObj) : (optional) maximum georef extents. If provided then it will be impos-
sible to zoom/pan outside of those extents.
int queryByPoint(pointObj point, int mode, double buffer) Query all selected layers in map at point location spec-
ified in georeferenced map coordinates (i.e. not pixels). The query is performed on all the shapes that are part of
a CLASS that contains a Templating value or that match any class in a layer that contains a LAYER TEMPLATE
value. Mode is MS_SINGLE or MS_MULTIPLE depending on number of results you want. Passing buffer -1
defaults to tolerances set in the map file (in pixels) but you can use a constant buffer (specified in ground units)
instead. Returns MS_SUCCESS if shapes were found or MS_FAILURE if nothing was found or if some other
error happened (note that the error message in case nothing was found can be avoided in PHP using the ‘@’
control operator).
int queryByRect(rectObj rect) Query all selected layers in map using a rectangle specified in georeferenced map
coordinates (i.e. not pixels). The query is performed on all the shapes that are part of a CLASS that con-
tains a Templating value or that match any class in a layer that contains a LAYER TEMPLATE value. Returns
MS_SUCCESS if shapes were found or MS_FAILURE if nothing was found or if some other error happened
(note that the error message in case nothing was found can be avoided in PHP using the ‘@’ control operator).
int queryByShape(shapeObj shape) Query all selected layers in map based on a single shape, the shape has to be
a polygon at this point. Returns MS_SUCCESS if shapes were found or MS_FAILURE if nothing was found
or if some other error happened (note that the error message in case nothing was found can be avoided in PHP
using the ‘@’ control operator).
int queryByFeatures(int slayer) Perform a query based on a previous set of results from a layer. At present the
results MUST be based on a polygon layer. Returns MS_SUCCESS if shapes were found or MS_FAILURE if
nothing was found or if some other error happened (note that the error message in case nothing was found can
be avoided in PHP using the ‘@’ control operator).
int queryByIndex(layerindex, tileindex, shapeindex[, addtoquery]) Add a specific shape on a given layer to the
query result. If addtoquery (which is a non mandatory argument) is set to MS_TRUE, the shape will be added
to the existing query list. Default behavior is to free the existing query list and add only the new shape.
int savequery(filename) Save the current query in a file. Returns MS_SUCESS or MS_FAILURE. Can be used with
loadquery
int loadquery(filename) Loads a query from a file. Returns MS_SUCESS or MS_FAILURE. To be used with save-
query.
void freequery(layerindex) Frees the query result on a specified layer. If the layerindex is -1, all queries on layers
will be freed.
int save(string filename) Save current map object state to a file. Returns -1 on error. Use absolute path. If a relative
path is used, then it will be relative to the mapfile location.
string getProjection() Returns a string representation of the projection. Returns NULL on error or if no projection is
set.
int setProjection(string proj_params, boolean bSetUnitsAndExtents) Set map projection and coordinate system.
Returns MS_SUCCESS or MS_FAILURE on error.
Parameters are given as a single string of comma-delimited PROJ.4 parameters. The argument : bSetUnit-
sAndExtents is used to automatically update the map units and extents based on the new projection. Possible
string processquerytemplate(array params, boolean generateimages) Process query template files and return the
result in a buffer. Second argument generateimages is not mandatory. If not given it will be set to TRUE.
See Also:
processtemplate
string processlegendtemplate(array params) Process legend template files and return the result in a buffer.
See Also:
processtemplate
int setSymbolSet(string fileName) Load and set a symbol file dynamically.
int getNumSymbols() Return the number of symbols in map.
int setFontSet(string fileName) Load and set a new FONTSET.
int selectOutputFormat(string type) Selects the output format to be used in the map. Returns
MS_SUCCESS/MS_FAILURE.
Note: the type used should correspond to one of the output formats declared in the map file. The type argument
passed is compared with the mimetype parameter in the output format structure and then to the name parameter in the
structure.
int saveMapContext(string filename) Available only if WMS support is enabled. Save current map object state
in WMS Map Context format. Only WMS layers are saved in the WMS Map Context XML file. Returns
MS_SUCCESS/MS_FAILURE.
int loadMapContext(string filename [, boolean unique_layer_name]) Available only if WMS support is enabled.
Load a WMS Map Context XML file into the current mapObj. If the map already contains some layers then
the layers defined in the WMS Map context document are added to the current map. The 2nd argument
unique_layer_name is optional and if set to MS_TRUE layers created will have a unique name (unique pre-
fix added to the name). If set to MS_FALSE the layer name will be the the same name as in the context. The
default value is MS_FALSE. Returns MS_SUCCESS/MS_FAILURE.
int applySLD(string sldxml) Apply the SLD document to the map file. The matching between the sld document and
the map file will be done using the layer’s name. See SLD HowTo for more information on the SLD support.
int applySLDURL(string sldurl) Apply the SLD document pointed by the URL to the map file. The matching
between the sld document and the map file will be done using the layer’s name. See SLD HowTo for more
information on the SLD support.
string generateSLD() Returns an SLD XML string based on all the classes found in all the layers.
string getconfigoption(string key) Returns the config value associated with the key. Returns an empty sting if key
not found.
int setconfigoption(string key, string value) Sets a config parameter using the key and the value passed
int applyconfigoptions() Applies the config options set in the map file. For example setting the PROJ_LIB using
the setconfigoption only modifies the value in the map object. applyconfigoptions will actually change the
PROJ_LIB value that will be used when dealing with projection.
int loadowsparameters(owsrequest request, string version) Load OWS request parameters (BBOX, LAYERS,
&c.) into map. Returns MS_SUCCESS or MS_FAILURE. 2nd argument version is not mandatory. If not
given, the version will be set to 1.1.1
int owsdispatch(owsrequest request) Processes and executes the passed OpenGIS Web Services request on the map.
Returns MS_DONE (2) if there is no valid OWS request in the req object, MS_SUCCESS (0) if an OWS
request was successfully processed and MS_FAILURE (1) if an OWS request was not successfully processed.
OWS requests include WMS, WFS, WCS and SOS requests supported by MapServer. Results of a dispatched
request are written to stdout and can be captured using the msIO services (ie. ms_ioinstallstdouttobuffer() and
ms_iogetstdoutbufferstring())
int insertLayer( layerObj layer [, int nIndex=-1 ] ) Insert a copy of layer into the Map at index nIndex. The default
value of nIndex is -1, which means the last possible index. Returns the index of the new Layer, or -1 in the case
of a failure.
layerObj removeLayer( int nIndex ) Remove a layer from the mapObj. The argument is the index of the layer to be
removed. Returns the removed layerObj on success, else null.
void free() Free the object properties and break the internal references. Note that you have to unset the php variable
to free totally the resources.
outputformatObj
Constructor
Instance of outputformatObj is always embedded inside the mapObj. It is uses a read only.
No constructor available (coming soon, see ticket 979)
Members
Type Name
string name
string mimetype
string driver
string extension
int renderer
int imagemode // MS_IMAGEMODE_* value.
int transparent
Methods
string getOption(string property_name) Returns the associated value for the format option property passed as ar-
gument. Returns an empty string if property not found.
int validate() Checks some internal consistency issues, Returns MS_SUCCESS or MS_FAILURE. Some problems
are fixed up internally. May produce debug output if issues encountered.
OwsrequestObj
Constructor
new OWSRequestObj()
Members
Type Name
int numparams (read-only)
int type (read-only): MS_GET_REQUEST or MS_POST_REQUEST
Methods
int loadparams() Initializes the OWSRequest object from the cgi environment variables REQUEST_METHOD,
QUERY_STRING and HTTP_COOKIE. Returns the number of name/value pairs collected.
int setparameter(string name, string value) Set a request parameter. For example :
$request->setparameter(’REQUEST’, ’GetMap’);
string getname(int index) Return the name of the parameter at index in the request’s array of parameter names.
string getvalue(int index) Return the value of the parameter at index in the request’s array of parameter values.
string getvaluebyname(string name) Return the value associated with the parameter name.
pointObj
Constructor
new pointObj()
Members
Type Name
double x
double y
double z (used for 3d shape files. set to 0 for other types)
double m (used only for measured shape files. set to 0 for other types.)
Methods
projectionObj
Constructor
Methods
querymapObj
Constructor
Instances of querymapObj are always are always embedded inside the mapObj.
Members
Type Name
int width
int height
int style (MS_NORMAL, MS_HILITE, MS_SELECTED)
colorObj color
Methods
int updateFromString(string snippet) Update a queryMap object from a string snippet. Returns
MS_SUCCESS/MS_FAILURE.
int set(string property_name, new_value) Set object property to a new value.
void free() Free the object properties and break the internal references. Note that you have to unset the php variable
to free totally the resources.
rectObj
Constructor
rectObj are sometimes embedded inside other objects. New ones can also be created with:
new rectObj()
Members:
Type Name
double minx
double miny
double maxx
double maxy
Methods
referenceMapObj
Constructor
Members
Type Name
string image
int width
int height
int status
int marker
string markername
int markersize
int maxboxsize
int minboxsize
rectObj extent
ColorObj color
ColorObj outlinecolor
Methods
int updateFromString(string snippet) Update a referenceMap object from a string snippet. Returns
MS_SUCCESS/MS_FAILURE.
int set(string property_name, new_value) Set object property to a new value.
void free() Free the object properties and break the internal references. Note that you have to unset the php variable
to free totally the resources.
resultObj
Constructor
Members
Type Name
int shapeindex (read-only)
int tileindex (read-only)
int classindex (read-only)
int resultindex (read-only)
Method
None
scalebarObj
Constructor
Instances of scalebarObj are always are always embedded inside the mapObj.
Members
Type Name
int height
int width
int style
int intervals
colorObj color
colorObj backgroundcolor
colorObj outlinecolor
int units
int status //MS_ON, MS_OFF, MS_EMBED
int position //for embeded scalebars, MS_UL, MS_UC, ...
int postlabelcache
labelObj label
colorObj imagecolor
int align
Methods
shapefileObj
Constructor
Opens a shapefile and returns a new object to deal with it. Filename should be passed with no extension.
To create a new file (or overwrite an existing one), type should be one of MS_SHP_POINT, MS_SHP_ARC,
MS_SHP_POLYGON or MS_SHP_MULTIPOINT. Pass type as -1 to open an existing file for read-only access, and
type=-2 to open an existing file for update (append).
Members
Type Name
int numshapes (read-only)
int type (read-only)
string source (read-only)
rectObj bounds (read-only)
Methods
shapeObj
Constructor
Members
Type Name
string text
int classindex
int type (read-only)
int numlines (read-only)
int index
int tileindex (read-only)
rectObj bounds (read-only)
int numvalues (read-only)
array values (read-only)
The values array is an associative array with the attribute values for this shape. It is set only on shapes obtained from
layer->getShape(). The key to the values in the array is the attribute name, e.g.
$population = $shape->values["Population"];
Methods
shapeobj difference(shapeobj shape) Returns a shape object representing the difference of the shape object with the
one passed as parameter. Only available if php/mapscript is built with GEOS library.
shapeobj symdifference(shapeobj shape) Returns the computed symmetric difference of the supplied and existing
shape. Only available if php/mapscript is built with GEOS library.
int overlaps(shapeobj shape) Returns true if the shape passed as argument overlaps the shape. Else returns false.
Only available if php/mapscript is built with GEOS library.
int within(shapeobj shape2) Returns true if the shape is entirely within the shape2 passed as argument. Else returns
false. Only available if php/mapscript is built with GEOS library.
int crosses(shapeobj shape) Returns true if the shape passed as argument crosses the shape. Else return false. Only
available if php/mapscript is built with GEOS library.
int touches(shapeobj shape) Returns true if the shape passed as argument touches the shape. Else return false. Only
available if php/mapscript is built with GEOS library.
int equals(shapeobj shape) Returns true if the shape passed as argument is equal to the shape (geometry only). Else
return false. Only available if php/mapscript is built with GEOS library.
int disjoint(shapeobj shape) Returns true if the shape passed as argument is disjoint to the shape. Else return false.
Only available if php/mapscript is built with GEOS library.
pointObj getCentroid() Returns a point object representing the centroid of the shape. Only available if php/mapscript
is built with GEOS library.
double getArea() Returns the area of the shape (if applicable). Only available if php/mapscript is built with GEOS
library.
double getLength() Returns the length (or perimeter) of the shape. Only available if php/mapscript is built with
GEOS library.
pointObj getLabelPoint() Returns a point object with coordinates suitable for labelling the shape.
string toWkt() Returns WKT representation of the shape’s geometry.
int setBounds() Updates the bounds property of the shape. Must be called to calculate new bounding box after new
parts have been added.
int simplify(double tolerance) Given a tolerance, returns a simplified shape object using underlying GEOS library
or NULL on error.
int topologySimplifyPreservingSimplify(double tolerance) Given a tolerance, returns a simplified shape object us-
ing underlying GEOS library or NULL on error.
void free() Free the object properties and break the internal references. Note that you have to unset the php variable
to free totally the resources.
styleObj
Constructor
The second argument ‘style’ is optional. If given, the new style created will be a copy of the style passed as argument.
Members
Type Name
int symbol
string symbolname
double size
double minsize
double maxsize
int offsetx
int offsety
int antialias
colorObj color
colorObj backgroundcolor
colorObj outlinecolor
double width
double minwidth
double maxwidth
double angle
double minvalue
double maxvalue
string rangeitem
int opacity (this parameter is only supported for the AGG driver)
Methods
This would bind the color parameter with the data (ie will extract the value of the color from the field called
“FIELD_NAME_COLOR”
string getBinding(const stylebinding) Get the attribute binding for a specfiled style property. Returns NULL if there
is no binding for this property.
$oStyle->setbinding(MS_STYLE_BINDING_COLOR, "FIELD_NAME_COLOR");
echo $oStyle->getbinding(MS_STYLE_BINDING_COLOR); // FIELD_NAME_COLOR
int removeBinding(const stylebinding) Remove the attribute binding for a specfiled style property. Added in
MapServer 5.0.
$oStyle->removebinding(MS_STYLE_BINDING_COLOR);
void free() Free the object properties and break the internal references. Note that you have to unset the php variable
to free totally the resources.
symbolObj
Constructor
Members
Type Name
string name
type name //Please refer to symbol type constants
int inmapfile If set to TRUE, the symbol will be saved inside the mapfile.
double sizex
double sizey
int numpoints (Read-Only)
int filled
int patternlength (Read-Only)
string imagepath (Read-Only))
int transparent
int transparentcolor
string character
int antialias
string font
int position
Methods
int setimagepath(char filename) Loads a pixmap symbol specified by the filename. The file should be of either Gif
or Png format.
Example of usage:
1. create a symbol to be used as a dash line
$nId = ms_newsymbolobj($gpoMap, "mydash");
$oSymbol = $gpoMap->getsymbolobjectbyid($nId);
$oSymbol->set("filled", MS_TRUE);
$oSymbol->set("sizex", 1);
$oSymbol->set("sizey", 1);
$oSymbol->set("inmapfile", MS_TRUE);
$aPoints[0] = 1;
$aPoints[1] = 1;
$oSymbol->setpoints($aPoints);
$aPattern[0] = 10;
$aPattern[1] = 5;
$aPattern[2] = 5;
$aPattern[3] = 10;
$oSymbol->setpattern($aPattern);
$style->set("symbolname", "mydash");
void free() Free the object properties and break the internal references. Note that you have to unset the php variable
to free totally the resources.
webObj
Constructor
Instances of webObj are always are always embedded inside the mapObj.
Members
Type Name
string log
string imagepath
string temppath
string template
string imageurl
string header
string footer
string empty (read-only)
string error (read-only)
string mintemplate
string maxtemplate
double minscaledenom
double maxscaledenom
rectObj extent (read-only)
string queryformat
string legendformat
string browseformat
hashTableObj metadata
Methods
int updateFromString(string snippet) Update a web object from a string snippet. Returns
MS_SUCCESS/MS_FAILURE.
int set(string property_name, new_value) Set object property to a new value.
void free() Free the object properties and break the internal references. Note that you have to unset the php variable
to free totally the resources.
clusterObj
Constructor
Members
Type Name
double maxdistance
double buffer
string region
Methods
Normally, you should not have to worry about the memory management because php has a garbage collector and will
free resources for you. If you write only small scripts that don’t do a lot of processing, it’s not worth to care about
that. Everything will be freed at the end of the script.
However, it may be useful to free resources during the execution if the script executes many tasks. To do so, you’ll
have to call the free() method of the mapscript objects and unset the php variables. The purpose of the free methods is
to break the circular references between an object and its properties to allow the zend engine to free the resources.
Here’s an example of a script that doesn’t free things during the execution:
$map = new mapObj("mapfile.map");
$of = $map->outputformat;
echo $map->extent->minx." - ".$map->extent->miny." - ".$map->extent->maxx." - ".$map->extent->maxy."\
echo "Outputformat name: $of->name\n";
unset($of);
unset($map); // Even if we unset the php variables, resources wont be freed
// Resources will be only freed at the end of the script
Contents
• Python MapScript Appendix
– Introduction
– Classes
– Exception Handling
6.5.1 Introduction
The Python MapScript module contains some class extension methods that have not yet been implemented for other
languages.
6.5.2 Classes
imageObj
The Python Imaging Library, http://www.pythonware.com/products/pil/, is an indispensible tool for image manipula-
tion. The extensions to imageObj are all geared towards better integration of PIL in MapScript applications.
imageObj Methods
imageObj( PyObject arg1, PyObject arg2 [, PyObject arg3 ] ) [imageObj] Create a new instance which is either
empty or read from a Python file-like object that refers to a GD format image.
The constructor has 2 different modes. In the blank image mode, arg1 and arg2 should be the desired width and
height in pixels, and the optional arg3 should be either an instance of outputFormatObj or a GD driver name as
a shortcut to a format. In the image file mode, arg1 should be a filename or a Python file or file-like object. If
the file-like object does not have a “seek” attribute (such as a urllib resource handle), then a GD driver name
must be provided as arg2.
Here’s an example of creating a 320 pixel wide by 240 pixel high JPEG using the constructor’s blank image
mode:
image = mapscript.imageObj(320, 240, ’GD/JPEG’)
In image file mode, interesting values of arg1 to try are instances of StringIO:
s = StringIO()
pil_image.save(s) # Save an image manipulated with PIL
ms_image = imageObj(s)
write( [ PyObject file ] ) [void] Write image data to a Python file-like object. Default is stdout.
pointObj
pointObj Methods
>>> p = mapscript.pointObj(1, 1)
>>> str(p)
{ ’x’: 1.000000 , ’y’: 1.000000 }
Note that the return value can be conveniently eval’d into a Python dictionary:
>>> p_dict = eval(str(p))
>>> p_dict[’x’]
1.000000
rectObj
rectObj Methods
__contains__( pointObj point ) [boolean] Returns True if point is inside the rectangle, otherwise returns False.
>>> r = mapscript.rectObj(0, 0, 1, 1)
>>> p = mapscript.pointObj(2, 0) # outside
>>> p in r
False
>>> p not in r
True
Note that the return value can be conveniently eval’d into a Python dictionary:
>>> r_dict = eval(str(r))
>>> r_dict[’minx’]
0.000000
The Python MapScript module maps a few MapServer errors into Python exceptions. Attempting to load a non-existent
mapfile raises an ‘IOError’, for example
>>> import mapscript
>>> mapfile = ’/no/such/file.map’
>>> m = mapscript.mapObj(mapfile)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.3/site-packages/mapscript.py", line 799, in __init__
newobj = _mapscript.new_mapObj(*args)
IOError: msLoadMap(): Unable to access file. (/no/such/file.map)
>>>
The message of the error is written by ‘msSetError’ and so is the same message that CGI mapserv users see in error
logs.
Table of Contents
• Python MapScript Image Generation
– Introduction
– Imagery Overview
– The imageObj Class
– Image Output
– Images and Symbols
6.6.1 Introduction
The MapScript HOWTO docs are intended to complement the API reference with examples of usage for specific
subjects. All examples in this document refer to the mapfile and testing layers distributed with MapServer 4.2+ and
found under mapserver/tests.
Pseudocode
All examples will use a pseudocode that is consistent with the language independent API reference. Each line is a
statement. For object attributes and methods we use the dot, ‘.’, operator. Creation and deletion of objects will be
indicated by ‘new’ and ‘del’ keywords. Other than that, the pseudocode looks a lot like Python.
The most common use of MapServer and MapScript is to create map imagery using the built-in GD format drivers:
GD/GIF, GD/PNG, GD/PNG24, and GD/JPEG. This imagery might be saved to a file on disk or be streamed directly
to another device.
Imagery is represented in MapScript by the imageObj class. Please see the API Reference (MapScript.txt) for class
attribute and method details.
The mapObj class has two methods that return instances of imageObj: ‘draw’, and ‘prepareImage’. The first returns a
full-fledged map image just as one would obtain from the mapserv CGI program
test_map = MapScript.mapObj(’tests/test.map’)
map_image = test_map.draw()
A properly sized and formatted blank image, without any layers, symbols, or labels, will be generated by ‘prepareIm-
age’
blank_image = test_map.prepareImage()
The imageObj class constructor creates new instances without need of a map
format = MapScript.outputFormatObj(’GD/JPEG’)
image = MapScript.imageObj(300, 200, format) # 300 wide, 200 high JPEG
Imagery is saved to disk by using the ‘save’ method. By accessing the ‘extension’ attribute of an image’s format, the
proper file extension can be used without making any assumptions
filename = ’test.’ + map_image.format.extension
map_image.save(filename)
If the image is using a GDAL/GTiff-based format, a GeoTIFF file can be created on disk by adding a mapObj as a
second optional argument to ‘save’
map_image.save(filename, test_map)
Direct Output
An image can be dumped to an open filehandle using the ‘write’ method. By default, the filehandle is ‘stdout’
# Send an image to a web browser
print "Content-type: " + map_image.format.mimetype + "\n\n"
map_image.write()
This method is not fully functional for all SWIG MapScript languages. See the API Reference (MapScript.txt) for
details. The ‘write’ method is new in 4.4.
The symbolObj::getImage() method will return an instance of imageObj for pixmap symbols
symbol = test_map.symbolset.getSymbolByName(’home-png’)
image = symbol.getImage()
There is a symmetric ‘setImage’ method which loads imagery into a symbol, allowing pixmap symbols to be created
dynamically
new_symbol = MapScript.symbolObj(’from_image’)
new_symbol.type = MapScript.MS_SYMBOL_PIXMAP
new_symbol.setImage(image)
index = test_map.symbolset.appendSymbol(new_symbol)
Contents
• Mapfile Manipulation
– Introduction
– Mapfile Overview
– The mapObj Class
– Children of mapObj
– Metadata
6.7.1 Introduction
The MapScript HowTo docs are intended to complement the API reference with examples of usage for specific sub-
jects. All examples in this document refer to the mapfile and testing layers distributed with MapServer 4.2+ and found
under mapserver/tests.
Pseudocode
All examples will use a pseudocode that is consistent with the language independent API reference. Each line is a
statement. For object attributes and methods we use the dot, ‘.’, operator. Creation and deletion of objects will be
indicated by ‘new’ and ‘del’ keywords. Other than that, the pseudocode looks a lot like Python.
By “Mapfile” here, I mean all the elements that can occur in (nearly) arbitrary numbers within a MapScript mapObj:
Layers, Classes, and Styles. MapServer 4.4 has greatly improved capability to manipulate these objects.
New instances
generates a default mapObj with no layers. A mapObj is initialized from a mapfile on disk in the usual manner:
test_map = new mapscript.mapObj(’tests/test.map’)
Cloning
An independent copy, less result and label caches, of a mapObj can be produced by the new mapObj.clone() method:
clone_map = test_map.clone()
Note: the Java MapScript module implements a “cloneMap” method to avoid conflict with the clone method of Java’s
Object class.
Saving
Frankly, the msSaveMap() function which is the foundation for mapObj::save is incomplete. Your mileage may vary.
There is a common parent/child object API for Layers, Classes, and Styles in MapServer 4.4.
Referencing a Child
References to Layer, Class, and Style children are obtained by “getChild”-like methods of their parent:
layer_i = test_map.getLayer(i)
class_ij = layer_i.getClass(j)
style_ijk = class_ij.getStyle(k)
These references are for convenience only. MapScript doesn’t have any reference counting, and you are certain to run
into trouble if you try to use these references after the parent mapObj has been deleted and freed from memory.
Cloning a Child
A completely independent Layer, Class, or Style can be created using the clone method of layerObj, classObj, and
styleObj:
clone_layer = layer_i.clone()
New Children
Uninitialized instances of layerObj, classObj, or styleObj can be created with the new constructors:
new_layer = new mapscript.layerObj
new_class = new mapscript.classObj
new_style = new mapscript.styleObj
and are added to a parent object using “insertChild”-like methods of the parent which returns the index at which the
child was inserted:
li = test_map.insertLayer(new_layer)
ci = test_map.getLayer(li).insertClass(new_class)
si = test_map.getLayer(li).getClass(ci).insertStyle(new_style)
The insert* methods create a completely new copy of the object and store it in the parent with all ownership taken on
by the parent.
see the API reference for more details.
Backwards Compatibility
The old style child object constructors with the parent object as a single argument:
new_layer = new mapscript.layerObj(test_map)
new_class = new mapscript.classObj(new_layer)
new_style = new mapscript.styleObj(new_class)
Removing Children
Child objects can be removed with “removeChild”-like methods of parents, which return independent copies of the
removed object:
# following from the insertion example ...
# remove the inserted style, returns a copy of the original new_style
removed_style = test_map.getLayer(li).getClass(ci).removeStyle(si)
removed_class = test_map.getLayer(li).removeClass(ci)
removed_layer = test_map.removeLayer(li)
6.7.5 Metadata
Map, Layer, and Class metadata are the other arbitrarily numbered elements (well, up to the built-in limit of 41) of a
mapfile.
New API
In MapServer 4.4, the metadata attributes of mapObj.web, layerObj, and classObj are instances of hashTableObj, a
class which functions like a limited dictionary
layer.metadata.set(’wms_name’, ’foo’)
name = layer.metadata.get(’wms_name’) # returns ’foo’
key = NULL
while (1):
key = layer.metadata.nextKey(key)
if key == NULL:
break
value = layer.metadata.get(key)
...
The old getMetaData and setMetaData methods of mapObj, layerObj, and classObj remain for use by older programs.
6.8 Querying
Contents
• Querying
– Introduction
– Querying Overview
– Attribute Queries
– Spatial Queries
6.8.1 Introduction
All examples in this document refer to the mapfile and testing layers distributed with MapServer 4.2+ and found under
mapserver/tests.
Pseudocode
All examples will use a pseudocode that is consistent with the language independent API reference. Each line is a
statement. For object attributes and methods we use the dot, ‘.’, operator. Creation and deletion of objects will be
indicated by ‘new’ and ‘del’ keywords. Other than that, the pseudocode looks a lot like Python.
Map layers can be queried to select features using spatial query methods or the attribute query method. Ignoring for
the moment whether we are executing a spatial or attribute query, results are obtained like so:
In the case of a failed query or query with zero results, ‘getResults’ returns NULL.
if results:
for i in range(results.numresults): # iterate over results
result = results.getResult(i)
This result object is a handle, of sorts, for a feature of the layer, having ‘shapeindex’ and ‘tileindex’ attributes that can
be used as arguments to ‘getFeature’.
Resulting Features
The previous example code can now be extended to the case of obtaining all queried features:
layer.query()
results = layer.getResults()
if results:
# open layer in preparation of reading shapes
layer.open()
for i in range(results.numresults):
result = results.getResult(i)
layer.getFeature(result.shapeindex, result.tileindex)
Backwards Compatibility
Scripts using the 4.2 API can continue to access query result members through layer methods:
for i in range(layer.getNumResults()):
result = layer.getResult(0)
but should adopt the new API for use in new work.
By Attributes
queryByAttributes()
By Rectangle
queryByRect()
By Point
queryByRect()
By Shape
queryByShape()
By Selection
queryByFeatures()
Contents
• MapScript Variables
– Version
– Logical Control - Boolean Values
– Logical Control - Status Values
– Map Units
– Layer Types
– Font Types
– Label Positions
– Label Size (Bitmap only)
– Shape Types
– Measured Shape Types
– Shapefile Types
– Query Types
– File Types
– Querymap Styles
– Connection Types
– DB Connection Types
– Join Types
– Line Join Types (for rendering)
– Image Types
– Image Modes
– Symbol Types
– Return Codes
– Limiters
– Error Return Codes
6.9.1 Version
6.9.23 Limiters
Data Input
261
MapServer Documentation, Release 6.0
Each type of data is made up of a data source and (one or more) layers. These two definitions apply to MapServer and
OGR.
Data Source - a group of layers stored in a common repository. This may be a file that handles several layers within
it, or a folder that has several files.
Layer - a sub-set of a data source often containing information in one type of vector format (point, line, polygon).
There are three types of data mapping and GIS data formats. Each type is handled differently. Below are the types and
some example formats:
• File-based- Shapefiles, Microstation Design Files (DGN), GeoTIFF images
• Directory-based - ESRI ArcInfo Coverages, US Census TIGER
• Database connections - PostGIS, ESRI ArcSDE, MySQL
File-based Data
File-based data consists of one or more files stored in any arbitrary folder. In many cases a single file is used (e.g.
DGN) but ESRI Shapefiles, for example, consist of at least 3 files each with a different filename extension: SHP, DBF,
SHX. In this case all 3 files are required because they each perform a different task internally.
Filenames usually serve as the data source name and contain layers that may or may not be obvious from the filename.
In Shapefiles, for example, there is one data source per shapefile and one layer which has the same name as that of the
file.
Directory-based Data
Directory-based data consists of one or more files stored in a particular way within a parent folder. In some cases
(e.g. Coverages) they may also require additional folders in other locations in the file tree in order to be accessed. The
directory itself may be the data source. Different files within the directory often represent the layers of data available.
For example, ESRI ArcInfo Coverages consist of more than one file with an ADF file extension, within a folder. The
PAL.ADF file represents the Polygon data. ARC.ADF holds the arc or line string data. The folder holds the data
source and each ADF file is a layer.
Database Connections
Database Connections are very similar to file and directory-based structures in one respect: they provide geographic
coordinate data for MapServer to interpret. That may be oversimplifying what is happening inside MapServer, but in
essence all you need is access to the coordinates making up the vector datasets.
Database connections provide a stream of coordinate data that is temporarily stored (e.g. in memory) and read by
MapServer to create the map. Other attribute or tabular data may also be required, but the focus of this guide is
coordinate data.
One important distinction between databases must be made. The databases discuss here are spatial databases, those
which can hold geographic data in its own data type. This is opposed to strictly tabular databases which cannot hold
geographic coordinates in the same way. It is possible to store some very simple coordinate data in regular tables, but
for anything but the most simple use a spatial database is required. There are spatial extensions to many databases
(open source and commercial). One of the most robust is the PostGIS extension to the PostgreSQL database. This
database not only allows the storage of geographic data, but also allows the manipulation of that data using SQL
commands. The other open source database with spatial capabilities is MySQL.
7.1.2 ArcInfo
ESRI ArcInfo Coverage Files are also known as simply as Coverages and less commonly as ADF files.
File listing
Coverages are made up of a set of files within a folder. The folder itself is the coverage name. The files roughly
represent different layers, usually representing different types of topology or feature types.
> ls /data/coverage/brazil
aat.adf arc.adf arx.adf bnd.adf lab.adf prj.adf tic.adf tol.adf
A folder with the name INFO is also part of the coverage. It sits at the same hierarchical level as the coverage folder
itself. Therefore, to copy a coverage (using regular file system tools) the coverage folder and the INFO folder must
both be copied. The INFO folder holds some catalogue information about the coverage.
> ls /data/coverage/info
arc0000.dat arc0001.dat arc0002.dat arc.dir
arc0000.nit arc0001.nit arc0002.nit
• CONNECTIONTYPE OGR must be used. The ability to use coverages is not built into MapServer.
• The path to the coverage folder name is required.
• The layer name (feature type) is specified in the DATA parameter
OGRINFO Examples
The directory is the data source. Layers are found within the directory. Using ogrinfo on a coverage directory:
> ogrinfo /data/coverage/brazil -summary
INFO: Open of ‘brazil’
using driver ‘AVCBin’ successful.
1: ARC (Line String)
2: CNT (Point)
3: LAB (Point)
4: PAL (Polygon)
7.1.3 ArcSDE
Spatial Database Engine (SDE) is one of ESRI‘s products which enables spatial data to be stored, managed, and
quickly retrieved from leading commercial database management systems like Oracle, Microsoft SQL Server, Sybase,
IBM DB2, and Informix.
• Linux, Windows, and Solaris (platforms that have SDE C API support)
• Install the SDE C API client libraries for your platform (preferably matched to the server version you are using,
ie 8.2 client -> 8.2 server, 8.3 client -> 8.3 server)
• Compile MapServer with SDE support MapServer Unix Compilation Howto for specific details)
• Define a LAYER block in a MapFile that uses SDE as the CONNECTIONTYPE
LAYER
NAME states
TYPE POLYGON
CONNECTION "sdemachine.iastate.edu,port:5151,sde,username,password"
CONNECTIONTYPE SDE
DATA "HOBU.STATES_LAYER,SHAPE,SDE.DEFAULT"
FILTER "where MYCOLUMN is not NULL"
PROCESSING "QUERYORDER=ATTRIBUTE" # <-- MapServer 4.10 and above
TEMPLATE ’/where/the/template/file/is/located’
CLASS
STYLE
SYMBOL ’circle’
SIZE 3
COLOR -1 -1 -1
OUTLINECOLOR 0 0 0
END
END
END
• sdemachine.iastate.edu - The name of the machine you are connecting to. In some instances, this may need
to be the IP address of the machine rather than the name if the server running MapServer is not configured to
• HOBU.STATES_LAYER - The layer name you are querying. This the full name of the table in which the layer
resides. If you are using Oracle or Microsoft SQL Server as the DB for SDE, the schema name must also be
supplied.
• SHAPE - The column that contains the geometry. SDE technically allows for storage of multiple geometry
types in the same layer, but in practice this isn’t desirable. Also, expect to have problems if there are invalid or
null geometries in the layer (or versions of the layer).
• SDE.DEFAULT - As of MapServer 4.2, you can query against a specific version of the layer. SDE sup-
ports multi-user editing with versions. If a layer has been Registered with the GeoDatabase and Registered
as Versioned (ArcGIS terms), MapServer can query against specified versions of those edits. If not specified,
SDE.DEFAULT will be used for all queries. Case Sensitive.
Note: The version parameter is located in a different spot than MapServer 4.2, which had it on the CONNECTION
string.
TEMPLATE
• /where/the/template/file/is/located - A template directive must be specified (can point to a dummy file) in order
for MapServer to be able to query attributes from SDE. If you are only going to be drawing layers, this directive
is unnecessary and will slow down the query operations of SDE (especially for layers with lots of attribute
columns).
PROCESSING
• PROCESSING “QUERYORDER=ATTRIBUTE” - Allows you to force SDE to use the WHERE clause that
was defined in your FILTER statement first, without attempting to hit the spatial index. Only in very special
cases will you want to do this.
• PROCESSING “OBJECTID=OBJECTID” - If you are having trouble with the SDE driver detecting your
unique ID column, you can override it with this processing parameter. Doing so will also have a slight perfor-
mance benefit because it will save a couple of extra queries to the database.
• PROCESSING “ATTRIBUTE_QUALIFIED=TRUE” - User can set this option to always use fully qualified
attribute names.
MapServer’s SDE driver, as of MapServer 5.0, allows you to join a single attribute table that has no geometries to
the layer that you are rendering. This feature allows you to use the data in the joined table much as you would in a
composite query that was made with something like PostGIS or Oracle Spatial. That is, the columns in the right table
of the join are available for CLASSITEM, LABELITEM and so on. The biggest constraint, however, is that fully
qualified names must be used or it most likely will not work. The join support is activated through PROCESSING
options.
• PROCESSING “JOINTABLE=SDE_MASTER.GEOSERVWRITE.JOINTABLE” - The JOINTABLE
processing option tells the driver which table you are joining the current layer to.
• CLASSITEM “SDE_MASTER.GEOSERVWRITE.JOINTABLE.VAL” - A CLASSITEM or LABELITEM
for a joined table using this mechanism must be fully qualified.
• FILTER “SDE_MASTER.GEOSERVWRITE.JOINTABLE.AQ_TAG=SDE_MASTER.GEOSERVWRITE.JOINTESTLA
- An important part of the join is defining how the join is to be made. Use a FILTER to do so.
7.1.4 DGN
File listing
Data are encapsulated in a single file, usually with the suffix .dgn.
0824t.dgn
OGRINFO Examples
Note: No geometry/feature type for the layer is identified because it can be multiple types.
DGN files are not really GIS data files. They evolved from drafting formats used by computer aided drafting/design
(CADD) programs.
They carry a few key attributes which are usually consistent across all DGN files. Most of the attributes relate to
graphical styling of features for map presentation, such as ColorIndex, Style, etc.
Spatial reference system information is not always encoded into DGN files. This can be a major problem when trying
to adequately reference the DGN data in another mapping program.
Measurement units can be a problem. In some cases the features could be located in kilometres or feet even though
it is not obvious from the output of ogrinfo. Sometimes the only way to identify or correct a problem with units is to
open the file in Microstation software.
Using ogrinfo to examine the structure of the file/layer:
> ogrinfo -summary /data/dgn/0824t.dgn elements
INFO: Open of ’0824t.dgn’
using driver ’DGN’ successful.
ESRI Personal Geodatabases are basically Microsoft Access files that contain spatial information. For more informa-
tion see the ESRI description page.
File listing
Similar to other database formats, the mdb file consists of several tables. The geometry is held in a BLOB table
column.
Personal geodatabase access is available through OGR. See the OGR driver page for specific driver information. The
driver is standard in any win32 build of GDAL/OGR version 1.3.2 or later. For Linux/Unix, MDBTools ODBC drivers
can be used for this (with some difficulty).
OGR uses the names of spatial tables within the personal geodatabase (tables with a Shape column) as layers.
The CONNECTION parameter must include the mdb extension, and the DATA parameter should be the name of the
spatial table (or OGR layer).
CONNECTIONTYPE ogr
CONNECTION "pgeodatabase.mdb"
DATA "layername"
OGRINFO Examples
First you should make sure that your GDAL/OGR build contains the personal geodatabase “PGeo” driver, by using
the ‘–formats’ command:
>ogrinfo --formats
Loaded OGR Format Drivers:
...
-> "ODBC" (read/write)
-> "PGeo" (readonly)
-> "PostgreSQL" (read/write)
...
If you don’t have the driver, you might want to try the FWTools or MS4W packages, which include the driver.
Once you have the PGeo driver you are ready to try an ogrinfo command on your database to get a list of spatial tables:
>ogrinfo test.mdb
INFO: Open of ‘test.mdb’
using driver ‘PGeo’ successful.
1: counties
Now use ogrinfo to get information on the structure of the spatial table:
>ogrinfo test.mdb counties -summary
INFO: Open of ‘test.mdb’
using driver ‘PGeo’ successful.
Note that you can also use an ODBC connection to access all of the tables in your geodatabase:
>ogrinfo PGeo:testDSN counties -summary
INFO: Open of ‘testDSN’
using driver ‘PGeo’ successful.
1: counties
2: counties_Shape_Index
...
Mapfile Example
LAYER
NAME my_geodatabase
TYPE POLYGON
CONNECTIONTYPE ogr
CONNECTION "test.mdb"
DATA "counties"
STATUS ON
CLASS
NAME "counties"
STYLE
COLOR 255 255 120
END
END
END
LAYER
NAME my_geodatabase
TYPE POLYGON
CONNECTIONTYPE ogr
CONNECTION "PGeo:testDSN"
DATA "counties"
STATUS ON
CLASS
NAME "counties"
STYLE
COLOR 255 255 120
END
END
END
Also known as ESRI ArcView Shapefiles or ESRI Shapefiles. ESRI is the company that introduced this format.
ArcView was the first product to use shapefiles.
File listing
Shapefiles are made up of a minimum of three similarly named files, with different suffixes:
Countries_area.dbf
Countries_area.shp
Countries_area.shx
Shapefile access is built directly into MapServer. It is also available through OGR, but direct access without OGR
is recommended and discussed here. The path to the shapefile is required. No file extension should be specified.
Shapefiles only hold one layer of data, therefore no distinction needs to be made.
OGRINFO Examples
7.1.7 GML
Also known as Geographic Markup Language and GML/XML. GML is a text-based, XML format that can represent
vector and attribute data. This is an Open Geospatial Consortium specification for data interchange. More information
is available at http://www.opengeospatial.org/standards/gml
File listing
GML files are usually a single text file with a GML filename extension. Some may use XML as the filename extension:
coal_dep.gml
XML schema documents often accompany GML files that have been translated from some other format (e.g. using
the ogr2ogr utility).
GML uses sets of nested tags to define attributes and geometry coordinates. Example of text in a GML file:
<gml:featureMember>
<Coal_Deposits fid="1">
<UNKNOWN>0.000</UNKNOWN>
<NA>0.000</NA>
<ID>2</ID>
<ID2>2</ID2>
<MARK>7</MARK>
<COALKEY>110</COALKEY>
<COALKEY2>110</COALKEY2>
<ogr:geometryProperty>
<gml:Point>
<gml:coordinates>78.531,50.694</gml:coordinates>
</gml:Point>
</ogr:geometryProperty>
</Coal_Deposits>
</gml:featureMember>
• GML access is available in MapServer through OGR. More information on OGR GML support is available at
http://www.gdal.org/ogr/drv_gml.html
• The CONNECTIONTYPE OGR parameter must be used.
• The path to the GML file is required, including file extension. There can be multiple layers in a GML file,
including multiple feature types.
OGRINFO Examples
COLOR 0 0 0
SYMBOL ’circle’
SIZE 6
END
END
END
GPX (the GPS Exchange Format) is a light-weight XML data format containing GPS data (waypoints, routes, and
tracks). For more information see the official GPX site.
File listing
All waypoints, routes, and tracks are stored in a single .gpx file.
• GPX access is available through OGR. See the OGR driver page for specific driver information.
• A relative path to the .gpx file can be used in the mapfile LAYER’s CONNECTION string.
• The feature type is specified in the DATA parameter
– the “tracks” feature type will usually be the track line
– the “track_points” feature type will usually be the points that make up the track line
OGRINFO Examples
First you should make sure that your GDAL/OGR build contains the “GPX” driver, by using the ‘–formats’ command:
>ogrinfo --formats
Loaded OGR Format Drivers:
...
-> "CSV" (read/write)
-> "GML" (read/write)
-> "GPX" (read/write)
-> "KML" (read/write)
...
If you don’t have the driver, you might want to try the FWTools or MS4W packages, which include the driver.
Once you have the GPX driver you are ready to try an ogrinfo command on your file to get a list of feature types:
>ogrinfo test.gpx
INFO: Open of ‘test.gpx’
using driver ‘GPX’ successful.
1: waypoints (Point)
2: routes (Line String)
3: tracks (Multi Line String)
4: route_points (Point)
5: track_points (Point)
Mapfile Example
Since you have confirmed that OGR can read your GPX file, now you can create a MapServer layer:
LAYER
NAME gpx
TYPE POINT
STATUS ON
CONNECTIONTYPE OGR
CONNECTION test.gpx
DATA "track_points"
CLASS
NAME "gpx"
STYLE
SYMBOL ’circle’
COLOR 0 119 255
SIZE 2
END
END
END # layer
7.1.9 Inline
Inline features refer to coordinates entered directly into the map file. They are not a file or database format and do not
require any DATA or CONNECTION parameters. Instead they use a FEATURE section to define the coordinates.
Inline features can be used to define points, lines and polygons as if taken from an external file. This requires direct
entry of coordinate pairs in the map file using a particular syntax.
This is a native MapServer option that doesn’t use any external libraries to support it.
Points
Lines
Lines are simply a list of points strung together, but the layer must be TYPE LINE instead of TYPE POINT.
LAYER
NAME inline_track
TYPE LINE
STATUS DEFAULT
MAXSCALE 10000000
FEATURE
POINTS
72.36 33.82
70.85 34.32
69.43 35.15
70.82 36.08
70.90 37.05
71.21 37.95
END
END
CLASS
STYLE
COLOR 255 10 0
SYMBOL ’circle’
SIZE 2
END
END
END
Polygons
Polygons are the same as the line example, just a list of points. They require the TYPE POLYGON parameter.
Polygons also require the final coordinate pair to be the same as the first, making it a closed polygon.
Table of Contents
• KML - Keyhole Markup Language
– Links to KML-Related Information
– Data Access / Connection Method
– Example 1: Displaying a .KML file
– Example 2: Displaying a .KMZ file
Keyhole Markup Language (KML) is an XML-based language for managing the display of 3D geospatial data. KML
is a standard maintained by the Open Geospatial Consoritum (OGC).
KML access in MapServer is available through OGR. See the OGR driver page for specific driver information. Read
support was initially added to GDAL/OGR version 1.5.0. A more complete KML reader was added to GDAL/OGR in
version 1.8.0, through the libKML driver (including the ability to read multigeometry, and KMZ files).
The CONNECTION parameter must include the kml or kmz extension, and the DATA parameter should be the name
of the layer.
CONNECTIONTYPE OGR
CONNECTION "filename.kml"
DATA "layername"
OGRINFO
First you should make sure that your GDAL/OGR build contains the “KML” driver, by using the ‘–formats’ command:
>ogrinfo --formats
Loaded OGR Format Drivers:
...
-> "GML" (read/write)
-> "GPX" (read/write)
-> "KML" (read/write)
...
If you don’t have the driver, you might want to try the FWTools or MS4W packages, which include the driver.
Once you have the KML driver you are ready to try an ogrinfo command on your file to get a list of available layers:
>ogrinfo myplaces.kml
INFO: Open of ‘myplaces.kml’
using driver ‘KML’ successful.
1: Layer #0 (Point)
Mapfile Example
LAYER
NAME "kml_example"
TYPE POINT
STATUS DEFAULT
CONNECTIONTYPE OGR
CONNECTION "kml/fountains-hotel.kml"
DATA "Layer #0"
LABELITEM "NAME"
CLASS
NAME "My Places"
STYLE
COLOR 250 0 0
OUTLINECOLOR 255 255 255
SYMBOL ’circle’
SIZE 6
END
LABEL
SIZE TINY
COLOR 0 0 0
OUTLINECOLOR 255 255 255
POSITION AUTO
END
END
END
OGRINFO
First you should make sure that your GDAL/OGR build contains the “LIBKML” driver, by using the ‘–formats’
command:
>ogrinfo --formats
Loaded OGR Format Drivers:
...
-> "GML" (read/write)
-> "GPX" (read/write)
-> "LIBKML" (read/write)
-> "KML" (read/write)
...
If you don’t have the driver, you might want to try the FWTools or MS4W packages, which include the driver. Or you
can follow the compiling notes for libKML and GDAL/OGR.
Once you have the LIBKML driver you are ready to try an ogrinfo command on your file to get a list of available
layers:
>ogrinfo Lunenburg_Municipality.kmz
INFO: Open of ‘Lunenburg_Municipality.kmz’
Mapfile Example
LAYER
NAME "lunenburg"
TYPE POLYGON
STATUS DEFAULT
CONNECTIONTYPE OGR
CONNECTION "Lunenburg_Municipality.kmz"
DATA "Lunenburg_Municipality"
CLASS
NAME "Lunenburg"
STYLE
COLOR 244 244 16
OUTLINECOLOR 199 199 199
END
END
END # layer
7.1.11 MapInfo
File listing
The following files are also associated with .TAB files: .DAT, .ID, .MAP. An example is:
border.DAT
border.ID
border.MAP
border.TAB
The term MID/MIF refers to files with .MID and .MIF extension.
OGRINFO Examples
LAYER
NAME Elevation_Poly_5
TYPE POLYGON
STATUS DEFAULT
CONNECTIONTYPE OGR
CONNECTION "./hypso/elev5_poly.TAB"
STYLEITEM "AUTO"
CLASS
NAME "Elevation Poly 5"
END
END # Layer
7.1.12 MSSQL
Contents
• MSSQL
– Introduction
– Creating spatial data tables in MSSQL 2008
– Connecting to Spatial Data in MSSQL 2008
* Create MapServer Layer
* Selecting the type of the geometry column
* The expected location on the plugin dll
* Using spatial indexes
* Layer Processing Options
– Obtaining binaries containing the MSSQL plugin dll
– More Information
Introduction
Microsoft SQL Server 2008+ supports storing spatial data by using the built in geometry/geography data types.
MapServer supports a driver to access these tables containing spatial columns, which is compiled as a plugin (msplu-
gin_mssql2008.dll).
There are several ways to create spatial data tables in MSSQL 2008. Having an existing data you can easily upload
that to an MSSQL table by using the ogr2ogr commandline tool and the OGR’s MSSQL Spatial driver
In order to connect to the MSSQL 2008 spatial database you should set up a valid connection string to the database
like the following examples:
Server=.\MSSQLSERVER2008;Database=Maps;Integrated Security=true
Server=55.55.55.55,1433;uid=a_user;pwd=a_password;database=a_database;Integrated Security=True
Server=55.55.55.55\SQLEXPRESS,1433;uid=a_user;pwd=a_password;database=a_database;Integrated Security=
Once the connection can be established to the server the layer can be configured to access MSSQL2008 as follows:
LAYER
NAME "rivers_mssql_spatial"
TYPE POLYGON
STATUS DEFAULT
CONNECTIONTYPE PLUGIN
PLUGIN "msplugin_mssql2008.dll"
CONNECTION "Server=.\MSSQLSERVER2008;Database=Maps;Integrated Security=true"
DATA "ogr_geometry from rivers USING UNIQUE ogr_fid USING SRID=4326"
...
END
The DATA parameter is used to perform the SQL select statement to access your table in MSSQL. The geometry
column is required in the select statement; in the above example the ogr_geometry column is the geometry column in
the rivers table. The table should also have an unique column (ogr_fid) which is provided for random access to the
features in the feature query operations.
The DATA section should also contain the spatial reference id (SRID) of the features in the data table The SRID is used
when specifying the search shapes during the intersect operations which should match with the SRID of the features
otherwise no features are returned in a particular query. if you omit specifying the SRID value in the DATA section
the diver will use SRID=0 when defining the search shapes.
For the geometry columns MSSQL supports 2 data types: “geometry” and “geography”. By default the driver con-
siders the type of the geometry column is “geometry”. In case if the type of the geometry column is “geography” we
must specify the data type in the DATA section explicitly, like:
DATA "ogr_geometry(geography) from rivers USING UNIQUE ogr_fid USING SRID=4326"
On Windows platforms the DLLs needed by the program are searched for in the following order:
1. The directory from which the application loaded.
2. The current directory.
3. The system directory. Use the GetSystemDirectory function to get the path of this directory.
4. The 16-bit system directory.
5. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
6. The directories that are listed in the PATH environment variable.
In order to speed up the access to the features a spatial index should be created to the geometry column which could
easily be done with the OGR MSSQL Spatial driver like:
ogrinfo -sql "create spatial index on rivers" "MSSQL:server=.\MSSQLSERVER2008;database=Maps;Integrate
In general we can safely rely on the query optimizer to select the most appropriate index in the sql query operations.
In some cases - however - we should force the optimizer to use the spatial index by specifying the index hint in the
DATA section like:
DATA "ogr_geometry from rivers using index ogr_geometry_sidx USING UNIQUE ogr_fid USING SRID=4326"
We can control the behaviour of the MSSQL driver by using the following PROCESSING options:
• CLOSE_CONNECTION=DEFER - This is where you can enable connection pooling for certain layer types.
Connection pooling will allow MapServer to share the handle to an open database or layer connection throughout
a single map draw process.
More Information
• OGR MSSQL Spatial driver page (describes the OGR MSSQL support)
• ogr2ogr application (describes the ogr2ogr commandline application)
• Vector Data (MapServer Vector Data Access Guide)
7.1.13 MySQL
Contents
• MySQL
– Introduction
– Connecting to Spatial Data in MySQL
* Requirements
* Verify MySQL Support in OGR Build
* Test Connection with ogrinfo
* Create MapServer Layer
– Connecting to non-Spatial Data in MySQL
* Requirements
* Create .ovf file
* Test Connection with ogrinfo
* Create MapServer Layer
– More Information
Introduction
The following methods connect to MySQL through OGR’s MySQL driver, thus avoiding the need to set up an ODBC
connection.
This section describes how to display a spatial MySQL table (meaning that the table has a column of type geometry)
in MapServer. OGR’s MySQL driver was expanded in OGR version 1.3.2 to support access to MySQL spatial tables.
Requirements
You can verify that your local build of OGR contains MySQL support by using the ogrinfo commandline utility, and
making sure that “MySQL” is returned:
ogrinfo --formats
Supported Formats:
-> "ESRI Shapefile" (read/write)
-> "MapInfo File" (read/write)
...
-> "PostgreSQL" (read/write)
-> "MySQL" (read/write)
...
which should return a list of all of your tables in the ‘test’ database:
INFO: Open of ‘MYSQL:test,user=root,password=mysql,port=3306’
using driver ‘MySQL’ successful.
1: province (Polygon)
LAYER
NAME "spain_provinces_mysql_spatial"
TYPE POLYGON
STATUS DEFAULT
CONNECTIONTYPE OGR
CONNECTION "MySQL:test,user=root,password=mysql,port=3306"
DATA "SELECT SHAPE,admin_name from province"
LABELITEM "admin_name"
CLASS
NAME "Spain Provinces"
STYLE
COLOR 240 240 240
OUTLINECOLOR 199 199 199
END
LABEL
COLOR 0 0 0
FONT sans
TYPE truetype
SIZE 8
POSITION AUTO
PARTIALS FALSE
OUTLINECOLOR 255 255 255
END
END
END # layer
The DATA parameter is used to perform the SQL select statement to access your table in MySQL. The geometry
column is required in the select statement; in the above example the SHAPE column is the geometry column in the
province table.
This section describes how to display a non-spatial MySQL table (meaning the table does not have a column of type
geometry) in MapServer.
Support for this functionality is found in GDAL/OGR 1.2.6 and older on Windows and GDAL/OGR 1.3.2 on Linux.
Requirements
# usr/local/bin/ogrinfo /maps/aqidata.ovf
ogrinfo returns
Don’t worry about the error, this is just telling you that it is a read-only driver. If it really bugs you, call ogrinfo with
the -ro (read only) flag.
To see the actual data
# usr/local/bin/ogrinfo /maps/aqidata.ovf -al
LAYER
NAME "MyAqi"
STATUS DEFAULT
TYPE POINT
CONNECTIONTYPE OGR
CONNECTION "aqidata.ovf"
DATA "aqidata"
CLASS
NAME "MyClass"
STYLE
SYMBOL ’circle’
SIZE 15
COLOR 0 255 0
END
END
END
DATA in the LAYER definition should be the same as the name attribute of the OGRVRTLayer element in the ovf file.
For this to draw, you need to have a SYMBOLSET defined in your mapfile and have a symbol called ‘circle’ in your
symbols.sym file.
More Information
7.1.14 NTF
NTF files are mostly used by the United Kingdom Ordnance Survey (OS). For more on the Ordnance Survey, see their
website at: http://www.ordnancesurvey.co.uk/oswebsite/
File listing
OGRINFO Examples
7.1.15 OGR
Table of Contents
• OGR
– Introduction
– What is OGR?
– Obtaining and Compiling MapServer with OGR Support
– Integrating OGR Support with MapServer Applications
– STYLEITEM “AUTO” - Rendering Layers Using Style Information from the OGR File
– Sample Sites Using OGR/MapServer
– FAQ / Common Problems
Introduction
Starting with version 3.5, MapServer included the ability to access vector data sets in formats other than Shapefile
in their native format using the OGR library. The following document describes the process for implementing OGR
support within MapServer applications.
Note: Experimental OGR support was included in MapServer version 3.4 but this initial implementation had some
limitations and is not covered in this document.
This document assumes that you are already familiar with certain aspects of MapServer:
• MapServer application development and especially setting up .map files.
• Some compilation skills if you don’t have ready access to a pre-compiled installation and need to compile your
own copy of MapServer with OGR support.
• access to OGR utilities, such as ogrinfo, which are available in the FWTools and MS4W packages.
Readers should also check out the Vector Data Access Guide, which has lots of examples of how to access specific
vector formats.
What is OGR?
The OGR Simple Features Library is a C++ open source library (and command-line tools) providing read (and some-
times write) access to a variety of vector file formats including ESRI Shapefiles, and MapInfo mid/mif and TAB
formats.
OGR is actually part of the GDAL library, so you will notice that some references point to GDAL (such as the mailing
list).
The OGR Simple Features Library allows MapServer users to display several types of vector data files in their native
formats. For example, MapInfo Mid/Mif and TAB data do not need to be converted to ESRI shapefiles when using
OGR support with MapServer.
See http://www.gdal.org/ogr/ogr_formats.html for the latest list of supported formats. At the date this document was
written, the following formats were supported:
• ArcInfo Binary Coverages
• ArcInfo E00 Coverages
• Atlas BNA
• Comma Separated Value (.csv)
• DODS/OPeNDAP
• ESRI ArcSDE
• ESRI Personal GeoDatabase
• ESRI Shapefiles
• FMEObjects Gateway
• Géoconcept Export
• GeoJSON
• GeoRSS
• GML
• GMT
• GRASS
• GPX
• Informix DataBlade
• INGRES
• INTERLIS
• KML
• MapInfo files
• Memory
• More information on the OGR Simple Features Project can be found at http://www.gdal.org/ogr/.
• The GDAL mailing list can be used for OGR related questions. Always search the list archives before sending
new questions.
• The GDAL Wiki has lots of good information for users and developers.
• The #gdal IRC channel on irc.freenode.net might also be of help. For info on IRC see the MapServer IRC page.
The main developer of the OGR library is Frank Warmerdam and the integration of OGR within MapServer was done
by Daniel Morissette.
The only change that is needed to integrate OGR support with a MapServer application is with the .map file.
The LAYER’s DATA parameter is expanded to three parameters (CONNECTIONTYPE OGR, CONNECTION and
DATA).
The syntax for this differs depending on the type of data being used (the Vector Data Access Guide is an excellent
resource for this). In OGR, a data source can be either a set of files that share a common basename (e.g. .shp/.shx/.dbf
for ArcView Shapefiles, or .tab/.map/.dat/.ind/.id for MapInfo TAB files) or a whole directory of files (e.g. TIGER).
Let’s call the former “File-based data sources” and the later “Directory-based data sources”. When accessing a file-
based data source you specify the filename of one of the files in the set (e.g. roads.shp or roads.tab) and when
accessing a directory-based data source you specify the directory name and OGR reads all the files in the directory
as a single data source with potentially several layers (e.g. TIGER files).
Some OGR drivers (e.g. SHP, TAB) can have dual behaviors, that is if they’re pointed to a single file then they behave
as a file-based data source and if they’re pointed to a directory then they will behave as a directory-based data source
and then every file in the directory becomes a new layer in the data source.
See the OGR formats page for more info on the specific file format you’re using. (Click on the format name for more
specific driver info on that format)
<datasource_name> is the name of the datasource to read from and is prefixed by the CONNECTION keyword. The
exact organization depends on the format driver in use. The format driver to use is automatically selected by OGR
based on the nature of the string passed as the datasource, and/or the format of the file referenced by it.
• For file based datasources this is the name of the file, including the extension, using an absolute path, or a relative
path. Relative paths are interpreted relative to the SHAPEPATH first, if not found then we try again relative to
the .map file location.
Note: Before version 4.1 the SHAPEPATH was ignored for OGR datasources.
• For directory based datasources, such as TIGER/Line, or Arc/Info Binary Coverages this is the name of the
directory containing the files. If the path is relative it is interpreted relative to the .map file.
• For virtual datasources such as database systems, and OGDI this is the service connection string
and is generally not related to the filesystem. For instance, for Oracle Spatial this might be
“OCI:warmerda/[email protected]”.
<layer_definition> is the name, number or SQL definition of the layer to use from the datasource. It is indicated via
the DATA keyword in the map file.
• Layer Name: The (case insenstive) layer name may be used to select a layer.
• Layer Number: The layer number (starting from 0 for the first layer) may be used to select a layer. Generally
the layer name is preferred to this since it is more self describing.
• Omitted: If no DATA keyword is provided, this is equivalent to selecting layer 0.
• SQL SELECT: If an SQL SELECT statement is used, it is interpreted in a driver specific manner to try and
generate a temporary pseudo-layer. For some formats this a restricted subset of SQL is interpreted within OGR.
For RDBMS based drivers (such as PostGIS and Oracle) this is passed through to the underlying database.
The OGRINFO utility can be used to find out the list of layers and their names in a data source.
Please see the Vector Data Access Guide for details and examples of each data format supported.
Example 1. MapInfo TAB file
LAYER
NAME "Builtup_Areas_tab"
TYPE POLYGON
CONNECTIONTYPE OGR
CONNECTION "data/tab/092b06_builtup_a.tab"
STATUS ON
CLASS
...
END
...
END
CONNECTIONTYPE OGR
CONNECTION "data/shppoly"
DATA "SELECT eas_id, idlink.Name FROM poly LEFT JOIN idlink ON poly.eas_id = idlink.eas_id"
STATUS ON
CLASSITEM "idlink.Name"
CLASS
...
END
END
OGRINFO is part of the GDAL/OGR distribution (it is also included in FWTools and MS4W). It is an executable that
can be used to obtain layer information about OGR supported files. The parameters are:
ogrinfo [-ro] [-q] datasource_name [layer [layer...]]
• -ro opens the file as read only (optional)
• -q executes in quiet mode, only the layer idex line will be returned (optional)
• datasource_name is the filename including extension (eg. roads.tab); for TIGER/Line files, data-
source_name is the directory containing the TIGER files (eg. ogrinfo TGR25001)
Example 5. To get the list of layers in a file:
$ ogrinfo popplace.tab
which shows that there is one point layer in the popplace.tab file.
Example 6. To get a dump of a specific layer, including field names, projection, etc:
$ ogrinfo popplace.tab popplace
OGRFeature(popplace):2
AREA (Real) = 0.000
PERIMETER (Real) = 0.000
POPPLACE_ (Real) = 2
POPPLACE_I (Real) = 1
NAME (String) = Hopedale
...
...
The above example shows that there are 14 layers in the TGR25001 directory.
Example 8. To get a summary of a specific TIGER layer, including only field names, projection, and extent
$ ogrinfo TGR25001 Landmarks -summary
OGR layers can be queried the same way as regular shapefiles in MapServer.
OGR layers can utilize tile indexes in a similar fashion to Shapefile based layers. The TILEINDEX keyword should
contain the connection string for the tile index file. The tile index file may be any supported OGR format, including
shapefiles.
The TILEITEM keyword in the LAYER definition indicates what attribute from the tile index file should be used as the
datasource location. If omitted, the default TILEITEM value is “location”. The value in the location field should be a
connection string the same as would have been used in the CONNECTION field for OGR layers. The CONNECTION
keyword is not needed (and will be ignored) for layers using the OGR connection type and having the TILEINDEX
keyword.
Tileindex files can be prepared in an external GIS, or using the OGR utility ogrtindex. Details can be found on the
OGR Utilities Page.
The following is a simple example of a point layer using a tile index.
LAYER
NAME "ogr_points"
TYPE POINT
CONNECTIONTYPE OGR
TILEINDEX "PIP_ogr_tiles.shp,0"
STATUS ON
CLASS
NAME "points"
STYLE
SYMBOL "default-circle"
COLOR 255 0 0
SIZE 6
END
END
END
OGR tileindex layers should support all normal query and attribute fetching mechanisms, including from MapScript;
however, this has not been heavily tested as of April/2002. Please report problems via the MapServer Trac. If auto
projection support is used for tileindexed OGR layers, the tileindex is read for the projection (not the component tiles).
Problems may (or may not) be encountered if the component tiles have differing schemas (different sets of attributes).
Connection Pooling
For some OGR supported formats, connecting to the dataset is quite expensive in terms of CPU use and amount of
disk IO. For instance, establishing access to an S-57 dataset results in a complete read into memory of the data files.
Connection pooling control aims at reducing this overhead in situations where the same file is used for several different
map layers.
To ensure that an OGR supported dataset is only opened once per map render (instead of separately for each map
LAYER referencing the dataset, use the CLOSE_CONNECTION PROCESSING option. The default value is for
CLOSE_CONNECTION is NORMAL, but if set to DEFER the dataset will be kept open till the map render is
complete. It will be reused by any other layers with using the same datasource.
Example 9. Preserve S-57 connection for two layers
In this example, we are using the same dataset (NO410810.000) for two layers. To avoid re-reading the dataset, we
mark the first layer to defer closing the connection till layer. In the second (or last) layer we request NORMAL
connection handling (though this could have been left out as normal handling is the default).
LAYER
NAME "AdminAreas"
TYPE POLYGON
CONNECTIONTYPE OGR
CONNECTION "NO410810.000"
DATA "ADMARE"
PROCESSING "CLOSE_CONNECTION=DEFER"
STATUS ON
...
END
LAYER
NAME "Land Areas"
TYPE POLYGON
CONNECTIONTYPE OGR
CONNECTION "NO410810.000"
DATA "LNDARE"
PROCESSING "CLOSE_CONNECTION=NORMAL"
STATUS ON
...
END
1. The text of the CONNECTION keyword must match exactly between layers for the connection to be reused.
2. Some dataset connections are quite memory expensive, and keeping them open may result in increased memory
use.
3. If all layers rendered for a particular connection defer closing the connection, it will remain open till MapServer
terminates. For normal cgi or MapScript use this is likely OK.
4. This use of CLOSE_CONNECTION handling is unique to OGR layers, and may be changed at some point in
the future as part of a broader implementation of connection pooling in MapServer.
STYLEITEM “AUTO” - Rendering Layers Using Style Information from the OGR File
Note: This feature is only supported with MapInfo TAB and Microstation DGN files at the moment, but eventually
other formats that carry colors and styles at the shape-level may also be supported through OGR.*
In MapServer, ArcView, and other shapefile-based applications, colors and styles are usually defined at the layer level.
This means that all the shapes in a given layer are usually rendered using the same color and styles.
On the other hand, some formats supported by OGR such as MapInfo TAB do have color and style information attached
to each shape. OGR adds support for the ‘STYLEITEM “AUTO”’ layer parameter which allows you to request that the
shapes in a layer be rendered using colors and styles coming from the data source instead of being driven by CLASSes
as was traditionally done with MapServer.
How to Implement
In order to have a layer rendered using colours and styles coming from the OGR data source, your must do the
following:
• Your layer definition must contain the STYLEITEM “AUTO” parameter.
• Your layer definition needs to contain at least one CLASS (which may be empty) and optionally a CLASSITEM
to match the expressions if your CLASS contains an expression. The empty CLASS in the layer will be updated
dynamically at runtime to contain colours and styles coming from the data source for each shape.
Examples
# This enables use of colors and styles from the source file.
STYLEITEM "AUTO"
# Define an empty class that will be filled at runtime from the color and
# styles read on each shape in the source file.
CLASS
END
END # layer
# This enables use of colors and styles from the source file.
STYLEITEM "AUTO"
# Define an empty class that will be filled at runtime from the color and
# styles read on each shape in the source file.
CLASSITEM "CATEGORY"
CLASS
EXPRESSION "1"
END
END
Please Note:
CLASS EXPRESSIONs are still working, so it is still possible to query and classify layers that are using STYLEITEM
“AUTO”. The only difference is that instead of using static class definitions, the colors and style will be read from the
data file.
Important Notes
NOTE 1 Even though MapInfo and other OGR data sources may support layers with mixed geometry
types (e.g. points, lines and polygons in the same file) this is not yet supported in MapServer. So
you still have to define a layer ‘TYPE’ and make sure that all the shapes in the OGR data source
are compatible with that layer type, otherwise MapServer may produce an error about incompatible
geometry types at runtime.
NOTE 2 Due to the dynamic nature of this feature, it is not compatible with the labelcache, so the label-
cache is automatically disabled for layers that make use of ‘STYLEITEM “AUTO”’.
NOTE 3 When you use STYLEITEM AUTO, MapServer tries to match symbol names returned by OGR
to names in your symbol file. For a quick solution, try using the following symbol file:
http://demo.mapserver.org/ogr-demos/yk_demo/etc/symbols_mapinfo.txt
The name of the symbols returned by OGR to MapServer depends on the file format. In the case of MapInfo files, it
will be:
• For “old-style” symbols (default MapInfo 3.0 symbols numbered 32 to 67) the symbol name will be ‘mapinfo-
sym-##’ where ‘##’ is the symbol number, e.g. ‘mapinfo-sym-32’.
• For “Font Symbols”, the symbol name is also ‘mapinfo-sym-##’ where ‘##’ is the symbol number in the font.
In this case, the name of the font itself is ignored by MapServer.
• MapInfo also supports “custom symbols” (bitmap symbols)... I’m not sure what you would get from OGR for
this, but I’m pretty sure that MapServer doesn’t do anything useful with them.
The OGRINFO utility can be used to find out exactly which symbol names OGR will return to MapServer. Look at
the “Style” string in the ogrinfo output for each shape that is read.
Here is the list of style parameters that are currently supported from OGR data sources and how they’re mapped in
MapServer:
Line color The line colour is mapped to CLASS.COLOR
Line thickness The line thickness is mapped to CLASS.STYLE.WIDTH. The default will be 1 pixel line (as it always
is with MapServer).
Polygon fill color Polygon fill color is mapped directly to CLASS.COLOR
Note that at this time, transparent polygons are not supported (they’re always opaque).
Polygon outline If a polygon has an outline color and thickness defined in the data source then the same rule as for
line color and thickness above will apply, except that the outline color is mapped to CLASS.OUTLINECOLOR
Point symbols Point symbol color is directly mapped to CLASS.COLOR Point symbol size is directly mapped to
CLASS.SIZE
If your symbolset contains a symbol called “default-marker” then this symbol will be used, otherwise the default
will be CLASS.SYMBOL=0 (i.e. a 1 pixel dot)
It is also possible (with a bit of work) to control which symbol gets used in rendering point symbols. OGR
provides MapServer with symbol names, and if the symbol name returned by OGR to MapServer matches the
name of one of the symbols in your symbolset then this symbol will be used.
For MapInfo point symbols (numbered 32 to 67 in the MapInfo MIF spec), the name returned by OGR is
“mapinfo-sym-X” where X should be replaced with the MapInfo symbol number (e.g. “mapinfo-sym-35” is the
star symbol).
Text labels The text string is mapped to CLASS.TEXT
Text color is mapped to CLASS.LABEL.COLOR
Text background color is mapped to CLASS.LABEL.BACKGROUNDCOLOR
OGR STYLEITEMAUTO label styles can be accessed through MapScript, such as PHP/MapScript’s getshape() or
getvalue() methods, by setting the LAYER’s PROCESSING parameter to “GETSHAPE_STYLE_ITEMS=all”. There-
fore, the LAYER may contain:
LAYER
...
PROCESSING "GETSHAPE_STYLE_ITEMS=all"
...
END
Q When using STYLEITEM AUTO, what should I have in my .sym symbols file?
A When you use STYLEITEM AUTO, MapServer tries to match symbol names returned by OGR to
names in your symbol file. For a quick solution, try using the following symbol file:
http://demo.mapserver.org/ogr-demos/yk_demo/etc/symbols_mapinfo.txt
The name of the symbols returned by OGR to MapServer depends on the file format. In the case of
MapInfo files, it will be:
• For “old-style” symbols (default MapInfo 3.0 symbols numbered 32 to 67) the symbol name
will be ‘mapinfo-sym-##’ where ‘##’ is the symbol number, e.g. ‘mapinfo-sym-32’.
• For “Font Symbols”, the symbol name is also ‘mapinfo-sym-##’ where ‘##’ is the symbol
number in the font. In this case, the name of the font itself is ignored by MapServer.
• MapInfo also supports “custom symbols” (bitmap symbols)... I’m not sure what you would get
from OGR for this, but I’m pretty sure that MapServer doesn’t do anything useful with them.
The OGRINFO utility can be used to find out exactly which symbol names OGR will return to
MapServer. Look at the “Style” string in the ogrinfo output for each shape that is read.
Table of Contents
• Oracle Spatial
– What MapServer 5.2 with Oracle Spatial
– Binaries
– Installation
– Two options for using Oracle Spatial with MapServer
– Mapfile syntax for native Oracle Spatial support
– Using subselects in the DATA statement
– Additional keywords - [FUNCTION]
– Additional keywords - [VERSION]
– More information
– Example of a LAYER
– Mapfile syntax for OGR Oracle Spatial support
Oracle Spatial is a spatial cartridge for the Oracle database. Remember that all Oracle databases come with Locator,
which has less features than Oracle Spatial. The differences between Locator and Spatial can be found in the Oracle
Spatial FAQ.
You can also see the original OracleSpatial wiki page that this document was based on.
• mode=map
• query modes: query, nquery, itemnquery
• MapScript query functions such as querybyattributes
• OGC:WMS: GetCapabilities, GetMap, GetFeatureInfo, DescribeLayer
• OGC:WFS, GetCapabilities, DescribeFeatureType, GetFeature
Binaries
MapServer Windows plugins with Oracle spatial support can be downloaded from MS4W. But you need Oracle client
software in the server on which you are running MapServer. Oracle client software can be obtained for development
purposes from the Oracle website, but you need to register, which by the way is free. The most recent version is
Oracle Database 10g Release 1 Client. The ORACLE TECHNOLOGY NETWORK DEVELOPMENT LICENSE
AGREEMENT applies to this software. The instant client will be satisfactory, and you can download the instant
client. Make sure though your MapServer is compiled against the same version as your Oracle client, for compiling
you need a full client install, not just the instant client.
Installation
See Oracle Installation for more configuration and installation information for MapServer’s native Oracle support
Note: If you receive error messages like “Error: .”. It’s likely related to MapServer being unable access or locate the
ORACLE_HOME.
The DATA statement for a LAYER of CONNECTIONTYPE oraclespatial can now have 4 options. This change is
backwards compatible, i.e. the old ways of specifying DATA still work. The new options are an extension to the
old DATA statements, as they needed to include identification of the primary key to be used for the query modes
(UNIQUE).
The following options are valid DATA statements:
"[geom_column]
FROM
[table]| [(
SELECT [...]
FROM [table]|[Spatial Operator]
[WHERE condition] )]
[USING [UNIQUE column]
| [SRID #srid]
| [FUNCTION]
| [VERSION #version]
]"
Example 1
The most simple DATA statement, in this case you only need to define one geometry column and one table. This
option assumes you do not have an SRID defined.
LAYER
...
CONNECTIONTYPE oraclespatial
DATA "MYGEOMETRY FROM MYTABLE"
...
END
Example 2
It’s composed of the first option plus the USING UNIQUE parameter. These new features are necessary when you
want to use any query function. When it is used you must pass a numeric column type. This option assumes you do
not have an SRID defined.
LAYER
...
CONNECTIONTYPE oraclespatial
DATA "MYGEOMETRY FROM MYTABLE USING UNIQUE MYTABLE_ID"
...
END
Example 3
This option is an extension to the first option. In this mode you must define the USING SRID parameter when the
SRID value in your data is different from NULL.
LAYER
...
CONNECTIONTYPE oraclespatial
DATA "MYGEOMETRY FROM MYTABLE USING SRID 90112"
...
END
Example 4
It is possible to define the source of the date as a subselect and not only as a table. As source of data, used in FROM
token, you can define any SQL, table, function, or operator that returns a SDO_GEOMETRY. For example:
DATA "[geom_column] FROM (SELECT [columns] FROM [table]|[Spatial function])"
If the LAYER definition contains a CLASSITEM, LABELITEM or FILTER, it is necessary that the fields used are
returned by the query. When you define CLASSITEM you can use an expression without any problems.
You can add three keywords to the DATA statement for [FUNCTION] option that influence the query which will be
executed in Oracle:
USING FILTER
Using this keyword triggers MapServer to use the Oracle Spatial SDO_FILTER operator. This operator executes only
the Oracle Spatial primary filter over your query data. In the Oracle User guide they explain: The primary filter
compares geometric approximations, it returns a superset of exact result. The primary filter therefore should be as
efficient (that is, selective yet fast) as possible. This operator uses the spatial index, so you need to define your spatial
index correctly to retrieve an exact result. If the result of the query is not exact you can try the next option.
USING RELATE
Using this keyword triggers MapServer to use the Oracle Spatial SDO_RELATE operator. This operator applies the
primary and secondary Oracle Spatial filters. It’s performance can be slightly slow but the result is extremely correct.
You can use this mode when you want a perfect result or when you can’t readjust the spatial index.
USING GEOMRELATE
Using this keyword triggers MapServer to use the geometry function SDO_GEOM.RELATE, a function that searches
the relations between geometries. SDO_GEOM.RELATE does not use the spatial index and your performance is more
slow than operators but it’s very accurate. You can use this mode when you can’t use the spatial index or when it
doesn’t exist.
USING NONE
Using this keyword triggers MapServer to don’t use any geometry function or spatial operator. So, the internal SQL
don’t retrict, bases in the extent, the data from source. All the data from source will be returned for MapServer. The
NONE token is very useful when the source of the data don’t contains any spatial index. It’s usually occur when the
source is a function like SDO_BUFFER, SDO_XOR, SDO_INTERSECTION...... So this mode is recomended when
you can’t use the spatial index or when it doesn’t exist.
You can define what version of database you are using to improve the internal sql. This is very useful when using
geodetic SRIDs and MapServer functions that retrieve the extent from data.
USING VERSION 8i
This indicates MapServer to use a internal SQL that it’s compatible with Oracle 8i version.
USING VERSION 9i
The second indicates MapServer to use 9i version, is recommended to use this parameter if you are using 9i version
because the internal SQL will use specific spatial functions that is need to retrieve data correctly from 9i Oracle Spatial
versions.
This indicates MapServer to use a internal SQL that it’s compatible with Oracle 10g version.
More information
• You can define any PROJECTION to your LAYER without problem, can be used for data with or without an
SRID in Oracle.
• The native support for Oracle Spatial supports the defaults definition for SDO_GEOMETRY in database, the
Oracle Spatial SDO package.
• Information about the primary and secondary Oracle Spatial filters can be found in the Oracle Spatial User Guide
(the “Query Model” section). Information about the SDO_FILTER and SDO_RELATE operators can be found
in the “Spatial Operators” section, and information about the SDO_GEOM.RELATE function can be found in
the “Geometry Function” section of the Oracle Spatial User Guide.
Example of a LAYER
LAYER
NAME kwadranten
TYPE POLYGON
CONNECTIONTYPE oraclespatial
CONNECTION "user/pwd"
DATA "GEOMETRIE FROM KWADRANTEN USING SRID 90112"
DUMP TRUE
CLASS
STYLE
OUTLINECOLOR 0 0 0
COLOR 0 128 128
END
END
END
You can specify the SID for your database, the SID alias needs to be supplied in the tnsnames.ora file of the Oracle
client, e.g.
Example for tnsnames.ora:
MYDB =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = server_ip)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = DB1)
)
)
Note: Make sure you set the wms_extent METADATA for the LAYER, as otherwise the “Getcapabilities” request
takes a lot of time.
7.1.17 PostGIS/PostgreSQL
Table of Contents
• PostGIS/PostgreSQL
– PostGIS/PostgreSQL
– Data Access /Connection Method
– OGRINFO Examples
– Mapfile Example
– Support for SQL/MM Curves
* Example#1: CircularString in MapServer
* Example#2: CompoundCurve in MapServer
* Example#3: CurvePolygon in MapServer
* Example#4: MultiCurve in MapServer
* Example#5: MultiSurface in MapServer
* Using MapServer < 6.0
PostGIS/PostgreSQL
PostGIS is supported directly by MapServer and must be compiled into MapServer to work.
The PostgreSQL client libraries (libpq.so or libpq.dll) must be present in the system’s path environment for function-
ality to be present.
The CONNECTIONTYPE parameter must be set to POSTGIS.
The CONNECTION parameter is used to specify the parameters to connect to the database. CONNECTION param-
eters can be in any order. Most are optional. dbname is required. user is required. host defaults to localhost, port
defaults to 5432 (the standard port for PostgreSQL).
The DATA parameter is used to specify the data used to draw the map. The form of DATA is “[geometry_column]
from [table_name|sql_subquery] using unique [unique_key] using srid=[spatial_reference_id]”. The “using unique”
and “using srid=” clauses are optional, but using them improves performance.
Here is a simple generic example:
CONNECTIONTYPE POSTGIS
CONNECTION "host=yourhostname dbname=yourdatabasename user=yourdbusername password=yourdbpassword por
DATA "geometrycolumn from yourtablename"
This example shows specifying the unique key and srid in the DATA line:
CONNECTIONTYPE POSTGIS
CONNECTION "dbname=yourdatabasename user=yourdbusername"
DATA "the_geom from the_database using unique gid using srid=4326"
This example shows using a SQL subquery to perform a join inside the database and map the result in MapServer.
Note the “as subquery” string in the statement – everything between “from” and “using” is sent to the database for
evaluation:
CONNECTIONTYPE POSTGIS
CONNECTION "dbname=yourdatabasename user=yourdbusername"
DATA "the_geom from (select g.gid, g.the_geom, a.attr1, a.attr2 from geotable g join attrtable a on g
This example shows using a geometry function and database sort to limit the number of features and vertices returned
to MapServer:
CONNECTIONTYPE POSTGIS
CONNECTION "dbname=yourdatabasename user=yourdbusername"
DATA "the_geom from (select g.gid, ST_Simplify(g.the_geom, 10.0) as the_geom from geotable g order by
This example shows the use of the !BOX! substitution string to over-ride the default inclusion of the map bounding
box in the SQL. By default the spatial box clause is appended to the SQL in the DATA clause, but you can use !BOX!
to insert it anywhere you like in the statement. In general, you won’t need to use !BOX!, because the PostgreSQL
planner will generate the optimal plan from the generated SQL, but in some cases (complex sub-queries) a better plan
can be generated by placing the !BOX! closer to the middle of the query:
CONNECTIONTYPE POSTGIS
CONNECTION "dbname=yourdatabasename user=yourdbusername"
DATA "the_geom from (select g.gid, ST_Union(g.the_geom, 10.0) as the_geom from geotable g where ST_In
OGRINFO Examples
OGRINFO can be used to read out metadata about PostGIS tables directly from the database.
First you should make sure that your GDAL/OGR build contains the PostgreSQL driver, by using the ‘–formats’
command:
>ogrinfo --formats
Loaded OGR Format Drivers:
...
-> "PGeo" (readonly)
-> "PostgreSQL" (read/write)
-> "MySQL" (read/write)
...
If you don’t have the driver, you might want to try the FWTools or MS4W packages, which include the driver.
Once you have the driver you are ready to try an ogrinfo command on your database to get a list of spatial tables:
>ogrinfo PG:"host=127.0.0.1 user=postgres password=postgres dbname=canada port=5432"
using driver ‘PostgreSQL’ successful.
1: province (Multi Polygon)
Now use ogrinfo to get information on the structure of the spatial table:
Mapfile Example
LAYER
NAME "province"
STATUS ON
TYPE POLYGON
CONNECTIONTYPE POSTGIS
CONNECTION "host=127.0.0.1 port=5432 dbname=canada user=postgres password=postgres"
DATA "the_geom from province"
CLASS
...
END
END
For more info about PostGIS and MapServer see the PostGIS docs: http://postgis.org/documentation/
PostGIS is able to store circular interpolated curves, as part of the SQL Multimedia Applications Spatial specification
(read about the SQL/MM specification). For more information about PostGIS’ support, see the SQL-MM Part 3 section
in the PostGIS documentation, such as here.
As of MapServer 6.0, the PostGIS features CircularString, CompoundCurve, CurvePolygon, MultiCurve, and Multi-
Surface can be drawn through MapServer directly.
The following is the Well Known Text of the feature loading into PostGIS:
INSERT INTO test ( g, id ) VALUES ( ST_GeomFromText(’CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0)’, -1), 2
TYPE POLYGON
CONNECTIONTYPE postgis
CONNECTION "user=postgres password=postgres dbname=curves host=localhost port=5432"
DATA "g from test using SRID=-1 using unique id"
CLASS
STYLE
COLOR 128 128 128
ANTIALIAS true
END
END
END
The following is the Well Known Text of the feature loading into PostGIS:
INSERT INTO test ( g, id ) VALUES ( ST_GeomFromText(’COMPOUNDCURVE(CIRCULARSTRING(0 0, 1 1, 1 0),(1 0
The following is the Well Known Text of the feature loading into PostGIS:
INSERT INTO test ( g, id ) VALUES ( ST_GeomFromText(’CURVEPOLYGON(CIRCULARSTRING(0 0, 4 0, 4 4, 0 4,
The following is the Well Known Text of the feature loading into PostGIS:
INSERT INTO test ( g, id ) VALUES ( ST_GeomFromText(’MULTICURVE((0 0, 5 5),CIRCULARSTRING(4 0, 4 4, 8
TYPE POLYGON
CONNECTIONTYPE postgis
CONNECTION "user=postgres password=postgres dbname=curves host=localhost port=5432"
DATA "g from test using SRID=-1 using unique id"
CLASS
STYLE
COLOR 128 128 128
ANTIALIAS true
END
END
END
The following is the Well Known Text of the feature loading into PostGIS:
INSERT INTO test ( g, id ) VALUES ( ST_GeomFromText(’MULTISURFACE(CURVEPOLYGON(CIRCULARSTRING(0 0, 4
END
END
If you cannot upgrade to MapServer 6.0, then you can use the PostGIS function ST_CurveToLine() in your MapServer
LAYER to draw the curves (note that this is much slower however):
LAYER
NAME "curves_poly"
STATUS DEFAULT
TYPE POLYGON
CONNECTIONTYPE postgis
CONNECTION "user=postgres password=postgres dbname=curves host=localhost port=5432"
DATA "wkb_geometry from (select c.id, ST_CurveToLine(c.g) as wkb_geometry from c) as subquery using
CLASS
STYLE
COLOR 128 128 128
ANTIALIAS true
END
END
END
7.1.18 SDTS
This is a United States Geological Survey (USGS) format. SDTS has a raster and a vector format. The raster format
is not supported in MapServer. Only the vector formats are supported, including VTP and DLG files.
File listing
• SDTS files are often organized into state-sized pieces. For example, all of the state of Maryland (MD), U.S.A.
• Files are also available for multiple types of features including hydrography, transportation and administrative
boundaries.
This example uses transportation data, which consists of 35 separate files, each with the suffix DDF:
MDTRAHDR.DDF MDTRARRF.DDF MDTRCATS.DDF
MDTRDQCG.DDF MDTRFF01.DDF MDTRLE02.DDF
MDTRNA03.DDF MDTRNO03.DDF MDTRSPDM.DDF
MDTRAMTF.DDF MDTRBFPS.DDF MDTRCATX.DDF
MDTRDQHL.DDF MDTRIDEN.DDF MDTRLE03.DDF
MDTRNE03.DDF MDTRPC01.DDF MDTRSTAT.DDF
MDTRARDF.DDF MDTRBMTA.DDF MDTRDDSH.DDF
MDTRDQLC.DDF MDTRIREF.DDF MDTRNA01.DDF
MDTRNO01.DDF MDTRPC02.DDF MDTRXREF.DDF
MDTRARDM.DDF MDTRCATD.DDF MDTRDQAA.DDF
MDTRDQPA.DDF MDTRLE01.DDF MDTRNA02.DDF
MDTRNO02.DDF MDTRPC03.DDF
OGRINFO Examples
Using ogrinfo on a catalog file (note that the first 7 layers do not have geometries):
> ogrinfo /data/sdts/MD/MDTRCATD.DDF
Had to open data source read-only.
INFO: Open of ‘MDTRCATD.DDF’
using driver ‘SDTS’ successful.
1: ARDF (None)
2: ARRF (None)
3: AMTF (None)
4: ARDM (None)
5: BFPS (None)
6: BMTA (None)
7: AHDR (None)
8: NE03 (Point)
9: NA01 (Point)
10: NA02 (Point)
11: NA03 (Point)
12: NO01 (Point)
13: NO02 (Point)
14: NO03 (Point)
15: LE01 (Line String)
16: LE02 (Line String)
17: LE03 (Line String)
18: PC01 (Polygon)
19: PC02 (Polygon)
20: PC03 (Polygon)
CONNECTIONTYPE OGR
CONNECTION "data/sdts/MD/MDTRCATD.DDF"
DATA "LE01"
STATUS DEFAULT
CLASS
STYLE
COLOR 0 0 0
END
END
END
7.1.19 S57
Also known as S57. The IHO S-57 format is a vector interchange format used for maritime charts. It was developed by
the International Hydrographic Organisation (IHO). For more information about the IHO see: http://www.iho.shom.fr/
File listing
• S57 access in MapServer occurs through OGR, CONNECTIONTYPE OGR must be used.
• Specify a full path or a relative path from the SHAPEPATH to the .000 file for the CONNECTION
• Use the DATA parameter to specify the s57 layer name
Special Notes
The underlying OGR code requires two files from your GDAL/OGR installation when reading S57 data in
MapServer : s57objectclasses.csv and s57attributes.csv. These files can be found in the /GDAL/data/ folder (unix:
/usr/local/share/gdal windows: /ms4w/gdaldata). If you receive an error in MapServer such as:
msDrawMap(): Image handling error. Failed to draw layer named ’s57’.
msOGRFileOpen(): OGR error. xxx failed for OGR connection
you may have to point MapServer to these files using the CONFIG parameter in the main section of your map file:
CONFIG GDAL_DATA "C:\ms4w\gdaldata"
OGRINFO Examples
TIGER/Line files are created by the US Census Bureau and cover the entire US. They are often referred simply as
TIGER files. For more information see: http://www.census.gov/geo/www/tiger/.
File listing
TIGER/Line files are text files and directory-based data sources. For example, one county folder TGR06059 contains
several associated files:
TGR06059.RT1 TGR06059.RT2 TGR06059.RT4 TGR06059.RT5
TGR06059.RT6 TGR06059.RT7 TGR06059.RT8 TGR06059.RTA
TGR06059.RTC TGR06059.RTH TGR06059.RTI TGR06059.RTP
TGR06059.RTR TGR06059.RTS TGR06059.RTT TGR06059.RTZ
OGRINFO Examples
Using ogrinfo to examine the structure of the TIGER feature type CompleteChain:
> ogrinfo TGR06059 CompleteChain -summary
ERROR 4: Tiger Driver doesn’t support update.
Had to open data source read-only.
INFO: Open of ‘TGR06059’
using driver ‘TIGER’ successful.
Table of Contents
• Virtual Spatial Data
– Types of Databases
– Types of Flat Files
– Steps for Display
This is an OGR extension to MapServer. It allows you to connect to databases that do not explicitly hold spatial data,
as well as flat text files. Your data must have an X and a Y column, and the data may be accessed through an ODBC
connection or a direct pointer to a text file.
The original VirtualSpatialData wiki page may contain additional information.
Types of Databases
The VirtualSpatialData OGR extension has been tested with the following databases and should, in theory, support all
ODBC data sources.
• Oracle
• MySQL
• SQL Server
• Access
• PostgreSQL
• Specific notes about creating a DSN on Windows and Linux can be found by searching the MapServer reference
documents site
• On some Windows systems you must create a SYSTEM DSN.
Test your connection with ogrinfo. The syntax for this command is:
> ogrinfo ODBC:user/pass@DSN table
Windows users may not be required to specify a user/password, so the syntax would be:
> ogrinfo ODBC:@DSN table
Example: Accessing a comma separated text file through ODBC using ogrinfo
The following is a snippet of the flat text file coal_dep.txt containing lat/long points:
unknown,na,id,id2,mark,coalkey,coalkey2,long,lat
0.000,0.000,1,1,7,87,87,76.90238,51.07161
0.000,0.000,2,2,7,110,110,78.53851,50.69403
0.000,0.000,3,3,3,112,112,83.22586,71.24420
0.000,0.000,4,4,6,114,114,80.79896,73.41175
If the DSN name is Data_txt, the ogrinfo command to see a list of applicable files in the directory is:
> ogrinfo ODBC:jeff/test@Data_txt
INFO: Open of ‘ODBC:jeff/test@Data_txt’
using driver ‘ODBC’ successful.
1: coal_dep.csv
2: coal_dep.txt
3: coal_dep_nf.txt
4: coal_dep_trim.txt
5: Copy of coal_dep.txt
6: deposit.csv
7: maruia.asc
8: oahuGISbathy.csv
9: oahuGISbathy.txt
10: on_pts.txt
11: on_pts_utm.txt
12: test.txt
13: utm_test.txt
Username and password may be optional, so the following may also be valid:
> ogrinfo ODBC:@Data_txt
Therefore, the command to see more information about one of the specific layers is:
> ogrinfo ODBC:@Data_txt coal_dep.txt
INFO: Open of ‘ODBC:@Data_txt’
using driver ‘ODBC’ successful.
This is a file with an ovf extension and looks like the following:
<OGRVRTDataSource>
<OGRVRTLayer name="mylayer">
<SrcDataSource>ODBC:user/pass@DSN</SrcDataSource>
<SrcLayer>tablename</SrcLayer>
<GeometryType>wkbPoint</GeometryType>
<LayerSRS>WGS84</LayerSRS>
<GeometryField encoding="PointFromColumns" x="x" y="y"/>
</OGRVRTLayer>
</OGRVRTDataSource>
5. Mapfile Layer
END
NAME "coal-test"
SIZEUNITS PIXELS
STATUS ON
TOLERANCE 0
TOLERANCEUNITS PIXELS
TYPE POINT
UNITS METERS
CLASS
STYLE
COLOR 255 0 0
MAXSIZE 100
MINSIZE 1
SIZE 6
SYMBOL "star"
END
END
END
The first thing you should try is to use the shp2img utility:
shp2img -m mymapfile.map -o test.png
Once you successfully created a map image, then try your application. Note Windows users may come across a
problem where shp2img works but their application throws an error similar to this:
Warning: [MapServer Error]: msOGRFileOpen(): Open failed for OGR connection ‘coal.ovf’.
Unable to initialize ODBC connection to DSN for jeff/test@Data_txt,
[Microsoft][ODBC Driver Manager] Data source name not found
and no default driver specified in D:\ms4w\Apache\htdocs\quickmap.php on line 40
If that happens you should make sure you have created a System DSN.
7.1.22 WFS
WFS is an Open Geospatial Consortium (OGC) specification. For more information about the format itself, see:
http://www.opengeospatial.org/standards/wfs
WFS allows a client to retrieve geospatial data encoded in Geography Markup Language (GML) from multiple Web
Feature Services. GML is built on the standard web language XML.
WFS differs from the popular Web Map Service (WMS) specification in that WFS returns a subset of the data in valid
GML format, not just a graphic image of data.
Capabilities
Requesting the capabilities using the GetCapabilities request to a WFS server returns an XML document showing
what layers and projections are available, etc. Example of a WFS GetCapabilities URL:
http://demo.mapserver.org/cgi-bin/wfs?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetCapabilities
Example of the Resulting XML from GetCapabilties:
...
<FeatureTypeList>
<Operations>
<Query/>
</Operations>
<FeatureType>
<Name>continents</Name>
<Title>World continents</Title>
<SRS>EPSG:4326</SRS>
<LatLongBoundingBox minx="-180" miny="-90" maxx="180" maxy="83.6274"/>
</FeatureType>
<FeatureType>
<Name>cities</Name>
<Title>World cities</Title>
<SRS>EPSG:4326</SRS>
<LatLongBoundingBox minx="-178.167" miny="-54.8" maxx="179.383" maxy="78.9333"/>
</FeatureType>
</FeatureTypeList>
...
• WFS access is a core MapServer feature. MapServer currently supports WFS version 1.0.0
• The CONNECTIONTYPE WFS parameter must be used.
• WFS layers can be requested through a layer in a map file, or you can request the GML directly through the
browser with a GetFeature request. You can specify a specific layer with the TypeName request. In a map file
the name/value pairs should be put into a METADATA object.
• You can limit the number of features returned in the GML by using the MaxFeatures option (e.g. &MAXFEA-
TURES=100).
Example of a WFS Request Directly Through the Browser:
The following URL requests the GML for the layer continents. (see the GetCapabilities above for the possible layers
available on this test server) . The URL is all one line, broken up here for readability (click here for a working link).
http://demo.mapserver.org/cgi-bin/wfs?
SERVICE=WFS&
VERSION=1.0.0&
REQUEST=getfeature&
TYPENAME=continents&
MAXFEATURES=100
LAYER
NAME "continents"
TYPE POLYGON
STATUS ON
CONNECTION "http://demo.mapserver.org/cgi-bin/wfs?"
CONNECTIONTYPE WFS
METADATA
"wfs_typename" "continents"
"wfs_version" "1.0.0"
"wfs_connectiontimeout" "60"
"wfs_maxfeatures" "10"
END
PROJECTION
"init=epsg:4326"
END
CLASS
NAME "Continents"
STYLE
COLOR 255 128 128
OUTLINECOLOR 96 96 96
END
END
END # Layer
Table of Contents
• Raster Data
– Introduction
– How are rasters added to a Map file?
– Supported Formats
– Rasters and Tile Indexing
– Raster Warping
– 24bit RGB Rendering
– Special Processing Directives
– Raster Query
– Raster Display Performance Tips
– Preprocessing Rasters
– Georeference with World Files
7.2.1 Introduction
MapServer supports rendering a variety of raster file formats in maps. The following describes some of the supported
formats, and what capabilities are supported with what formats.
This document assumes that you are already familiar with setting up MapServer Mapfile, but does explain the raster
specific aspects of mapfiles.
A simple raster layer declaration looks like this. The DATA file is interpreted relative to the SHAPEPATH, much like
shapefiles.
LAYER
NAME "JacksonvilleNC_CIB"
DATA "Jacksonville.tif"
TYPE RASTER
STATUS ON
END
Though not shown rasters can have PROJECTION, METADATA, PROCESSING, MINSCALE, and MAXSCALE
information. It cannot have labels, CONNECTION, CONNECTIONTYPE, or FEATURE information.
Classifying Rasters
As usual, CLASS definitions are evaluated in order from first to last, and the first to match is used. If a CLASS has
a NAME attribute it may appear in a LEGEND. Only the COLOR, EXPRESSION and NAME parameters within a
CLASS definition are utilized for raster classifications. The other styling or control information is ignored.
Raster classifications always take place on only one raster band. It defaults to the first band in the referenced file, but
this can be altered with the BANDS PROCESSING directive. In particular this means that including even a single
CLASS declaration in a raster layer will result in the raster layer being rendered using the one band classification rules
instead of other rules that might have applied (such as 3 band RGB rendering).
As of MapServer 4.4 support has been added for classifying non-8bit raster inputs. That is input rasters with values
outside the range 0-255. Mostly this works transparently but there are a few caveats and options to provide explicit
control.
Classifying raster data in MapServer is accomplished by pre-classifying all expected input values and using that table
of classification results to lookup each pixel as it is rendered. This is done because evaluating a pixel value against a
series of CLASS definitions is relatively expensive to do for the hundreds of thousands of pixels in a typical rendered
image.
For simple 8bit inputs, only 256 input values need to be pre-classified. But for non-8bit inputs more values need to be
classified. For 16bit integer inputs all 65536 possible input values are pre-classified. For floating point and other input
data types, up to 65536 values are pre-classified based on the maximum expected range of input values.
The PROCESSING directive can be used to override the range of values to be pre-classified, or the number of val-
ues (aka Buckets) in that range to classify. The SCALE=min,max PROCESSING directive controls the range. The
SCALE_BUCKETS PROCESSING directive controls the number of buckets. In some cases rendering can be accel-
erated considerable by selecting a restricted range of input values and a reduced number of scaling values (buckets).
The following example classifies a floating raster, but only 4 values over the range -10 to 10 are classified. In particular,
the values classified would be -7.5, -2.5, 2.5, and 7.5 (the middle of each “quarter” of the range). So those four value
are classified, and one of the classification results is selected based on which value is closest to the pixel value being
classified.
LAYER
NAME grid1
TYPE raster
STATUS default
DATA data/float.tif
PROCESSING "SCALE=-10,10"
PROCESSING "SCALE_BUCKETS=4"
CLASS
NAME "red"
EXPRESSION ([pixel] < -3)
STYLE
COLOR 255 0 0
END
END
CLASS
NAME "green"
EXPRESSION ([pixel] >= -3 and [pixel] < 3)
STYLE
COLOR 0 255 0
END
END
CLASS
NAME "blue"
EXPRESSION ([pixel] >= 3)
STYLE
COLOR 0 0 255
END
END
END
What raster formats are supported by MapServer is largely controlled by configuration time options. Some formats
are considered to be built-in while the remainder are handled by the optional GDAL raster library.
More information on GDAL can be found at http://www.gdal.org, including the supported formats list. Some of the
advanced MapServer raster features, such as resampling, RGB color cube generation and automatic projection capture
only work with raster formats used through GDAL. GDAL is normally built and installed separately from MapServer,
and then enabled during the build of MapServer using the –with-gdal configuration switch.
To find out what is built into a particular MapServer executable, use the -v flags to discover what build options are
enabled. To find out what GDAL formats are available, the “gdalinfo –formats” command may be used. For example:
warmerda@gdal2200[124]% mapserv -v
MapServer version 4.4.0-beta2 OUTPUT=GIF OUTPUT=PNG OUTPUT=JPEG OUTPUT=WBMP
SUPPORTS=PROJ SUPPORTS=FREETYPE SUPPORTS=WMS_SERVER SUPPORTS=WMS_CLIENT
SUPPORTS=WFS_SERVER SUPPORTS=WFS_CLIENT SUPPORTS=WCS_SERVER SUPPORTS=FASTCGI
INPUT=EPPL7 INPUT=POSTGIS INPUT=OGR INPUT=GDAL INPUT=SHAPEFILE DEBUG=MSDEBUG
warmerda@gdal2200[18]% gdalinfo --formats
Supported Formats:
GRASS (ro): GRASS Database Rasters (5.7+)
GTiff (rw+): GeoTIFF
NITF (rw+): National Imagery Transmission Format
HFA (rw+): Erdas Imagine Images (.img)
SAR_CEOS (ro): CEOS SAR Image
...
If MapServer is built with GDAL it is generally better to access all possible formats through GDAL rather than via the
built-in drivers. The built-in drivers are less featureful, and not as well maintained.
When handling very large raster layers it is often convenient, and higher performance to split the raster image into a
number of smaller images. Each file is a tile of the larger raster mosaic available for display. The list of files forming a
layer can be stored in a shapefile with polygons representing the footprint of each file, and the name of the files. This
is called a TILEINDEX and works similarly to the same feature in vector layers. The result can be represented in the
MAP file as one layer, but MapServer will first scan the tile index, and ensure that only raster files overlapping the
current display request will be opened.
The following example shows a simple example. No DATA statement is required because MapServer will fetch the
filename of the raster files from the Location attribute column in the hp2.dbf file for records associated with polygons
in hp2.shp that intersect the current display region. The polygons in hp2.shp should be rectangles representing the
footprint of the corresponding file. Note that the files do not have to be all the same size, the formats can vary and they
can even overlap (later files will be drawn over earlier ones); however, they must all be in the same coordinate system
(projection) as the layer.
LAYER
NAME "hpool"
STATUS ON
TILEINDEX "hp2.shp"
TILEITEM "Location"
TYPE RASTER
END
The filenames in the tileindex are searched for relative to the SHAPEPATH or map file, not relative to the tileindex.
Great care should be taken when establishing the paths put into the tileindex to ensure they will evaluate properly
in use. Often it is easiest to place the tileindex in the SHAPEPATH directory, and to create the tileindex with a path
relative to the SHAPEPATH directory. When all else fails, absolute paths can be used in tileindex, but then they cannot
be so easily moved from system to system.
While there are many ways to produce TILEINDEX shapefiles for use with this command, one option is the gdaltindex
program, part of the GDAL utility suite. The gdaltindex program will automatically generate a tile index shapefile from
a list of GDAL supported raster files passed on the command line.
Usage: gdaltindex [-tileindex field_name] index_file [gdal_file]*
See Also:
Tile Indexes
MapServer is able to resample GDAL rasters on the fly into new projections. Non-GDAL rasters may only be up or
down sampled without any rotation or warping.
Raster warping kicks in if the projection appears to be different for a raster layer than for the map being generated.
Warped raster layers are significantly more expensive to render than normal raster layers with rendering time being
perhaps 2-4 times long than a normal layer. The projection and datum shifting transformation is computed only at
selected points, and generally linearly interpolated along the scanlines (as long as the error appears to be less than
0.333 pixels.
In addition to reprojecting rasters, the raster warping ability can also apply rotation to GDAL rasters with rotational
coefficients in their georeferencing information. Currently rotational coefficients won’t trigger raster warping unless
the map and layer have valid (though matching is fine) projection definitions.
Traditionally MapServer has been used to produce 8 bit pseudo-colored map displays generated from 8bit greyscale
or pseudocolored raster data. However, if the raster file to be rendered is actually 24bit (a red, green and blue band)
then additional considerations come into play. Currently rendering of 24bit imagery is only supported via the GDAL
renderer. The built-in PNG, JPEG and other drivers do not support 24bit input images.
If the output is still 8bit pseudo-colored (the IMAGEMODE is PC256 in the associated OUTPUT format declaration)
then the full 24bit RGB colors for input pixels will be converted to a color in the colormap of the output image. By
default a color cube is used. That is a fixed set of 175 colors providing 5 levels of red, 7 levels of green and 5 levels
of blue is used, plus an additional 32 greyscale color entries. Colors in the input raster are mapped to the closest color
in this color cube on the fly. This substantial degrades color quality, especially for smoothly changing images. It also
fills up the colors table, limited to 256 colors, quite quickly.
A variation on this approach is to dither the image during rendering. Dithering selects a color for a pixel in a manner
that “diffuses error” over pixels. In an area all one color in the source image, a variety of output pixel colors would
be selected such that the average of the pixels would more closely approximate the desired color. Dithering also takes
advantage of all currently allocated colors, not just those in the color cube. Dithering requires GDAL 1.1.9 or later, and
is enabled by providing the PROCESSING “DITHER=YES” option in the mapfile. Dithering is more CPU intensive
than using a simple color cube, and should be avoided if possible in performance sensitive situations.
The other new possibility for handling 24bit input imagery in MapServer 4.0 or later, is to produce 24bit output images.
The default “IMAGETYPE png24” or “IMAGETYPE jpeg” declaration may be used to produce a 24bit PNG output
file, instead of the more common 8bit pseudo-colored PNG file. The OUTPUTFORMAT declaration provides for
detailed control of the output format. The IMAGEMODE RGB and IMAGEMODE RGBA options produce 24bit and
32bit (24bit plus 8bit alpha/transparency) for supported formats.
As of MapServer 4.0, the PROCESSING parameter was added to the LAYER of the Mapfile. It is primarily used to
pass specialized raster processing options to the GDAL based raster renderer. The following processing options are
supported in MapServer 4.0 and newer.
DITHER=YES This turns on error diffusion mode, used to convert 24bit images to 8bit with error diffusion to get
better color results.
Example:
PROCESSING "DITHER=YES"
BANDS=red_or_grey[,green,blue[,alpha]] This directive allows a specific band or bands to be selected from a raster
file. If one band is selected, it is treated as greyscale. If 3 are selected, they are treated as red, green and blue. If
4 are selected they are treated as red, green, blue and alpha (opacity).
Example:
PROCESSING "BANDS=4,2,1"
SCALE[_n]=AUTO or min,max This directive instructs the GDAL reader to pre-scale the incoming raster data. It
is primarily used to scale 16bit or floating point data to the range 0-255, but can also be used to constrast stretch
8bit data. If an explicit min/max are provided then the input data is stretch (or squished) such that the minimum
value maps to zero, and the maximum to 255. If AUTO is used instead, a min/max is automatically computed.
To control the scaling of individual input bands, use the SCALE_1, SCALE_2 and SCALE_3 keywords (for
red, green and blue) instead of SCALE which applies to all bands.
Example:
PROCESSING "SCALE=AUTO"
or
PROCESSING "SCALE_1=409,1203"
PROCESSING "SCALE_2=203,296"
PROCESSING "SCALE_3=339,1004"
LUT[_n]=<lut_spec> This directive (MapServer 4.9+) instructs the GDAL reader to apply a custom LUT (lookup
table) to one or all color bands as a form of on the fly color correction. If LUT is used, the LUT is applied to all
color bands. If LUT_n is used it is applied to one color band (n is 1 for red, 2 for green, 3 for blue, 4 for alpha).
The LUT can be specified inline in the form:
<lut_spec> = <in_value>:<out_value>[,<in_value>:<out_value>]*
This essentially establish particular input values which are mapped to particular output values. The list implicitly
begins with 0:0, and 255:255. An actual 256 entry lookup table is created from this specification, linearly
interpolating between the values. The in values must be in increasing order. The LUT specification may also be
in a text file with the <lut_spec> being the filename. The file contents should be in the same syntax, and the file
is searched relative to the mapfile.
Example:
PROCESSING "LUT_1=red.lut"
PROCESSING "LUT_2=green.lut"
PROCESSING "LUT_3=blue.lut"
or
PROCESSING "LUT=100:30,160:128,210:200"
As a special case there is also support for GIMP format curve files. That is the text files written out by the
Tools->Color->Curves tool. If this is specified as the filename then it will be internally converted into linear
segments based on the curve control points. Note that this will not produce exactly the same results as the
GIMP because linear interpolation is used between control points instead of curves as used in the GIMP. For a
reasonable number of control points the results should be similar. Also note that GIMP color curve files include
an overall “value” curve, and curves for red, green, blue and alpha. The value curve and the appropriate color
curve will be composed internally to produce the final LUT.
Example:
PROCESSING "LUT=munich.crv"
COLOR_MATCH_THRESHOLD=n Alter the precision with which colors need to match an entry in the color
table to use it when producing 8bit colormapped output (IMAGEMODE PC256). Normally colors from a raster
colormap (or greyscale values) need to match exactly. This relaxes the requirement to being within the specified
color distance. So a COLOR_MATCH_THRESHOLD of 3 would mean that an existing color entry within 3
(sum of difference in red, green and blue) would be used instead of creating a new colormap entry. Especially
with greyscale raster layers, which would normally use all 256 color entries if available, this can be a good way
to avoid “stealing” your whole colormap for a raster layer. Normally values in the range 2-6 will give good
results.
Example:
PROCESSING "COLOR_MATCH_THRESHOLD=3"
RESAMPLE=NEAREST/AVERAGE/BILINEAR This option can be used to control the resampling kernel used
sampling raster images. The default (and fastest) is NEAREST. AVERAGE will perform compute the average
pixel value of all pixels in the region of the disk file being mapped to the output pixel (or possibly just a sampling
of them). BILINEAR will compute a linear interpolation of the four pixels around the target location. This topic
is discussed in more detail in MS RFC 4: MapServer Raster Resampling.
Resampling options other than NEAREST result in use of the generalized warper and can dramatically slow
down raster processing. Generally AVERAGE can be desirable for reducing noise in dramatically downsampled
data, and can give something approximating antialiasing for black and white linework. BILINEAR can be
helpful when oversampling data to give a smooth appearance.
Example (chose one):
PROCESSING "RESAMPLE=NEAREST"
PROCESSING "RESAMPLE=AVERAGE"
PROCESSING "RESAMPLE=BILINEAR"
LOAD_FULL_RES_IMAGE=YES/NO This option affects how image data is loaded for the resampler when repro-
jecting or otherwise going through complex resampling (as opposed to the fast default image decimation code
path). This forces the source image to be loaded at full resolution if turned on (default is NO). This helps work
around problems with default image resolution selection in when radical warping is being done. It can result in
very slow processing if the source image is large.
LOAD_WHOLE_IMAGE=YES/NO This option affects how image data is loaded for the resampler (as above). This
option, if turned on, will cause the whole source image to be loaded and helps make up for problem identifying
the area required, usually due to radical image reprojection near a dateline or projection “horizon”. The default
is NO. Turning this on can dramatically affect rendering performance and memory requirements.
A new feature added in MapServer 4.4 is the ability to perform queries on rasters in a manner similar to queries
against vector layers. Raster queries on raster layers return one point feature for each pixel matching the query. The
point features will have attributes indicating the value of different bands at that pixel, the final rendering color and
the class name. The resulting feature can be directly access in MapScript, or processed through templates much like
normal vector query results. Only raster layers with a query TEMPLATE associated can be queried, even for the query
methods that don’t actually use the query template (much like vector data).
Raster query supports QueryByPoint, QueryByRect, and QueryByShape. QueryByPoint supports single and multiple
result queries. Other query operations such as QueryByIndex, QueryByIndexAdd, QueryByAttributes and Query-
ByFeature are not supported for raster layers.
Raster layers do not support saving queries to disk, nor query maps.
Raster queries return point features with some or all of the following attributes:
x georeferenced X location of pixel.
y georeferenced Y location of pixel.
value_list a comma separated list of the values of all selected bands at the target pixel.
value_n the value for the n’th band in the selected list at this pixel (zero based). There is one value_n
entry for each selected band.
class Name of the class this pixel is a member of (classified layers only).
red red component of the display color for this pixel.
green green component of the display color for this pixel.
blue blue component of the display color for this pixel.
The red, green and blue attribute are intended to be the final color the pixel would be rendered with, but in some subtle
cases it can be wrong (ie. classified floating point results). The selected bands are normally the band that would be
used to render the layer. For a pure query-only layer BANDS PROCESSING directive can be used to select more
bands than could normally be used in a render operation. For instance for a 7 band landsat scene a PROCESSING
“BANDS=1,2,3,4,5,6,7” directive could be used to get query results for all seven bands in results to a query operation.
Care should be taken to avoid providing a large query area (selecting alot of pixels) as each selected pixel requires
over 100 bytes of memory for temporary caching. The RASTER_QUERY_MAX_RESULT PROCESSING item can
be used to restrict the maximum number of query results that will be returned. The default is one million which would
take on the order of 100MB of RAM.
Query results can be returned as HTML via the normal substitution into query template HTML. Query results are also
accessible via WMS GetFeatureInfo calls, and from MapScript. The following example shows executing a feature
query from Python MapScript and fetching back the results:
map = mapscript.Map(’rquery.map’)
layer = map.getLayer(0)
pnt = mapscript.Point()
pnt.x = 440780
pnt.y = 3751260
layer.open()
for i in range(1000):
result = layer.getResult( i )
if result is None:
break
layer.close()
This following is a simple example query TEMPLATE file. The raster pixel attributes will be substituted in before the
query result is returned to the user as HTML.
Pixel:<br>
values=[value_list]<br>
value_0=[value_0]<br>
value_1=[value_1]<br>
value_2=[value_2]<br>
RGB = [red],[green],[blue]<p>
Class = [class]<br>
Internally raster query results are essentially treated as a set of temporary features cached in RAM. Issuing a new
query operation clears the existing query cache on the layer. The transitory in-memory representation of raster query
results is also responsible for the inability to save raster query results since saved query results normally only contain
the feature ids, not the entire features. Some addition information is available in the RasterQuery Wiki topic.
• Build overview levels for large rasters to ensure only a reasonable amount of data needs to be touched to display
an overview of a large layer. Overviews can be implemented as a group of raster layers at different resolutions,
using MINSCALE, and MAXSCALE to control which layers are displayed at different resolutions. Another,
perhaps easier way, is to build overviews for GDAL supported formats using the gdaladdo utility.
• When using tileindexes to manage many raster files as a single file, it is especially important to have an overview
layer that kicks in at high scales to avoid having to open a large number of raster files to fulfill the map request.
• Preprocess RGB images to eightbit with a colormap to reduce the amount of data that has to be read, and the
amount of computation to do on the fly.
• For large images use tiling to reduce the overhead for loading a view of a small area. This can be accomplished
using the TILEINDEX mechanism of the mapfile, or by creating a tiled format file (ie. TIFF with GDAL).
• Ensure that the image is kept on disk in the most commonly requested projection to avoid on-the-fly image
warping which is fairly expensive.
• If you are getting debug output from MapServer in your web server log file, check to see if the message msRe-
sampleGDALToMap in effect appears. If so, the raster layer is being resampled. If you don’t think it should be
resampled carefully review your map file to ensure that the layer projection exactly matches the map projection
or that the layer has no projection definition.
The following operations use GDAL commandline utilities, some of which are python scripts. They are generally
available on any GDAL installation with python support.
The TIFF and Erdas Imagine formats support internal tiling within files, and will generally give better display speed
for local map requests from large images. To produce a GeoTIFF file in internally tiled format using the TILED=YES
creation option with the gdal_translate utility:
gdal_translate -co TILED=YES original.tif tiled.tif
Erdas Imagine (HFA) files are always tiled, and can be larger than 4GB (the GeoTIFF limit). Use a command like the
following to translate a raster to Imagine format:
gdal_translate -of HFA original.tif tiled.img
Rendering and returning 24bit images (especially as PNG) can be quite expensive in render/compress time and band-
width. Pre-reducing raster data to 8bit can save disk space, processing time, and bandwidth. However, such a color
reduction also implicitly reduces the quality of the resulting map. The color reduction can be done on the fly by
MapServer but this requires even more processing. A faster approach is to pre-reduce the colors of 24bit imagery to
8bit. This can be accomplished with the GDAL rgb2pct.py script like this:
rgb2pct.py original.tif 8bit.tif
By default images will be reduced to 256 colors but this can mean there are not enough colors to render other colors
in the map. So it may be desired to reduce to even less colors:
rgb2pct.py -n 200 original.tif 8bit.tif
Downsampling to 8bit should be done before internal tiling and overview building. The rgb2pct.py script tries to
compute an optimal color table for a given image, and then uses error diffusion during the 24bit to 8bit reduction.
Other packages (such as ImageMagick or Photoshop) may have alternative color reduction algorithms that are more
appropriate for some uses.
Most GDAL supported raster formats can have overviews pre-built using the gdaladdo utility. However, a few formats,
such as JPEG2000, MrSID, and ECW already contain implicit overviews in the format themselves and will not gener-
ally benefit from external overviews. For other formats (such as GeoTIFF, and Erdas Imagine format) use a command
like the following to build overviews:
gdaladdo tile.tif 2 4 8 16 32 64 128
The above would build overviews at x2 through x128 decimation levels. By default it uses “nearest neighbour”
downsampling. That is one of the pixels in the input downsampled area is selected for each output pixel. For some
kinds of data averaging can give much smoother overview results, as might be generated with this command:
gdaladdo -r average tiled.tif 2 4 8 16 32 64 128
Note that overview building should be done after translating to a final format. Overviews are lost in format conversions
using gdal_translate. Also, nothing special needs to be done to make MapServer use GDAL generated overviews. They
are automatically picked up by GDAL when mapserver requests a reduced resolution map.
When working with large collections of raster files using a MapServer tileindex, it is desirable to build reduced reso-
lution overview layers that kick in at high scales (using MINSCALE/MAXSCALE to control which layer activates).
Preparing the overviews can be a somewhat complex process. One approach is to use the gdal_merge.py script to
downsample and mosaic all the images. For instance if we want to produce an overview of many 1meter ortho photos
with 250 meter pixels we might do something like:
gdal_merge.py -o overview.tif -ps 250 250 ortho_*.tif
The gdal_merge.py utility suffers from a variety of issues, including no support for different resampling kernels. With
GDAL 1.3.2 or later it should be able to accomplish something similar with the more flexible gdalwarp utility:
gdalwarp -rc -tr 250 250 ortho_*.tif overview.tif
In some cases the easiest way of generating an overview is to let MapServer do it using the shp2img utility. For
instance if the tileindex layer is called ‘’orthos” we could do something like:
Note that the overview will be generated with the extents and size in the .map file, so it may be necessary to temporarily
adjust the map extents and size values to match the raster extents and the desired output size. Also, if using this method,
don’t leave large files in PNG (or GIF or JPEG) format as they are slow formats to extract subareas from.
World files are a simple mechanism for associating georeferencing (world coordinates) information with raster files.
ESRI was the first company to propagate the use of world files, and they often used with TIFF instead of embedding
georeferencing information in the file itself.
The world file contents look like the following. The first coefficient is the X pixel size. The second and third are
rotational/shear coefficients (and should normally be 0.0). The fourth is the Y pixel size, normally negative indicating
that Y decreases as you move down from the top left origin. The final two values are the X and Y location of the
center of the top left pixel. This example is for an image with a 2m x 2m pixel size, and a top left origin at (356800E,
5767999N):
2
0.0000000000
0.0000000000
-2
356800.00
5767999.00
The name of the world file is based on the file it relates to. For instance, the world file for aerial.tif might be aerial.tfw.
Conventions vary for appropriate endings, but with MapServer the extension .wld is always OK for world files.
Since the GDAL/OGR library is used for vector and raster access in MapServer, many more formats are supported, so
please see the OGR (vector) and GDAL (raster) formats pages.
Output Generation
Table of Contents
• AGG Rendering Specifics
– Introduction
– Setting the OutputFormat
– New Features
– Modified Behavior
8.1.1 Introduction
MapServer 5.0 released with a new rendering backend. This howto details the changes and new functionality that this
adds to map creation. This howto assumes you already now the basics of mapfile syntax. If not, you should probably
be reading the mapfile syntax.
339
MapServer Documentation, Release 6.0
24 bit jpeg (jpeg compression artifacts may appear, but smaller file size):
OUTPUTFORMAT
NAME ’AGG_JPEG’
DRIVER AGG/JPEG
IMAGEMODE RGB
END
• All rendering is now done antialiased by default. All ANTIALIAS keywords are now ignored, as well as
TRANSPARENCY ALPHA. Pixmaps and fonts are now all drawn respecting the image’s internal alpha channel
(unless a backgroundcolor is specified).
• As with GD in ver. 4.10, using a SYMBOL of type ELLIPSE to draw thick lines isn’t mandatory anymore. To
draw a thick line just use:
STYLE
WIDTH 5
COLOR 0 0 255
END
• A line symbolizer has been added, that works with vector or pixmap symbols, to draw textured lines. This
happens by default if a line’s style is given a symbol of type vector or pixmap. To enable “shield” symbolization,
i.e. a marker placed only on some points of the line, you must add a GAP parameter to your symbol definition.
This GAP value is scaled w.r.t the style’s SIZE parameter. Specify a positive gap value for symbols always
facing north (optionally rotated by the ANGLE of the current style), or a negative value for symbols that should
follow the line orientation
• This happens by default if a line’s style is given a symbol of type vector or pixmap. To enable “shield” sym-
bolization, i.e. a marker placed only on some points of the line, you must add a GAP parameter to your symbol
definition. This GAP value is scaled w.r.t the style’s SIZE parameter - specify a positive gap value for symbols
always facing north (optionally rotated by the ANGLE of the current style), or a negative value for symbols that
should follow the line orientation
• Pixmap and font symbols can now be rotated without loosing their transparency
• For POLYGON layers with no specific SYMBOL, the WIDTH keyword specifies the width of the outline, if
an OUTLINECOLOR was specified. This is a shorthand that avoids having to create multiple styles for basic
rendering, and will provide a marginal performance gain. Note that in this case, the width of the outline is /not/
scale dependent.
• When specifying a SYMBOL for a polygon shape, the GAP parameter of the symbol is used as a separation
between each rendered symbol. This works for symbols of type vector, pixmap and ellipse. For example a
symbol defined by
SYMBOL
NAME ’triangle’
TYPE VECTOR
FILLED TRUE
POINTS
0 1
.5 0
1 1
0 1
END
GAP 1
END
Note: For quality antialiased output from mapserver, it is highly recommended to use the AGG rendering. This
document applies only if you whish to stick to the GD rendering, or if you are using a version predating the 5.0 release
of mapserver.
Table of Contents
• AntiAliasing with MapServer
– What needs to be done
1. Change (or add) IMAGETYPE keyword in MAP object to PNG24 (24-bit PNG output) or JPEG
MAP
...
IMAGETYPE P N G 24
...
END
LAYER
...
TRANSPARENCY ALPHA
...
END
END
3. Add ANTIALIAS keyword to the STYLE object within the CLASS object within the LAYER and set value to
TRUE
MAP
...
IMAGETYPE P N G 24
...
LAYER
...
TRANSPARENCY ALPHA
...
CLASS
...
STYLE
...
ANTIALIAS TRUE
...
END
\.\.\.
END # end class
END # end layer
END # end map
Note: Don’t use the SYMBOL or the SIZE keywords within the CLASS object, instead use WIDTH to specify width
of line or polygon outline. Don’t use WIDTH unless you have to. If you must define a SYMBOL, use symbol of type
ELLIPSE–it supports antialiasing.
Here’s an example of a real-world mapfile:
Note: From Mapserver 6, symbol type CARTOLINE is no longer supported. You have to use AGG rendering and
STYLE PATTERN to achieve dashed lines. Therefore, the following example does not work anymore.
1 MAP
2 NAME ’ms101’
3 EXTENT -2198022.00 -2444920.25 2707932.00 1234545.25 # CONUS LAEA (US)
4 SIZE 640 480
5 SHAPEPATH ’data’
6 SYMBOLSET ’symbols/symbols.txt’
7
8 IMAGETYPE P N G 24
9
10 PROJECTION
11 "init=epsg:2163"
12 END
13
24 PROJECTION
25 "init=epsg:4326"
26 END
27
28 CLASS
29 NAME ’Country Boundary’
30 STYLE
31 COLOR 96 96 96
32 ANTIALIAS TRUE
33 END
34 END
35 END # end country boundary layer
36
37 # The layer below shows one way to draw a polygon with antialiased outline
38 LAYER # begin antialiased country boundary (polygon) layer
39 NAME ’country_line’
40 DATA ’shapefile/Countries_area’
41 TYPE POLYGON
42 STATUS ON
43 TRANSPARENCY ALPHA
44
45 PROJECTION
46 "init=epsg:4326"
47 END
48
49 CLASS
50 NAME ’Country Boundary’
51 STYLE
52 COLOR 212 212 212
53 OUTLINECOLOR 96 96 96
54 WIDTH 3
55 ANTIALIAS TRUE
56 END
57 END
58 END # end country boundary polygon layer
59
60 # The layer below shows one way to draw a polygon with antialiased outline
61 LAYER # begin antialiased state boundary (line) layer
62 NAME ’state_line’
63 DATA ’shapefile/us_states’
64 TYPE LINE
65 STATUS ON
66 TRANSPARENCY ALPHA
67
68 PROJECTION
69 "init=epsg:4326"
70 END
71
72 CLASS
73 NAME ’State Boundary’
74 STYLE
75 COLOR 144 144 144
76 SYMBOL ’cartoline’
77 ANTIALIAS TRUE
78 END
79 END
80 END # end state line layer
81 END # end of map file
Note: The examples provided here are for illustrative purposes only–keep your map file definitions simple. Antialias-
ing adds computing overhead on the server and could slow/degrade its performance. Don’t use it unless you must and
certainly don’t use symbols with it unless you really have to.
Table of Contents
• Dynamic Charting
– Setup
– Adding a Chart Layer to a Mapfile
– Pie Charts
– Bar Graphs
Starting with version 5.0, MapServer included the ability to automatically draw pie or bar graphs whose values are
taken and adjusted from attributes of a datasource.
This document assumes that you are already familiar with MapServer application development and especially setting
up Mapfile s. You can also check out the Vector Data Access Guide, which has lots of examples of how to access
specific data sources.
8.3.1 Setup
Supported Renderers
Dynamic charts are supported solely with the GD and AGG renderers.
Attempting to add a chart layer with any other renderer (e.g. PDF or SWF) will result in an error. Rendering quality
with the GD renderer is less than optimal, especially with small graphs, due to the lack of subpixel rendering functions.
MapServer GD Rendering
Layer Type
A new type of layer has been added to the mapfile syntax. To specify a chart layer, use
LAYER
...
TYPE CHART
...
END
No other specific keywords have been added in order to keep the number of different keywords to a minimum in the
mapfile syntax, therefore all the chart specific configuration is determined by PROCESSING directives.
The size of each chart is specified by the CHART_SIZE directive. If two values are given for this parameter, this will
specify the width and height of each chart (this only applies for bar graphs). By default, the charts are 20x20 pixels.
LAYER
TYPE CHART
PROCESSING "CHART_SIZE=21" # specify size of the chart for pie or bar graphs
#PROCESSING "CHART_SIZE=20 10" # specify width and height for bar graphs
...
END
From version 5.2 and onwards, the diameter of a pie chart can be bound to an attribute,using the
CHART_SIZE_RANGE PROCESSING attribute:
PROCESSING "CHART_SIZE_RANGE = itemname minsize maxsize minval maxval"
where:
• itemname is the name of the attribute that drives the chart size (e.g. total_sales)
• minsize and maxsize are the minimum and maximum chart size values in pixels (e.g. “10 100”)
• minval and maxval are the minimum values of the attribute that correspond to chart sizes of minsize and maxsize
(e.g. 10000 1000000).
If the attribute value is smaller than ‘minval’ then the chart size will be minsize pixels, and if the attribute value is
larger than maxval, the chart size will be maxsize pixels.
Each value to be plotted (i.e. a slice in a pie chart, or a bar in a par graph) is specified in a CLASS of the chart layer.
The value to be plotted is taken from the SIZE keyword from the first STYLE block of the class. This is semantically
a bit awkward, but keeps the number of different keywords to a minimum in the mapfile syntax. The value given to
the SIZE keyword could of course be given a static value, but dynamic charting really only makes sense with attribute
binding.
LAYER
...
CLASS
# include a NAME keyword if you want this class to be included
# in the legend
NAME "value 1"
STYLE
# specify which value from the data source will be used as the
# value for the graph
SIZE [ a t t r i b u t e ]
...
END
END
CLASS
...
END
...
END
At least 2 CLASS blocks must be specified before charting can occur (but you already knew this if you want your
charts to convey at least some information ;) ).
Specifying Style
The styling of each value in the charts is specified by the usual MapServer syntax. Only one style per class is supported,
any other STYLE block will be silently ignored. Only a subset of the styling keywords are supported:
STYLE
SIZE [ a t t r i b u t e ]
# specify the fill color
COLOR r g b
# only for pie charts. ’a’ is the number of pixels the corresponding
# slice will be offset relative to the center of the pie. This is useful
# for emphasizing a specific value in each chart. ’b’ is required by the
# mapfile parser but is ignored.
OFFSET a b
END
This is the default type of chart that is rendered. This can also be specifically set with a PROCESSING keyword in the
layer attributes:
PROCESSING "CHART_TYPE=PIE"
For each shape in the layer’s datasource, the STYLE SIZE is used to set the relative size (value) of each pie slice, with
the angles of the slices that are automatically computed so as to form a full pie. For example:
1 LAYER
2 NAME "Ages"
3 TYPE CHART
4 CONNECTIONTYPE postgis
5 CONNECTION "blabla"
6 DATA "the_geom from demo"
7 PROCESSING "CHART_TYPE=pie"
8 PROCESSING "CHART_SIZE=30"
9 STATUS ON
10 CLASS
11 NAME "Population Age 0-19"
12 STYLE
13 SIZE [ v 1006]
In the example above, if for a given shape we have v1006=1000, v1007=600 and v1008=400 then the actual pie slices
for each class will be respectively 50%, 30% and 20% of the total pie size.
Bar graph drawing is set with a PROCESSING keyword in the layer attributes:
PROCESSING "CHART_TYPE=BAR"
For each shape in the layer’s datasource, the STYLE SIZE is used to set the relative size (value) of each bar in the
graph. By default, the vertical axis of each bar graph is scaled for the values of the corresponding shape, and will
always include the origin (=0). For example
• a shape whose STYLE SIZEs contains values {5,8,10,3} will be plotted on a graph whose vertical axis spans 0
to 10.
• a shape whose STYLE SIZEs contains values {-5,-8,-10,-3} will be plotted on a graph whose vertical axis spans
-10 to 0.
• a shape whose STYLE SIZEs contains values {-5,-8,10,3} will be plotted on a graph whose vertical axis spans
-8 to 10.
Additional PROCESSING directives are used to optionally specify the bounds of vertical axes so that the graphs for
all the shapes can be plotted with the same scale:
PROCESSING "CHART_BAR_MINVAL=val"
PROCESSING "CHART_BAR_MAXVAL=val"
Values in the datasource that are above CHART_BAR_MAXVAL or below CHART_BAR_MINVAL will be clipped
respectively to these values. If only one of these directives is included, the other will be automatically adjusted for
each shape to include at least the origin, i.e. the graphs for all the shapes will be in the same scale only if all the values
are of the same sign (positive or negative).
Table of Contents
• Flash Output
– Introduction
– Installing MapServer with Flash Support
– How to Output SWF Files from MapServer
– What is Currently Supported and Not Supported
8.4.1 Introduction
Since MapServer 4.0, MapServer can output Flash files, in SWF format (or “Shockwave Flash Format”). The following
document outlines how to enable Flash output in MapServer.
To check that your mapserv executable includes Flash support, use the “-v” command-line switch and look for “OUT-
PUT=SWF”.
$ ./mapserv -v
MapServer version 5.2.0-rc1 OUTPUT=GIF OUTPUT=PNG OUTPUT=JPEG OUTPUT=WBMP
OUTPUT=PDF OUTPUT=SWF OUTPUT=SVG SUPPORTS=PROJ SUPPORTS=AGG
SUPPORTS=FREETYPE SUPPORTS=ICONV SUPPORTS=WMS_SERVER SUPPORTS=WMS_CLIENT
SUPPORTS=WFS_SERVER SUPPORTS=WFS_CLIENT SUPPORTS=WCS_SERVER
SUPPORTS=SOS_SERVER SUPPORTS=FASTCGI SUPPORTS=THREADS
SUPPORTS=GEOS SUPPORTS=RGBA_PNG INPUT=JPEG INPUT=POSTGIS
INPUT=ORACLESPATIAL INPUT=OGR INPUT=GDAL INPUT=SHAPEFILE
The library chosen to output SWF files is the Ming library. Ming is a C library for generating SWF (“Flash”) format
movies, and it contains a set of wrappers for using the library from C++ and popular scripting languages like PHP,
Python, and Ruby.
Building on Windows
• at this point you should have a libming.lib that will be linked with MapServer
• edit the nmake.opt in your MapServer directory and uncomment the MING=-DUSE_MING_FLASH flag, and
point MING_DIR to your Ming directory.
• build MapServer as usual
Building on Unix
Use the “–with-ming” configure flag to enable MING support on Unix. “–with-ming=dir” will try to find the include
files and library in the indicated directory.
Note: compiling MapServer 4.4.2 with flash support (mingbeta version 0.3) requires
the -DMING_VERSION_03 option otherwise the make fails. This option should be included
in the configure.in after -DUSE_MING_FLASH as below:
SWF output is specified by using the OUTPUTFORMAT object. There are 2 possible output types:
1. A single movie containing the raster output for all the layers. To enable this, declare the following in the map
file:
OUTPUTFORMAT
NAME swf
MIMETYPE "application/x-shockwave-flash"
DRIVER swf
IMAGEMODE PC256
FORMATOPTION "OUTPUT_MOVIE=SINGLE"
END
2. A movie for every layer (vector movies for vector layers and raster movies for raster layers). To enable this,
declare the following in the map file:
OUTPUTFORMAT
NAME swf
MIMETYPE "application/x-shockwave-flash"
DRIVER swf
IMAGEMODE PC256
FORMATOPTION "OUTPUT_MOVIE=MULTIPLE"
END
• FORMATOPTION “FULL_RESOLUTION=FALSE”
The FULL_RESOLUTION applies only for vector layers. If set to FALSE, filtering will be applied to the vector
elements. It results in a smaller SWF file. The default value is TRUE.
• FORMATOPTION “LOAD_AUTOMATICALLY=OFF”
Setting this option to OFF will not load the SWF files for each layer. The default value is ON.
Several SWF Files will be produced from a single map file: there will be one SWF file for each layer defined in the
map file and one ‘main’ SWF file containing critical information on the map file and the layers produced.
• The ‘main’ SWF File will contain Action Script (AS) code that gives critical information on the map file and
the SWF layers produced. Basically there will be an object called mapObj containing the height, width, extent,
scale, number of layers, etc. Here is an example (in AS) of the contents of this main movie:
mapObj = new Object ();
mapObj.name = "DEMO_SWF";
mapObj.width = 400;
mapObj.height = 300;
mapObj.extent = "-2594561.353333,3467361.353333,3467361.353333,3840000.000000"; ;
mapObj.numlayers = 4;
mapObj.layers = new Array ();
function LayerObj (name, type, fullname, relativename) {
this.name = name;
this.type = type;
this.fullname = fullname;
this.relativename = relativename;
}
mapObj.layers[0] = new LayerObj ("park", "2", "c:/tmp/ms_tmp/102389536132841_layer_0.swf", "10
mapObj.layers[1] = new LayerObj ("popplace", "4", "c:/tmp/ms_tmp/102389536132841_layer_1.swf",
mapObj.layers[2] = new LayerObj ("rail", "1", "c:/tmp/ms_tmp/102389536132841_layer_2.swf", "10
mapObj.layers[3] = new LayerObj ("road", "1", "c:/tmp/ms_tmp/102389536132841_layer_3.swf", "10
This example is produced based on a mapfile with two layers defined in it. We create a layer class object
containing useful information on a layer. The parameters are:
– Name : the name found in the map file
– Type : the type of layer ( 0 = Point Layer; 1=Line; 2=Polygon; 3=Raster; 4=Annotation; 6=Circle)
– Fullname : Full name of the file with path included
– Relative name : Relative Name
For example you can use mapObj.layers[0].name to extract the name of the first layer.
Note: All map parameters from MapServer are not exported at this time. We should come up with a list of
information of what we want to output. Note that this information can be used in a Flash application to load the
SWF file, to build a legend, to build a scale bar, etc.
• SWF Files for each layer
Each layer defined in the mapfile will have an associated SWF file created. The names of these SWF files are
based on the name of the main file with an addition of ‘layer_X’ at the end of the name (where X is the layer
index).
These SWF files will contain vector and raster data as well as some Action Script depending on the layer and
some configurations in the map file. We will see these configurations in detail in the following section.
Exporting Attributes
Exporting attributes works on a layer basis (it is only available for Vector Layers). To be able to export attributes to
the SWF files, you have to define a metadata item called SWFDUMPATTRIBUTES in the layer section of the mapfile.
Here is an example :
...
LAYER
NAME park
METADATA
"DESCRIPTION""Parks"
"RESULT_FIELDS" "NAME_E YEAR_EST AREA_KMSQ"
"SWFDUMPATTRIBUTES" "NAME_E,AREA_KMSQ "
END
TYPE POLYGON
STATUS ON
DATA park
...
In the above example, the values for the attributes NAME_E and AREA_KMSQ will be exported for each element in
the layer.
The resulting SWF File will have the values of these attributes (written in Action Script). Here is an example related
to the above layer:
nAttributes= 2;
Attributes = new Array();
Attributes[0] = "NAME_E";
Attributes[1] = "AREA_KMSQ";
Element = new Array ();
Element[0] = new Array();
Element[0][0] = "Ellesmere Island National Park Reserve";
Element[0][1] = "1500";
Element[1][0] = " Aulavik National park";
Element[1][1] = "1500";
Here is what is currently implemented concerning events (events here refer to mouse events happening on an element.
The available events are MOUSEUP, MOUSEDOWN, MOUSEOVER, MOUSEOUT):
• Events are only available for layers that have defined attributes exported (using SWFDUMPATTRIBUTES).
This is like defining that a certain layer is queryable.
• When a mouse event happens on one of the elements, there is an Action Script call that is made:
_root.ElementSelecetd(LayerId, ShapeId, Event) . The Flash application who wants to receive these events
should define the function ElementSelected and use the information received to do actions like retrieving the
attribute values from the specific SWF for the specified shape and display it.
In order to have highlighting, it has to be defined when the SWF is produced (basically highlighting means that the
shape is redrawn using a different color).
As of MapServer 5.0, highlighting is available on queryable layers by using the QueryMap object in the map file to
extract the color and do a highlight when on MOUSEOVER. The current implementation will highlight all objects that
are in a layer that uses SWFDUMPATTRIBUTES, using the COLOR set in the QueryMap object in the mapfile.
Before MapServer 5.0, all objects that are in a layer that uses SWFDUMPATTRIBUTES are highlighted using a red
color.
Fonts
Ming uses a special type of font called FDB files. It does not yet support Truetype fonts. Please refer to ming
documentation on how to produce FDB files.
One mechanism would be to use the metadata for layer objects to define a raster output for vector layers. We could
use something like “SWFOUTPUT” “RASTER”. If this sounds desirable, please file an enhancement ticket with this
request, specifying the “Output-SWF” component.
1. Vector layers
• Layer Point (case MS_LAYER_POINT) : done
– msDrawMarkerSymbol
– msDrawLabel
• Layer line (case MS_LAYER_LINE) : done
– msDrawLineSymbol
– msDrawLabel
• Layer circle ( case MS_LAYER_CIRCLE) : not done (should be done easily but missing data for testing)
– omsCircleDrawLineSymbol
– omsCircleDrawShadeSymbol
• Layer annotation (case MS_LAYER_ANNOTATION): done
– omsDrawMarkerSymbol
– omsDrawLabel
• Layer Polygon (MS_SHAPE_POLYGON): done
– omsDrawShadeSymbol
– omsDrawLineSymbol
– omsDrawLabel
• Vector Low Level functions
– omsDrawMarkerSymbol
* case(MS_SYMBOL_TRUETYPE) : done
* case(MS_SYMBOL_PIXMAP) : done
* case(MS_SYMBOL_ELLIPSE) : done
* case(MS_SYMBOL_VECTOR) : done
– omsDrawLineSymbol
Contents
• HTML Legends with MapServer
– Introduction
– Sample Site Using the HTML Legend
8.5.1 Introduction
The HTML legend is an alternative to the traditional GIF legend in MapServer. The following document describes
the process for implementing an HTML legend in MapServer CGI applications (NOTE: MapServer version > 3.5 is
required).
This document assumes that you are already familiar with certain aspects of MapServer:
• Setting up MapServer mapfiles and templates.
Implementation
Key components for generating HTML legends are 1) a template parameter in the legend object, 2) a CGI [legend] tag
in the HTML file, and 3) an HTML legend template file. So that means that if the HTML page has the CGI [legend]
parameter set, and the mapfile has a LEGEND object with its TEMPLATE set to a valid HTML legend file then an
HTML legend will be returned. The following sections discuss these components.
The HTML legend is enabled by a new TEMPLATE parameter in the Legend Object of the mapfile. If TEMPLATE
is set in the Legend Object, then the HTML legend template file is read and used to generate an HTML legend which
will be inserted at the location of the [legend] tag in the main HTML template. Similar to other MapServer templates,
the HTML legend template filename MUST end with an “.html” extension.
Example 1. Sample Legend Object with the new TEMPLATE parameter
...
# LEGEND object
LEGEND
STATUS ON
KEYSIZE 18 12
# LABEL object
LABEL
TYPE BITMAP
SIZE MEDIUM
COLOR 0 0 89
END
TEMPLATE "legend.html" ### HTML template file
END
...
If TEMPLATE is not set, then the [legend] tag produces a regular image in a GIF/PNG image (the traditional be-
haviour).
The traditional CGI [legend] tag returns the URL of an image, so it is usually used inside an <IMG SRC=[legend]> tag
in the HTML file. The new HTML [legend] tag returns a block of HTML, so when converting an existing application
template from using a traditional image legend to the new HTML legend, you have to remove the IMG tag in the
main application template. Also note that if legend mode is specified in the URL, then MapServer will return a gif
containing the whole legend if no template is specified.
See the CGI Reference doc for more information on CGI parameters.
Example 2. [legend] tag in the main HTML template (with TEMPLATE set)
...
<FONT SIZE=+1><B>Legend</B></FONT><BR><HR>[legend]<HR>
...
Example 3. [legend] tag in the main HTML template (with TEMPLATE not set)
...
<FONT SIZE=+1><B>Legend</B></FONT><BR><HR><IMG SRC="[legend]"><HR>
...
The HTML legend template file is a separate file that contains 0 or 1 of each of the following tags that define blocks
of HTML to use in building the legend:
[leg_group_html] ... [/leg_group_html]
[leg_layer_html <OPTIONAL PARAMS>] ... [/leg_layer_html]
[leg_class_html <OPTIONAL PARAMS>] ... [/leg_class_html]
Note
Any text or HTML tags outside the [leg_*_html] tag pairs in the legend template file are ignored by the template
parser.
The following example shows what an HTML legend TEMPLATE file could look like:
Example 4. An HTML legend TEMPLATE file
[leg_group_html]
<tr>
<td colspan=3 bgcolor=#cccccc><b>[leg_group_name]</b></td>
</tr>
[/leg_group_html]
[leg_class_html]
<tr>
<td width=15> </td>
<td>
<img src="[leg_icon width=20 height=10]" width=20 height=10>
</td>
<td>
[leg_class_name]
</td>
</tr>
[/leg_class_html]
HEADER block
Tag [leg_header_html]...[/leg_header_html]
Description HTML block to use as the header of the legend.
FOOTER block
Tag [leg_footer_html]...[/leg_footer_html]
Description HTML block to use as the footer of the legend.
Example 5. HTML Legend File Using Header/Footer Blocks
[leg_header_html]
<p><b>my header</b></p>
[/leg_header_html]
[leg_layer_html]
...
[/leg_layer_html]
[leg_footer_html]
<p><b>my footer</b></p>
[/leg_footer_html]
GROUP block
[leg_group_html opt_flag=12]
...
[/leg_group_html]
SUPPORTED TAGS:
Tag [leg_group_name]
Description Returns the group’s name.
Tag [layer_status]
Description Returns the status of the first layer in the group.
Tag [leg_icon width=<optional_width> height=<optional_height>]
Description In the group context, the [leg_icon] tag returns the URL of a legend icon for the first class
in the first layer that’s part of this group.
Tag [metadata name=<metadata_field_to_display>]
Description Returns specified metadata value from web’s metadata.
e.g. the group block below simply displays the name of the group in the legend:
[leg_group_html]
<tr><td colspan=2><b>[leg_group_name]</b></td></tr>
[/leg_group_html]
LAYER block
[leg_layer_html opt_flag=14]
...
[/leg_layer_html]
SUPPORTED TAGS:
Tag [leg_layer_group]
Description Returns the group name of the layer. This was added to MapServer v4.8.
Tag [leg_layer_index]
Description Returns the mapfile index value of the layer, which is useful for ordering. This was added to
MapServer v4.8.
Tag [leg_layer_maxscale]
Description Returns the maximum scale set for the layer. This was added to MapServer v4.8.
Tag [leg_layer_minscale]
Description Returns the minimum scale set for the layer. This was added to MapServer v4.8.
Tag [leg_layer_name]
Description Returns the current LAYER NAME value.
Tag [leg_icon width=<optional_width> height=<optional_height>]
Description In the layer context, the [leg_icon] tag returns the URL of a legend icon for the first class in
this layer.
Tag [metadata name=<metadata_field_to_display>]
Description Returns specified metadata value from this layer’s metadata and web’s metadata.
e.g. the layer block below simply displays an icon of the layer’s class and the layer name:
[leg_layer_html]
<tr><td><img src=[leg_icon width=15 height=15]><b>[leg_layer_name]</b></td></tr>
[/leg_layer_html]
CLASS block
[leg_class_html opt_flag=14]
...
[/leg_class_html]
SUPPORTED TAGS:
Tag [leg_class_index]
Description Returns the mapfile index value of the class, which is useful for ordering and legend icon
creation. This was added to MapServer v4.8.
Tag [leg_class_maxscale]
Description Returns the maximum scale set for the class. This was added to MapServer v4.8.
Tag [leg_class_minscale]
Description Returns the minimum scale set for the class. This was added to MapServer v4.8.
Tag [leg_class_name]
Description Returns the CLASS NAME value.
Tag [leg_class_title]
Description Returns the CLASS TITLE value.
Tag [leg_layer_name]
Description Returns the parent layer name. This was added to MapServer v4.8.
Tag [leg_icon width=<optional_width> height=<optional_height>]
Description In the layer context, the [leg_icon] tag returns the URL of a legend icon for the first class in
this layer.
Tag [metadata name=<metadata_field_to_display>]
Description Returns specified metadata value from the metadata of the layer to which this class belongs
and web’s metadata.
e.g. the class block below simply displays an icon of the layer’s class and the class name:
[leg_class_html]
<tr><td><img src=[leg_icon width=15 height=15]><b>[leg_class_name]</b></td></tr>
[/leg_class_html]
CONDITIONAL text
[if] tags can be used in any of the [leg_*_html] tags above to place conditional text. The syntax is:
[if name=<field_to_check> oper=<eq|neq|isset|isnull> value=<to_compare_with_field>] ... [/if]
Note:
Nested IF’s are supported. Parameter “oper” can be “eq” for equal, “neq” for not equal, “isset” (self-explanatory), or
“isnull” (self-explanatory). The default value is equal.
Example 6. [if] tag can be used to maintain the state of a layer checkbox
[leg_layer_html order_metadata=legend_order opt_flag=5]
<tr>
<td>
The possible values that can be tested in an [if] tag depend on the context in which the [if] tag is used. At the moment,
the number of values that can be tested is limited, but new values may be added as needed.
Note that the order of the items in the following [if] contexts are listed by their order of precedence. The rule is always
that special keywords have top priority (e.g. layer_status, etc.), followed by layer-level metadata, and ending with
map-level metadata. The possible values that can be tested are as follows:
In a [leg_group_html] context:
• [if name=layer_status value=...] ... [/if]
value is the layer status of the first layer that belongs to the group in integer format: 0=OFF, 1=ON,
2=DEFAULT
• [if name=layer_visible value=...] ... [/if]
value is the visibility of the first layer in the group: 0=NOT VISIBLE, 1=VISIBLE
• [if name=group_name value=...] ... [/if]
• [if name=any_layer_metadata value=...] ... [/if]
Uses metadata value from the first layer in the mapfile that belongs to that group
• [if name=any_web_metadata value=...] ... [/if]
In a [leg_layer_html] context:
• [if name=layer_status value=...] ... [/if]
value is the layer’s status in integer format: 0=OFF, 1=ON, 2=DEFAULT
• [if name=layer_type value=...] ... [/if]
value is the layer’s type in integer format: 0=POINT, 1=LINE, 2=POLYGON, 3=RASTER, 4=AN-
NOTATION, 5=QUERY, 6=CIRCLE
• [if name=layer_name value=...] ... [/if]
value is the layer’s name in string format
• [if name=layer_group value=...] ... [/if]
value is the layer’s group name in string format
• [if name=layer_visible value=...] ... [/if]
value is the visibility of the layer: 0=NOT VISIBLE, 1=VISIBLE
• [if name=any_layer_metadata value=...] ... [/if]
• [if name=any_web_metadata value=...] ... [/if]
In a [leg_class_html] context:
• [if name=layer_status value=...] ... [/if]
value is the status of the layer in which the class is located
http://www2.dmsolutions.ca/msapps/itasca_legend/demo_init.html
This demo is based on the MapServer Itasca demo and contains several variations of HTML Legends, some of which
are listed below:
• “HTML Legend 1” - displays classes only, similar to the traditional legends:
[leg_class_html opt_flag=15]
<img src=[leg_icon]> [leg_class_name]<br>
[/leg_class_html]
• “HTML Legend 2” - displays layer titles with HREF links and classes:
[leg_layer_html order_metadata=WMS_ORDER visibility_flag=15]
<a href="[leg_layer_name]">[metadata name=WMS_TITLE]</a><BR>
[/leg_layer_html]
[leg_class_html visibility_flag=15]
<img src=[leg_icon]> [leg_class_name]<br>
[/leg_class_html]
• “HTML Legend 3” - displays layers by group, with checkboxes to turn layers on/off:
[leg_group_html]
<tr><td colspan=2><b>[leg_group_name]</b></td></tr>
[/leg_group_html]
Contents
• HTML Imagemaps
– Introduction
– Mapfile Layer Definition
– Templates
– Request URL
– Additional Notes
– More Information
8.6.1 Introduction
The shpxy method of creating imagemaps uses MapServer query functionality to build a html imagemap. Just like a
regular MapServer query, you send a query request and MapServer uses the templates to build a block of html that it
sends back to the browser. The first example shows you how to build an imagemap based on a point layer. An example
template for a polygon layer is also included.
Components
• MapServer mapfile
• query template file
• query header template
• query footer template
UNITS METERS
STATUS ON
SHAPEPATH "/web/maps/data"
IMAGECOLOR 255 255 255
WEB
IMAGEPATH "/web/maps/tmp/"
IMAGEURL "/maps/tmp/"
END
QUERYMAP
STATUS ON
STYLE NORMAL
END
LAYER
NAME "sites"
STATUS DEFAULT
TYPE point
DATA ’aqiAreas’
TEMPLATE "bodytemplate.html"
HEADER "imapheader.html"
FOOTER "imapfooter.html"
END
END
You can see that we have a mapfile with one point layer, and that it contains references to three query templates.
8.6.3 Templates
In MapServer, the query header and footers get processed only once. The main query template, ‘bodytemplate.html’
in this example, gets processed once for each record in the record set returned by the query.
Point Layers
Here is the query header, ‘imapheader.html’. It creates the opening tag for your html imagemap.
<map id="mymap" name="mymap">
Here is the query template, ‘bodytemplate.html’. It creates the body of the html imagemap.
<area shape="circle" coords="[shpxy precision=0 proj=image yf=",7" xf=","]" href="http://my.url/mypag
This template is used to create circular imagemap elements for a point layer. NAME is a fieldname in the data source,
the value for NAME for each individual record gets substituted as the template is processed. The href specifies the
URL link if the element is clicked. Title and alt will display the value when an element is moused over.
The resulting html element looks like
<area shape="circle" coords="80,103,7" href="http://my.url/mypage.cfm?region=Northern" >
This is where MapServer will substitute the image coordinates for that query record. With Precision=0, the coordinates
will be integers.
You also see shpxy template formatting options ‘xf’ and ‘yf’. ‘xf=”,” tells MapServer to place a comma after the x
coordinate. ‘yf=”,7” after the y coordinate. This is done to specify a radius of 7 pixels for the circle. More options can
be found in the Template Reference.
The query footer template simply adds the closing tag for the html imagemap
</map>
Polygon Layers
To get the imagemap, you need to send a GET or POST request to MapServer with several URL variables defined. The
below URL tells MapServer where the mapfile is located, what layer we are querying, and that we are using nquery
mode to return multiple results.
http://myurl/cgi-bin/mapserv?map=/web/maps/demoimap.map&qlayer=sites&mode=nquery&searchmap=true
If you use separate map files to generate your imagemap and your map image, make sure that the EXTENT and SIZE
specified in both mapfiles are identical. If they are not, your features will not align properly.
Table of Contents
• OGR Output
– Introduction
– OUTPUTFORMAT Declarations
– LAYER Metadata
– MAP / WEB Metadata
– Geometry Types Supported
– Attribute Field Definitions
– Return Packaging
– Test Suite Example
8.7.1 Introduction
OGR output support was added to MapServer 6.0. It provides an output driver to produce feature style output suitable
as a return result from WMS GetFeatureInfo or WFS GetFeature requests. OGR feature output depends on MapServer
being built against the GDAL/OGR library. The OGR output driver should be enabled in MapServer 6.0 or newer
when INPUT=OGR appears in the version string.
Details of OGR output formats allowed are controlled by an OUTPUTFORMAT declaration. The declarations define
the OGR format driver to be used, creation options specific to that driver, and more general instructions to MapServer
on how to package multi-file results and whether to try and build the result on disk or in memory.
Examples:
OUTPUTFORMAT
NAME "CSV"
DRIVER "OGR/CSV"
MIMETYPE "text/csv"
FORMATOPTION "LCO:GEOMETRY=AS_WKT"
FORMATOPTION "STORAGE=memory"
FORMATOPTION "FORM=simple"
FORMATOPTION "FILENAME=result.csv"
END
OUTPUTFORMAT
NAME "OGRGML"
DRIVER "OGR/GML"
FORMATOPTION "STORAGE=filesystem"
FORMATOPTION "FORM=multipart"
FORMATOPTION "FILENAME=result.gml"
END
OUTPUTFORMAT
NAME "SHAPEZIP"
DRIVER "OGR/ESRI Shapefile"
FORMATOPTION "STORAGE=memory"
FORMATOPTION "FORM=zip"
FORMATOPTION "FILENAME=result.zip"
END
The OGR format driver to be used is determined by the name appearing after “OGR/” in the DRIVER argument.
This name should match one of the formats listed as supported for the “-f” argument to ogr2ogr in the ogr2ogr usage
message.
The IMAGEMODE for OGR output is FEATURE, but this is implicit and does not need to be explicitly stated for
OGR output driver declarations.
The OGR renderer will support the following FORMATOPTION declarations:
DSCO:* Anything prefixed by DSCO: is used as a dataset creation option with the OGR driver. See the OGR web
page for the particular format driver to see layer creation options available.
LCO:* Anything prefixed by LCO: is used as a layer creation option. See the OGR web page for the particular format
driver to see layer creation options available.w
FORM=simple/zip/multipart Indicates whether the result should be a simple single file (single), a mime multipart
attachment (multipart) or a zip file (zip). “zip” is the default.
STORAGE=memory/filesystem/stream Indicates where the datasource should be stored while being written. “file”
is the default.
If “memory” then it will be created in /vsimem/ - but this is only suitable for drivers supporting VSI*L which
we can’t easily determine automatically.
If “file” then a temporary directory will be created under the IMAGEPATH were the file(s) will be written and
then read back to stream to the client.
If “stream” then the datasource will be created with a name “/vsistdout” as an attempt to write directly to stdout.
Only a few OGR drivers will work properly in this mode (ie. CSV, perhaps kml, gml).
FILENAME=name Provides a name for the datasource created, default is “result.dat”.
The OGR output driver utilizes several items from the LAYER level METADATA object. Some of these were origi-
nally intended for GML output or are primarily intended to support WFS.
wfs_getfeature_formatlist (Optional) A comma delimited list of formats supported for WFS GetFeature responses.
The OUTPUTFORMAT NAME values should be listed.
"wfs_getfeature_formatlist" "OGRGML,SHAPEZIP,CSV"
gml_include_items (Optional) A comma delimited list of items to include, or keyword “all”. You can enable full
exposure by using the keyword “all”.
"gml_include_items" "all"
You can specify a list of attributes (fields) for partial exposure, such as:
"gml_include_items" "Name,ID"
You can specify a list of attributes (fields) for partial exposure, such as:
"gml_include_items" "Name,ID"
gml_[item name]_type (Optional) Specifies the type of the attribute. Valid values are Inte-
ger|Real|Character|Date|Boolean.
gml_[item name]_width (Optional) Specifies the width of the indicated field for formats where this is significant,
such as Shapefiles.
gml_[item name]_precision (Optional) Specifies the precision of the indicated field for formats where this is signif-
icant, such as Shapefiles. Precision is the number of decimal places, and is only needed for “Real” fields.
gml_types (Optional) If this field is “auto” then some input feature drivers (ie. OGR, and native shapefiles) will
automatically populate the type, width and precision metadata for the layer based on the source file.
"gml_types" "auto"
ows/wfs_geomtype (Optional) Set the geometry type of OGR layers created from this MapServer LAYER. One of
“Point”, “LineString”, “Polygon”, “MultiPoint”, “MultiLineString”, “MultiPolygon”, “GeometryCollection”,
“Geometry”, or “None”. Most are fairly obvious, but “Geometry” can be used to represent a mix of geometry
types, and “None” is sometimes suitable for layers without geometry. Note that layers which are a mix of
polygon and multipolygon would normally have to be described as “Geometry”.
"ows_geomtype" "Polygon"
wms_feature_info_mime_type In order for WMS GetFeatureInfo to allow selection of OGR output formats, the
mime type associated with the OUTPUTFORMAT must be listed in this metadata item.
"wms_feature_info_mime_type" "text/csv"
In MapServer we have POINT, LINE and POLYGON layers which also allow for features with multiple points, lines
or polygons. However, in the OGC Simple Feature geometry model used by OGR a point and multipoint layer are
quite distinct. Likewise for a LineString and MultiLineString and Polygon an MultiPolygon layer type.
To work around the mismatches between the MapServer and OGR geometry models, there is a mechanism to specify
the geometry type to be used when exporting through OGR. This is the “wfs/ows_geomtype” metadata item on the
layer. It may be one of one of “Point”, “LineString”, “Polygon”, “MultiPoint”, “MultiLineString”, “MultiPolygon”,
“GeometryCollection”, “Geometry”, or “None”.
If this item is not specified, then “Point”, “LineString” or “Polygon” will be used depending on the TYPE of the
LAYER. In cases of mixed geometry types (ie. polygons and multipolygons) the geometry type should be set to
“Geometry” which means any geometry type.
"ows_geomtype" "Geometry"
For OGR output it is highly desirable to be able to create the output fields with the appropriate datatype, width and
precision to reflect the source feature definition.
It is possible to set the gml_[item]_type, gml_[item]_width and gml_[item]_precision metadata on the layer to provide
detailed field definitions:
METADATA
"gml_ID_type" "Integer"
"gml_ID_width" "8"
"gml_AREA_type" "Real"
"gml_AREA_width" "15"
"gml_AREA_precision" "6"
"gml_NAME_type" "Character"
"gml_NAME_width" "64"
...
However, doing this manually is tedious and error prone. For that reason some feature sources (at least OGR, Shape-
files, POSTGIS and ORACLESPATIAL) support a mechanism to automatically populate this information from the
source datastore. To accomplish this specify:
"gml_types" "auto"
If no effort is made to set type, width and precision information for attribute fields, they will all be treated as variable
length character fields when writing through OGR.
One of the challenges returning generalized feature formats is that many such formats consists of multiple files which
must be returned in the result. There are three approaches taken to this based on the FORM FORMATOPTION in the
OUTPUTFORMAT declaration.
simple In this case a single result is returned. This is suitable for format drivers that produce a single file. The
return result will have the mimetype listed in the OUTPUTFORMAT declaration. Note that if the OGR driver
actually returns multiple files, only the primary one (the one with a name matching the filename passed into the
OGR CreateDataSource call) will be returned. The return result will have a suggested filename based on the
FILENAME FORMATOPTION.
multipart In this case all the files produced are returned as a multipart mime result. In this case the MIMETYPE of
the OUTPUTFORMAT is ignored. All component files are returned with a mime type of “application/binary”
and the whole package is “multipart/mixed”.
zip In this case all the files produced are bundled into one .zip file and this zip file is returned with a mimetype of
“application/zip”. The OUTPUTFORMAT MIMETYPE is ignored.
One caveat with “zip” results is that this option is only available if the GDAL/OGR version is 1.8 or newer (or a 1.8
development later than approximately Oct 15, 2010). Earlier versions of GDAL/OGR lacked the zipping capability
needed.
The MSAutoTest test suite contains a test case for use of OGR Output from WFS. The mapfile is at:
http://svn.osgeo.org/mapserver/trunk/msautotest/wxs/wfs_ogr.map
The comments at the start of the file have a variety of sample requests that can be run against the map, as long as [MAP-
FILE] is replaced with the mapfile name. They requests should be run against mapserv sitting in the msautotest/wxs
directory.
Table of Contents
• PDF Output
– Introduction
– What is currently supported and not supported
– Implementing PDF Output
– PHP/MapScript and PDF Output
8.8.1 Introduction
PDF output support was added to MapServer 3.7. Previous versions of MapServer had support for pdf output using a
utility program (shp2pdf) to output a pdf file given a MapServer mapfile.
The difference in this new version is that the output to PDF can now be directly specified in the mapfile using the
IMAGETYPE or the OUTPUTFORMAT parameters in the mapfile. Additionally, raster layers are now supported for
pdf output.
1. Vector Layers
• Layer Point: supported
• Layer Line: supported
• Layer Polygon: supported
• Layer Circle : not supported
• Layer Annotation: supported
Note: Note: Dashed lines are supported with PDFlib version 6 or greater.
Note: Polygons filled with symbols are not supported.
2. Raster Layers
Raster layers are supported. Note that at this point all raster layers are transformed to jpeg format
before being written to the PDF file.
3. WMS Layers
Not yet supported
4. Surround components
Legend, scalebar are not supported.
5. Fonts
Standard PostScript fonts are supported. For use of other fonts (such as truetype), see the pdflib
documentation for use of UPR description files (some notes on it are here).
Note that the following instructions were developed for MapServer 3.7 and pdflib 4.0.3, but the general steps should
be similar for recent versions of both.
In order to have access to the PDF support in MapServer, you should download and build the PDF library from
http://www.pdflib.com/products/pdflib/. Please follow the instructions on the PDFLib site to build on your specific
platforms.
Here are some quick notes on how to build on windows:
• download and extract the source code from http://www.pdflib.com/products/pdflib/
• open the project PDFlib.dsw in MS Visual C++
• build the project pdflib_dll
• after a sucessful build, you should have a pdflib.lib and pdblib.dll under the pdflib directory
• copy the pdflib.dll under your system directory (ex : c:/winnt/system32)
• the pdflib.lib will be used while building mapserver with the PDF support
Windows platform
Edit the makefile.vc and uncomment the following lines (make sure that the paths are adapted to your installation):
PDF_LIB=../pdflib-4.0.3/pdflib/pdflib.lib
PDF_INC=-I../pdflib-4.0.3/pdflib
PDF=-DUSE_PDF
See the Windows Compilation document for general MapServer compile instructions.
Unix platforms
Add with-pdf to your configure command line before compiling.
See the Unix Compilation document for general MapServer compile instructions.
Mapfile definition
The IMAGETYPE parameter in the Mapfile should be set to pdf in order to output to PDF:
NAME pdf-test
STATUS ON
...
IMAGETYPE pdf
..
WEB
...
END
LAYER
...
END
END
You can also specify the output using the OUTPUTFORMAT tag (this tag was introduced in mapserver 3.7) :
OUTPUTFORMAT
NAME pdf
MIMETYPE "application/x-pdf"
DRIVER pdf
FORMATOPTION "OUTPUT_TYPE=RASTER" ##not mandatory
END
If the OUTPUT_TYPE=RASTER all the layers will be rendered as rasters. Note that when WMS layers are in-
cluded in the mapfile, this option should be set since there is a problem with transparency and wms layers. See the
OUTPUTFORMAT object in the Mapfile reference for parameter explanations.
Testing
The easiest way to test your pdf output mapfile is with the MapServer shp2img utility. Windows users can find this
utility in MS4W, as well as FWTools.
You simply pass a mapfile to the executable and a name for the output pdf, and a pdf file is generated:
shp2img -m gmap_pdf.map -o test.pdf
Possible Errors
This is related to fonts. If you remove the LABEL object from your mapfile you will see this error go away. The pdf
error is described here. Basically, until this issue is ‘fixed’, if you want to use a font other than the included standard
PostScript fonts in pdf output (such as truetype fonts), consult the PDFlib documentation.
MapServer can render to PDF directly, another option is to render to a PNG and insert that into a PDF document. This
is not the only way to create a PDF document of course. You will need to have support for PDFLib compiled into your
PHP install.
This example shows the key parts of the process, you will need to furnish parts of the script yourself (depending on
your app) and repeat the process for each map element that you want to include.
Refer to the PHP/MapScript Reference wherever necessary.
In brief, we will pass parameters required to render a map to a PHP script that will:
• create a PDF document
• render a PNG view at a suitably higher resolution
• insert the PNG
• buffer it and send it to the user
Here is an example similiar to the one given on the PHP website to create a new PDF document:
$my_pdf = pdf_new();
...
Get this stage and section 4.5 working before you try inserting MapServer elements.
Work back from the assumption that you will need no more than 300 dpi on your page for your map to look presentable.
For an A4 map, I am using 150 dpi for an 8’ x 8’ main map, which is 1200 x 1200 pixels.
$map->set(width,1200);
$map->set(height,1200);
Of course, our map will not be very useful unless it is zoomed in to the extent our user requested, and the layers they
selected are switched on. Maintain arrays in your application that record:
- The current extent (say $ext[])
- Layer status (say $layer[])
Open your map file and pass these back through to set the map file into the state the user is expecting, something like:
$map->setextent($ext[0], $ext[1], $ext[2], $ext[3]);
while($layer[]) {
$layer=$map->getLayer($n);
if($layer[$n]==1) {
$layer->set(status,1);
} else {
$layer->set(status,0);
}
}
Use the same method for all your map elements, such as drawReferenceMap?(), drawScaleBar?() and drawLegend().
This is really easy, use the pdf_open_image_file() function to import the map elements into your PDF document:
$element = pdf_open_image_file($my_pdf, "png", "$webroot/$url");
pdf_place_image($my_pdf, $element, $xpos, $ypos);
pdf_close_image($my_pdf, $element);
Assuming we have been creating the document $my_pdf, when we are done, we merely buffer it and send it to the
user using echo():
<?php
....
pdf_close($my_pdf);
$data = pdf_get_buffer($my_pdf);
header(’Content-type: application/pdf’);
header(’Content-disposition: inline; filename=my_pdf.pdf’);
header(’Content-length: ’ . strlen($data) );
echo $data;
?>
Gotcha: remember that you cannot send headers if you have at any stage outputed text to the browser.
Rendering everything as PNG can look ugly, so I step through the key and extract labels so I can render them using
PDF’s text functions.
This can be done for other map element, such as map titles, layer descriptions, or anything else that can be read from
the mapfile.
8.9 SVG
Table of Contents
• SVG
– Introduction
– Feature Types and SVG Support Status
– Testing your SVG Output
– goSVG
8.9.1 Introduction
SVG (or Scalable Vector Graphics) is a standardized XML language for describing 2D graphics via vector graphics,
text and raster graphics. As of version 4.5, MapServer can output SVG v1.1 maps. The following documentation is
based on the World Wide Web Consortium’s (W3C) Scalable Vector Graphics (SVG) 1.1 Specification.
This document assumes that you are already familiar with certain aspects of MapServer:
• MapServer application development and setting up map files.
Annotation Layers
Annotation layers are supported (see the Text Features section below for details).
Circle Layers
Line Layers
The following items describe how line layers are handled by MapServer for SVG output:
• Lines are converted to SVG polyline elements.
• The STYLE object’s WIDTH parameter is used for SYMBOL 0 for line thickness.
• The STYLE object’s SIZE parameter is used for other symbols for line thickness.
• All lines are drawn without symbols - only line thickness changes.
• If a style uses a symbol and this symbol has a dashed style, it will be transformed into an SVG stroke-dasharray
element.
Point Layers
The following items describe how point layers are handled by MapServer for SVG output:
• VECTOR, ELLIPSE, and TRUETYPE symbols are supported.
• PIXMAP symbols are not currently supported.
• Labels attached with the symbols are supported (see the Text Features section below for details).
Polygon Layers
The following items describe how polygon layers are handled by MapServer for SVG output:
• Polygons are converted to SVG polygon elements.
• The STYLE’s COLOR is used for the fill.
• The STYLE’s OUTLINECOLOR is used for the stroke.
• SVG patterns are not currently supported.
Raster Layers
The following items describe how raster layers are handled by MapServer for SVG output:
• Temporary image is created through the GD library, and GD functions are used to draw the layer.
• You must have at least PNG or JPEG support compiled in MapServer.
• You must have the WEB object’s IMAGEPATH and IMAGEURL set properly in your mapfile.
Text Features
The following items describe how text features are handled by MapServer for SVG output:
• Text is converted to SVG text element.
• Only TRUETYPE fonts are supported.
• Supports labels with ENCODING (output as UTF-8 hexadecimal values).
• The FONT name used in MapServer is parsed to form the SVG font-family, font-style, and font-weight.
WMS Layers
Note:
If FORMATOPTION “COMPRESSED_OUTPUT=TRUE” is set MapServer will produce a compressed SVG
file (svgz). By default this option is FALSE. Note that to be able to create compressed output, MapServer must
be built with the compile flag USE_ZLIB.
If FORMATOPTION “FULL_RESOLUTION=TRUE” is set MapServer will not eliminate duplicate points and
collinear lines when outputting SVG. By default this option is set to FALSE.
• The easiest way to test your SVG mapfile is to use MapServer CGI. For example, you might enter the following
URL in a browser:
http://127.0.0.1/cgi-bin/mapserv.exe?map=my/path/to/my-svg.map&mode=map&layers=layer1 layer2
• You can also use PHP/MapScript to test your SVG mapfile. Your php file might look like the following:
<?php
dl("php_mapscript_45.dll");
$oMap = ms_newmapObj("my/path/to/my-svg.map");
$img = $oMap->draw();
header("Content-type: image/svg+xml");
$url = $img->saveImage("");
?>
An SVG file should be created in your IMAGEPATH directory. If you open the SVG file in a text editor you can see
that it is an XML file. Below is a sample SVG file of a point layer with labels:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-flat.dtd
<svg version="1.1" width="400" height="300" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://ww
You can now view the SVG file in a supported browser (see the official list of SVG implementations for possible SVG
viewers). The Adobe Viewer plugin is very popular.
8.9.4 goSVG
goSVG is now supported as a vector output format in MapServer 4.5 (and later).
Definition
Requirements
...
END
END
To be able to output a valid goSVG file, you must define an OUTPUTFORMAT object in the mapfile and set the
IMAGETYPE to svg. Here is an example:
MAP
...
IMAGETYPE svg
...
OUTPUTFORMAT
NAME svg
MIMETYPE "image/svg+xml"
DRIVER svg
FORMATOPTION "GOSVG=TRUE"
FORMATOPTION "GOSVG_ZoomInTH=20"
FORMATOPTION "GOSVG_ZoomOutTH=40"
FORMATOPTION "GOSVG_ScrollTH=60"
END
...
WEB
IMAGEPATH "/tmp/ms_tmp/"
IMAGEURL "/ms_tmp/"
END
...
PROJECTION
"init=epsg:42304"
END
...
LAYER
...
END
END
Refer to the section Testing your SVG Output to generate and test your goSVG output. goSVG can be read by regular
SVG viewers (they will just ignore the goSVG headers).
Table of Contents
• Tile Mode
– Introduction
– Configuration
– Utilization
8.10.1 Introduction
MapServer can feed tile-based map clients directly using the CGI “tile mode”. Tile-based map clients work by dividing
the map of the world up into a discrete number of zoom levels, each partitioned into a number of identically sized
“tiles”. Instead of accessing a map by requesting a bounding box, a tile client builds a map by accessing individual
tiles.
8.10.2 Configuration
Tile requests are handled by the ‘mapserv’ CGI program. In order to return tiles in the correct projection, MapServer
must be built with the –use-proj option turned on. You can check if your version of ‘mapserv’ has projection support
by running it with the ‘-v’ option and looking for ‘SUPPORTS=PROJ’.
Example 1. On Unix:
$ ./mapserv -v
MapServer version 4.6.1 OUTPUT=GIF OUTPUT=PNG OUTPUT=JPEG OUTPUT=WBMP OUTPUT=PDF
OUTPUT=SWF OUTPUT=SVG SUPPORTS=PROJ SUPPORTS=FREETYPE SUPPORTS=WMS_SERVER
SUPPORTS=WMS_CLIENT SUPPORTS=WFS_SERVER SUPPORTS=WFS_CLIENT SUPPORTS=WCS_SERVER
INPUT=JPEG INPUT=POSTGIS INPUT=OGR INPUT=GDAL INPUT=SHAPEFILE DEBUG=MSDEBUG
Example 2. On Windows:
C:\apache\cgi-bin> mapserv -v
MapServer version 4.6.1 OUTPUT=GIF OUTPUT=PNG OUTPUT=JPEG OUTPUT=WBMP OUTPUT=PDF
OUTPUT=SWF OUTPUT=SVG SUPPORTS=PROJ SUPPORTS=FREETYPE SUPPORTS=WMS_SERVER
SUPPORTS=WMS_CLIENT SUPPORTS=WFS_SERVER SUPPORTS=WFS_CLIENT SUPPORTS=WCS_SERVER
INPUT=JPEG INPUT=POSTGIS INPUT=OGR INPUT=GDAL INPUT=SHAPEFILE DEBUG=MSDEBUG
MapServer requires that each LAYER in your map file have a valid PROJECTION block to support reprojection.
Because the tile mode uses reprojection, you will have to ensure each LAYER has a valid PROJECTION block.
Configuration checklist:
• MapServer compiled with PROJ support
• Map file with a PROJECTION defined for every LAYER
As of MapServer 6.0, there are two extra parameters available for configuring tile mode.
• tile_map_edge_buffer renders the tile into a buffered rendering frame, then clips out the final tile. This will
reduce edge effects when large symbols or wide lines are drawn. Recommended value: the size of the largest
symbol or line width in your map file.
• tile_metatile_level renders the into into a fixed metatile, then clips out the final tile. This will reduce label
repetition, at the expense of much higher rendering cost. Recommended value: 1 if you are doing labelling of
large features in your layer. 0 otherwise.
If you use both tile_map_edge_buffer and tile_metatile_level at the same time, the buffer will be applied at the meta-tile
level.
8.10.3 Utilization
The MapServer tile support adds three new directives to the CGI interface:
• mode=tile tells the server to generate tiles based on the other tile mode parameters
• tilemode=gmap tells the server use the Google Maps tile scheme for the tiles
• tile=x+y+z tells the server what tile you want to retrieve, using the Google Maps tile addressing system
• tilemode=ve tells the server use the Virtual Earth tile naming scheme for the tiles
• tile=10231 tells the server what tile you want to retrieve, using the Virtual Earth tile addressing system
Spherical Mercator (also called “web mercator” by some) is a world projection. All the major tile-based map interfaces
(Google Maps, Microsoft Virtual Earth, Yahoo Maps, OpenLayers) use the spherical mercator system to address tiles.
A spherical mercator set of tiles has the following properties:
• The map has been reprojected to mercator using a spherical mercator algorithm
• There is one tile in the top zoom level, zoom level zero
• Each successive zoom level (z) has 2^z tiles along each axis
• Tiles are 256x256 in size
Google Maps and Virtual Earth both use spherical mercator as their underlying tile projection, but use different formats
to address the individual tiles.
Google Maps uses an “x”, “y”, “zoom” format. The zoom indicates which level to pull tiles from, and the “x” and “y”
indicate while tile in that zoom level to pull.
Virtual Earth uses a single string to address each tile. The top zoom level in Virtual Earth has four tiles (equivalent
to Google’s zoom level 1). The top left tile in the Virtual Earth top zoom level is addessed as “0”, top right as “1”,
bottom left as “2” and bottom right as “3”. Each tile the next level is addressed by first referencing the top level tile
that contains it, then its address relative to that tile. So the top left tile in the second zoom level is “00” and the bottom
right one is “33”. See the Virtual Earth site for more details: http://msdn.microsoft.com/en-us/library/bb545006.aspx
The Google Maps API includes support for using alternative tile sets as overlays, or as alternate base maps. Here is an
example of an GTileLayerOverlay
1 <!DOCTYPE html
2 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 <html xmlns="http://www.w3.org/1999/xhtml">
5 <head>
6 <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
12 function load() {
13 if (GBrowserIsCompatible()) {
14 var urlTemplate = ’http://localhost/cgi-bin/mapserv?’;
15 urlTemplate += ’map=/var/map.map&’;
16 urlTemplate += ’layers=layer1 layer2&’;
17 urlTemplate += ’mode=tile&’;
18 urlTemplate += ’tilemode=gmap&’;
19 urlTemplate += ’tile={X}+{Y}+{Z}’;
20 var myLayer = new GTileLayer(null,0,18,{
21 tileUrlTemplate:urlTemplate,
22 isPng:true,
23 opacity:1.0 });
24 var map = new GMap2(document.getElementById("map"));
25 map.addControl(new GLargeMapControl());
26 map.addControl(new GMapTypeControl());
27 map.setCenter(new GLatLng(35.35, -80.55), 15);
28 map.addOverlay(new GTileLayerOverlay(myLayer));
29 }
30 }
31
32 </script>
33 </head>
34 <body onload="load()" onunload="GUnload()">
35 <div id="map" style="width: 500px; height: 500px"></div>
36 </body>
37 </html>
Note the format of the tileUrlTemplate: a valid URL, with {X}, {Y} and {Z} substitution tokens that Google Maps
will replace with the tile coordinates and zoom level on the fly to retrieve tiles from your server.
You can also use a MapServer tile layer as an alternate base map:
1 <!DOCTYPE html
2 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 <html xmlns="http://www.w3.org/1999/xhtml">
5 <head>
6 <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
7 <title>Google/MapServer Tile Example</title>
8 <script src="http://maps.google.com/maps?file=api&v=2&key=[YOUR KEY HERE]"
9 type="text/javascript"></script>
10 <script type="text/javascript">
11
12 function load() {
13 if (GBrowserIsCompatible()) {
14 var urlTemplate = ’http://localhost/cgi-bin/mapserv?’;
15 urlTemplate += ’map=/var/map.map&’;
16 urlTemplate += ’layers=layer1 layer2&’;
17 urlTemplate += ’mode=tile&’;
18 urlTemplate += ’tilemode=gmap&’;
19 urlTemplate += ’tile={X}+{Y}+{Z}’;
20 var myLayer = new GTileLayer(null,0,18,{
21 tileUrlTemplate:urlTemplate,
22 isPng:true,
23 opacity:0.3 });
24 var map = new GMap2(document.getElementById("map"));
25 map.addControl(new GLargeMapControl());
26 map.addControl(new GMapTypeControl());
27 map.setCenter(new GLatLng(35.35, -80.55), 15);
28 var myMapType = new GMapType([myLayer], new GMercatorProjection(18), ’MapServer’);
29 map.addMapType(myMapType);
30 }
31 }
32
33 </script>
34 </head>
35 <body onload="load()" onunload="GUnload()">
36 <div id="map" style="width: 500px; height: 500px"></div>
37 </body>
38 </html>
The only change from the previous example is that we don’t create a GTileLayerOverlay, we create a GMapType, and
use addMapType(), instead of addOverlay().
The Virtual Earth API also includes support for using alternative tile sets as overlays, or as alternate base maps. Here
is an example:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-stri
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
5 <title>Virtual Earth Example</title>
6 <script type="text/javascript" src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1"><
7 <script type="text/javascript">
8
11 function OnLoadMap () {
12 map = new VEMap("myMap");
13 map.LoadMap();
14
27 </script>
28 </head>
29 <body onload="OnLoadMap();">
30 <div id="myMap" style="position:relative; width:500px; height:500px;"></div>
31 </body>
32 </html>
Table of Contents
• Template-Driven Output
– Introduction
– OUTPUTFORMAT Declarations
– Template Substitution Tags
– Examples
8.11.1 Introduction
RFC 36 added support for defining template-driven OUTPUTFORMATs for use with feature queries, including WMS
GetFeatureInfo and WFS GetFeature. This allows for custom text-oriented output such as GeoJSON, KML, or XML.
The templates are essentially the same as with the standard MapServer query Templating, however there are some
additional tags to allow for template definition in a single file instead of the standard header/template/footer.
Note: There are other, simpler, ways to output some of these formats using MapServer. However, template-driven
output provides maximal flexibility and customization of the output, at the cost of additional complexity and configu-
ration.
Details of template-driven output formats are controlled by an OUTPUTFORMAT declaration. The declarations define
the template file to be used, as well as other standard OUTPUTFORMAT options.
Examples:
OUTPUTFORMAT
NAME "kayml"
DRIVER "TEMPLATE"
MIMETYPE "application/vnd.google-earth.kml+xml"
FORMATOPTION "FILE=myTemplate.kml"
FORMATOPTION "ATTACHMENT=queryResults.kml"
END
OUTPUTFORMAT
NAME "geojson"
DRIVER "TEMPLATE"
FORMATOPTION "FILE=myTemplate.json"
END
OUTPUTFORMAT
NAME "customxml"
DRIVER "TEMPLATE"
FORMATOPTION "FILE=myTemplate.xml"
END
The template file to be used is determined by the “FILE=...” FORMATOPTION. The template filename is relative to
the mapfile’s path. As is standard with MapServer template files, the file must containt the magic string ‘mapserver
template’ in the first line of the file, usually within a comment, but this line is not output to the client.
Note that both the MIMETYPE and FORMATOPTION “ATTACHMENT=...” parameters are very useful for control-
ling how a web browser handles the output file.
These tags only work in query result templates, and their purpose is primarily to simplify the templating to a single
file for custom ouput formats.
[include src=”otherTemplate.txt”] Includes another template file; the path to the template file is relative to the map-
file path.
[resultset name=layername]...[/resultset] Defines the location of the results for a given layer.
[feature]...[/feature] Defines the loop around the features returned for a given layer.
Optional arguments:
• limit= specifies the maximum number of features to output for this layer.
• trimlast= specifies a string to be trimmed off of the end of the final feature that is output. This is intended
to allow for trailing record delimiters to be removed. See the examples below.
[join name=join1]...[/join] defines the loop around the features join from another layer.
8.11.4 Examples
This example shows how to emulate the old 3-file system using the new system, to compare the usage:
<!-- mapserver template -->
[include src="templates/header.html"]
[resultset name=lakes]
... old layer HEADER stuff goes here, if a layer has no results this block disappears...
[feature]
...repeat this block for each feature in the result set...
[join name=join1]
...repeat this block for each joined row...
[/join]
[/feature]
...old layer FOOTER stuff goes here...
[/resultset]
[resulset name=streams]
... old layer HEADER stuff goes here, if a layer has no results this block disappears...
[feature]
...repeat this block for each feature in the result set...
[/feature]
...old layer FOOTER stuff goes here...
[/resultset]
[include src="templates/footer.html"]
<gml:description>This is a GML document which provides locations of all MapServer User Meeting that
<gml:name>MapServer User Meetings</gml:name>
<gml:boundedBy>
<gml:Envelope>
<gml:coordinates>-93.093055556,44.944444444 -75.7,45.4166667</gml:coordinates>
</gml:Envelope>
</gml:boundedBy>
[feature]
<gml:featureMember>
<Meeting>
<gml:description>[desc]</gml:description>
<gml:name>[name]</gml:name>
<gml:location>
<gml:Point srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">
<gml:pos>[x] [y]</gml:pos>
</gml:Point>
</gml:location>
<year>[year]</year>
<venue>[venue]</venue>
<website>[url]</website>
</Meeting>
</gml:featureMember>
[/feature]
<dateCreated>2007-08-13T17:17:32Z</dateCreated>
</MapServerUserMeetings>
[resultset]
A GeoJSON example:
// mapserver template
[resultset layer=mums]
{
"type": "FeatureCollection",
"features": [
[feature trimlast=’,’]
{
"type": "Feature",
"id": "[id]",
"geometry": {
"type": "PointLineString",
"coordinates": [
{
"type": "Point",
"coordinates": [[x], [y]]
}
]
},
"properties": {
"description": "[description]",
"venue": "[venue]",
"year": "[year]"
}
},
[/feature]
]
}
[/resultset]
A more complicated KML example. Note the use of [shpxy] to support multipolygons with holes, and also that a point
<Pair>
<key>highlight</key>
<styleUrl>#parks_highlight</styleUrl>
</Pair>
</StyleMap>
[resultset layer=parks]
<Folder>
<name>Parks</name>
[feature trimlast=’,’ limit=1]
<Placemark>
<name>[NAME]</name>
<Snippet/>
<description>
<![CDATA[
<p>Year Established: [YEAR_ESTABLISHED]</p>
<p>Area: [AREA_KILOMETERS_SQUARED] sq km</p>
]]>
</description>
<styleUrl>#parks_map</styleUrl>
<ExtendedData>
<Data name="Year Established">[YEAR_ESTABLISHED]</Data>
<Data name="Area">[AREA_KILOMETERS_SQUARED]</Data>
</ExtendedData>
<MultiGeometry>
<Point>
<coordinates>[shplabel proj=epsg:4326 precision=10],0</coordinates>
</Point>
[shpxy ph="<Polygon><tessellate>1</tessellate>" pf="</Polygon>" xf="," xh=" " yh=" " yf=",0 " orh="<o
</MultiGeometry>
</Placemark>
[/feature]
</Folder>
[/resultset]
</Document>
</kml>
8.12.1 Introduction
This purpose of this docuement is to describethe KML/KMZ output support in MapServer 6.0.
The main goal of the KML driver is to generate KML output used mainly by Google Earth application.
Kml support is provided by using a kml or kmz image type in the map file. Output can then be generated using
MapServer cgi (example mode=map) or through a WMS request.
The default name of the output format is kml or kmz, and this name can be used to set the imagetype parameter in the
map file.
The format can also be defined in the map file:
OUTPUTFORMAT
NAME kml
DRIVER "KML"
MIMETYPE "application/vnd.google-earth.kml+xml"
IMAGEMODE RGB
EXTENSION "kml"
FORMATOPTION ’ATTACHMENT=gmap75.kml’ #name of kml file returned
FORMATOPTION "maxfeaturestodraw=100"
END
OUTPUTFORMAT
NAME kmz
DRIVER "KMZ"
MIMETYPE "application/vnd.google-earth.kmz"
IMAGEMODE RGB
EXTENSION "kmz"
FORMATOPTION ’ATTACHMENT=gmap75.kmz’ #name of kmz file returned
END
8.12.4 Build
The number of vector features drawn by default is set to 1000 per layer. To control the number of features, users can
set:
• layer level metadata that only applies to the layer: “maxfeaturestodraw” “100”
• map level metada that applies to all layers: “maxfeaturestodraw” “100”
• output format option that applies to all layers: FORMATOPTION “maxfeaturestodraw=100”
8.12.6 Map
In terms for Kml object, the MapServer KML output will produce a <Document> element to include all the layers that
are part of the MapServer map file. Features supported for the Document are:
8.12.7 Layers
Each layer of the MapServer map file will be inside a Kml <Folder> element. Supported Folder elements are:
Folder element Sup- MapServer equivalence/Notes
ported
name Yes Name of the layer. If not available the name will be Layer concatenated
with the layer’s index (Layer1)
visibility Yes Always set to 1
open No Default is 0
atom:authoratom:linkaddressAddressDetailsphoneNumberSnippet
No
description No Could be supported using ows_description
AbstarctView No
TimePrimitive No
styleUrl Yes The user can use the kml_folder_display layer or map level metedata to
choose a setting. Possible values are ‘check’ (default), ‘radioFolder’,
‘checkOffOnly’, ‘checkHideChildren’.
RegionMetadataExtended- No
Data
Each element in the Layer will be inside a Kml <Placemark> element. As described in the Kml reference : « A
Placemark is a Feature with associated Geometry. In Google Earth, a Placemark appears as a list item in the Places
panel. A Placemark with a Point has an icon associated with it that marks a point on the Earth in the 3D viewer. (In
the Google Earth 3D viewer, a Point Placemark is the only object you can click or roll over. Other Geometry objects
do not have an icon in the 3D viewer. To give the user something to click in the 3D viewer, you would need to create
a MultiGeometry object that contains both a Point and the other Geometry object.) »
For Polygon and Line layers, when a feature is associated with a label, a MultiGeometry element containing a point
geometry and the geometry of the feature is created. The point feature will be located in the middle of the polygon or
line
<Folder>
<name>park</name>
<visibility>1</visibility>
<styleUrl>#LayerFolder_check</styleUrl>
<Placemark>
<name>Ellesmere Island National Park Reserve</name>
<styleUrl>#style_line_ff787878_w4.0_polygon_ff00ffc8_label_ff0000ff</styleUrl>
<MultiGeometry>
<Polygon>
<outerBoundaryIs>
<LinearRing>
<coordinates>
...
<Point>
<coordinates>
-70.86810858,82.12291871
</coordinates>
</Point>
</MultiGeometry>
</Placemark>
</Folder>
Point Layers
Line Layers
Polygon Layers
Annotation Layers
Not supported.
Raster Layers
8.12.8 Styling
As described in Section 4, all different styles from the layers will be stored at the Document level and referenced from
the folders using a styleUrl.
Point Layers
Point layers will be styled using the IconStyle styling element of kml. An image representing the symbol will be
created and referenced from the IconStyle object. If a label is attached to the point, a LabelStyle element will also be
used. The LabelStyle will have the color parameter set.
<Style id="style_label_ff0000ff_symbol_star_13.0_ff000000">
<IconStyle>
<Icon>
<href>>http://localhost/ms_tmp/4beab862_19bc_0.png</href>
</Icon>
</IconStyle>
<LabelStyle>
<color>ff0000ff</color>
</LabelStyle>
</Style>
Line Layers
Line layers will be styled using the LineStyle styling element of kml. Color and width parameters of the LineStyle
will be used. If a label is attached to the layer, a LabelStyle element will also be used.
Polygon Layers
Polygon layers will be styled using the PolyStyle styling element of kml. Color parameter of the PolyStyle will be
used. If an outline is defined in the map file, an addition LineStyle will be used. If a label is attached to the layer, a
LabelStyle element will also be used.
8.12.9 Attributes
The map level projection should be set to epsg:4326. If not set, the driver will automatically set it. Layers are expected
to have projection block if their projection is different from epsg:4326.
• When the projection of the map file is not set or is different from a a lat/lon projection, the driver automatically
sets the projection to espg:4326. If the map is is debug mode, the following message is sent: « ”KmlRen-
derer::checkProjection: Mapfile projection set to epsg:4326 »
• If imagepath and imageurl are not set in the web object, the following message is sent in debug mode: « Kml-
Renderer::startNewLayer: imagepath and imageurl should be set in the web object »
Interoperability is increasingly becoming a focus point for organizations that distribute and share data over the In-
ternet. The Open Geospatial Consortium (OGC) focuses on the development of publicly available geospatial web
standards. MapServer supports numerous OGC standards, allowing users to publish and consume data and services in
an application neutral implementation manner.
Table of Contents
• WMS Server
– Introduction
– Setting Up a WMS Server Using MapServer
– WMS 1.3.0 Support
– Reference Section
– FAQ / Common Problems
9.1.1 Introduction
A WMS (or Web Map Server) allows for use of data from several different servers, and enables for the creation of a
network of Map Servers from which clients can build customized maps. The following documentation is based on the
Open Geospatial Consortium’s (OGC) Web Map Server Interfaces Implementation Specification v1.1.1.
MapServer v3.5 or more recent is required to implement WMS features. At the time this document was written,
MapServer supports the following WMS versions: 1.0.0, 1.0.7, 1.1.0 (a.k.a. 1.0.8), 1.1.1 and 1.3.0
This document assumes that you are already familiar with certain aspects of MapServer:
• MapServer application development and setting up .map files.
395
MapServer Documentation, Release 6.0
• Familiarity with the WMS spec would be an asset. A link to the WMS specification document is included in the
“WMS-Related Information” section below.
WMS servers interact with their clients via the HTTP protocol. In most cases, a WMS server is a CGI program. This
is also the case with MapServer.
The WMS specification defines a number of request types, and for each of them a set of query parameters and associ-
ated behaviors. A WMS-compliant server MUST be able to handle at least the following 2 types of WMS requests:
1. GetCapabilities: return an XML document with metadata of the Web Map Server’s information
2. GetMap: return an image of a map according to the user’s needs.
And support for the following types is optional:
1. GetFeatureInfo: return info about feature(s) at a query (mouse click) location. MapServer supports 3 types of
responses to this request:
• text/plain output with attribute info.
• text/html output using MapServer query templates specified in the CLASS template parameter. The
MIME type returned by the Class templates defaults to text/html and can be controlled using the meta-
data “wms_feature_info_mime_type”.
• application/vnd.ogc.gml, GML.1 or GML for GML features.
2. DescribeLayer: return an XML description of one or more map layers. To execute this:
• for vector layers: to have a valid return the user needs to setup wfs_onlineresource (or ows_onlineresource)
metadata either at the map level or at the layer level (the layer level metadata is the one which is used if
both are defined)
• for raster layers: the metadata is wcs_onlineresource with the same logic as above.
3. GetLegendGraphic: returns a legend image (icon) for the requested layer, with label(s). More information on
this request can be found in the GetLegendGraphic section later in this doc.
With respect to MapServer specifically, it is the “mapserv” CGI program that knows how to handle WMS requests.
So setting up a WMS server with MapServer involves installing the mapserv CGI program and a setting up a mapfile
with appropriate metadata in it. This is covered in the rest of this document.
WMS requests are handled by the mapserv CGI program. Not all versions of the mapserv program do include WMS
support (it is included by default when you compile together with the PROJ library), so the first step is to check that
your mapserv executable includes WMS support. One way to verify this is to use the “-v” command-line switch and
look for “SUPPORTS=WMS_SERVER”.
(Unix users should refer to the Compiling on Unix document for any compiling instructions, and Windows users might
want to use MS4W, which comes ready with WMS/WFS support)
Example 1. On Unix:
$ ./mapserv -v
MapServer version 4.6.1 OUTPUT=GIF OUTPUT=PNG OUTPUT=JPEG OUTPUT=WBMP OUTPUT=PDF
OUTPUT=SWF OUTPUT=SVG SUPPORTS=PROJ SUPPORTS=FREETYPE SUPPORTS=WMS_SERVER
SUPPORTS=WMS_CLIENT SUPPORTS=WFS_SERVER SUPPORTS=WFS_CLIENT SUPPORTS=WCS_SERVER
INPUT=JPEG INPUT=POSTGIS INPUT=OGR INPUT=GDAL INPUT=SHAPEFILE DEBUG=MSDEBUG
Example 2. On Windows:
C:\apache\cgi-bin> mapserv -v
MapServer version 4.6.1 OUTPUT=GIF OUTPUT=PNG OUTPUT=JPEG OUTPUT=WBMP OUTPUT=PDF
OUTPUT=SWF OUTPUT=SVG SUPPORTS=PROJ SUPPORTS=FREETYPE SUPPORTS=WMS_SERVER
SUPPORTS=WMS_CLIENT SUPPORTS=WFS_SERVER SUPPORTS=WFS_CLIENT SUPPORTS=WCS_SERVER
INPUT=JPEG INPUT=POSTGIS INPUT=OGR INPUT=GDAL INPUT=SHAPEFILE DEBUG=MSDEBUG
Each instance of WMS server that you setup needs to have its own mapfile. It is just a regular MapServer mapfile in
which some parameters and some metadata entries are mandatory. Most of the metadata is required in order to produce
a valid GetCapabilites output.
Here is the list of parameters and metadata items that usually optional with MapServer, but are required (or strongly
recommended) for a WMS configuration:
At the MAP level:
• Map NAME
• Map PROJECTION
• Map Metadata (in the WEB Object):
– wms_title
– wms_onlineresource
– wms_srs (unless PROJECTION object is defined using “init=epsg:...”)
And for each LAYER:
• Layer NAME
• Layer PROJECTION
• Layer METADATA
– wms_title
– wms_srs (optional since the layers inherit the map’s SRS value)
• Layer STATUS
– Layers set to STATUS DEFAULT will always be sent to the client.
– Layers set to STATUS ON or STATUS OFF can be requested by the client.
• Layer TEMPLATE (required for GetFeatureInfo requests)
• Layer DUMP TRUE (only required for GetFeatureInfo GML requests)
Let’s go through each of these paramters in more detail:
• Map Name and wms_title:
WMS Capabilities requires a Name and a Title tag for every layer. The Map’s NAME and wms_title metadata
will be used to set the root layer’s name and title in the GetCapabilities XML output. The root layer in the WMS
context corresponds to the whole mapfile.
• Layer Name and wms_title metadata:
Every individual layer needs its own unique name and title. Layer names are also used in GetMap and GetFea-
tureInfo requests to refer to layers that should be included in the map output and in the query. Layer names must
start with a letter when setting up a WMS server (layer names should not start with a digit or have spaces in
them).
• Map PROJECTION and wms_srs metadata:
WMS servers have to advertise the projection in which they are able to serve data using EPSG projection codes
(see http://www.epsg.org/ for more background on EPSG codes). Recent versions of the PROJ4 library come
with a table of EPSG initialization codes and allow users to define a projection like this:
PROJECTION
"init=epsg:4269"
END
(Note that “epsg” has to be in lowercase when used in the PROJ4 ‘init’ directive.)
If the MAP PROJECTION block is provided in the format “init=epsg:xxxx” then MapServer will also use this
information to generate a <BoundingBox> tag for the top-level layer in the WMS capabilities document. Note
that the BoundingBox is an optional element of WMS capabilities, but it is good practice to allow MapServer to
include it when possible.
The above is sufficient for MapServer to recognize the EPSG code and include it in SRS tags in the capabilities
output (wms_srs metadata is not required in this case). However, it is often impossible to find an EPSG code
to match the projection of your data. In those cases, the “wms_srs” metadata is used to list one or more EPSG
codes that the data can be served in, and the PROJECTION object contains the real PROJ4 definition of the
data’s projection.
Here is an example of a server whose data is in an Lambert Conformal Conic projection (42304). It’s capabilities
output will advertize EPSG:4269 and EPSG:4326 projections (lat/lon), but the PROJECTION object is set to
the real projection that the data is in:
NAME "DEMO"
...
WEB
...
METADATA
"wms_title" "WMS Demo Server"
"wms_onlineresource" "http://my.host.com/cgi-bin/mapserv?map=wms.map&"
"wms_srs" "EPSG:4269 EPSG:4326"
END
END
PROJECTION
"init=epsg:42304"
END
...
END
In addition to EPSG:xxxx projections, a WMS server can advertize projections in the AUTO:xxxx namespace.
AUTO projections 42001 to 42005 are internally supported by MapServer. However, AUTO projections are
useful only with smart WMS clients, since the client needs to define the projection parameters in the WMS
requests to the server. For more information see Annex E of the WMS 1.1.1 specification and section 6.5.5.2 of
the same document. See also the FAQ on AUTO projections at the end of this document.
• Layer PROJECTION and wms_srs metadata:
By default layers inherit the SRS of their parent layer (the map’s PROJECTION in the MapServer case). For
this reason it is not necessary (but still strongly recommended) to provide PROJECTION and wms_srs for every
layer. If a layer PROJECTION is not provided then the top-level map projecion will be assumed.
Layer PROJECTION and wms_srs metadata are defined exactly the same way as the map’s PROJECTION and
wms_srs metadata.
For vector layers, if a PROJECTION block is provided in the format “init=epsg:xxxx” then MapServer will also
use this information to generate a <BoundingBox> tag for this layer in the WMS capabilities document. Note
that the BoundingBox is an optional element of WMS capabilities, but it is good practice to allow MapServer to
include it when possible.
• “wms_onlineresource” metadata:
The wms_onlineresource metadata is set in the map’s web object metadata and specifies the URL that should
be used to access your server. This is required for the GetCapabilities output. If wms_onlineresource is not
provided then MapServer will try to provide a default one using the script name and hostname, but you shouldn’t
count on that too much. It is strongly recommended that you provide the wms_onlineresource metadata.
See section 6.2.2 of the WMS 1.1.1 specification for the whole story about the online resource URL. Basically,
what you need is a complete HTTP URL including the http:// prefix, hostname, script name, potentially a
“map=” parameter, and and terminated by “?” or “&”.
Here is a valid online resource URL:
http://my.host.com/cgi-bin/mapserv?map=mywms.map&
By creating a wrapper script on the server it is possible to hide the “map=” parameter from the URL and then
your server’s online resource URL could be something like:
http://my.host.com/cgi-bin/mywms?
This is covered in more detail in the section “More About the Online Resource URL” below.
• Configuring for GetFeatureInfo Requests:
You must set the layer TEMPLATE parameter for the layer to be queryable by GetFeatureInfo requests. For
requests of type “text/html” you should also set the layer HEADER and FOOTER parameters.
For GetFeatureInfo requests of GML you must set the layer to DUMP TRUE in the mapfile. As of MapServer
4.6 you must also set the gml_* metadata for the layer attributes to be served (see the Layer Object metadata in
the Reference Section later in this document).
Here are working examples of GetFeatureInfo requests: text/plain / text/html / gml (for gml, your browser might
ask you to save the file, if so save it locally as a .gml file and view it in a text editor)
OK, now that we’ve got a mapfile, we have to check the XML capabilities returned by our server to make sure nothing
is missing.
Using a web browser, access your server’s online resource URL to which you add the parameters “SER-
VICE=WMS&VERSION=1.1.1&REQUEST=GetCapabilities” to the end, e.g.
http://my.host.com/cgi-bin/mapserv?map=mywms.map&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetCapabilities
Here is a working GetCapabilities request (note that the SERVICE parameter is required for all GetCapabilities re-
quests):
http://demo.mapserver.org/cgi-bin/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetCapabilities
This should return a document of MIME type application/vnd.ogc.wms_xml, so your browser is likely going to prompt
you to save the file. Save it and open it in a text editor (Emacs, Notepad, etc.), and you will see the returned XML
from the WMS server.
If you get an error message in the XML output then take necessary actions. Common problems and solutions are listed
in the FAQ at the end of this document.
If everything went well, you should have a complete XML capabilities document. Search it for the word “WARN-
ING”... MapServer inserts XML comments starting with “<!–WARNING: ” in the XML output if it detects missing
mapfile parameters or metadata items. If you notice any warning in your XML output then you have to fix all of them
before you can register your server with a WMS client, otherwise things are likely not going to work.
Note that when a request happens, it is passed through WMS, WFS, and WCS in MapServer (in that order) until one
of the services respond to it.
OK, now that we know that our server can produce a valid XML GetCapabilities response we should test the GetMap
request. MapServer only checks for a few of the required GetMap parameters, so both of the minimum MapServer
parameters and a valid GetMap request will be explained below.
The following is a list of the required GetMap parameters according to the WMS spec:
VERSION=version: Request version
REQUEST=GetMap: Request name
LAYERS=layer_list: Comma-separated list of one or more map layers. Optional if SLD parameter is
present.
STYLES=style_list: Comma-separated list of one rendering style per requested layer. Optional if SLD
parameter is present. NOTE that MapServer does not support named styles, so most times you would
specify “STYLES=” with an empty value. MapServer does support STYLES when used with an SLD.
SRS=namespace:identifier: Spatial Reference System.
BBOX=minx,miny,maxx,maxy: Bounding box corners (lower left, upper right) in SRS units.
WIDTH=output_width: Width in pixels of map picture.
HEIGHT=output_height: Height in pixels of map picture.
FORMAT=output_format: Output format of map.
Note: WMS Servers only advertise supported formats that are part of the gd / gdal libraries.
A valid example would therefore be:
http://my.host.com/cgi-bin/mapserv?map=mywms.map&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&LAYERS=prov
If you have access to a WMS client, then register your new server’s online resource with it and you should be off and
running.
If you don’t have your own WMS client installed already, here are a few pointers:
• MapServer itself can be used as a WMS client, see the MapServer WMS Client Howto.
• Quantum GIS is a full GIS package which includes WMS client support. (recommended)
• OpenJUMP is a desktop GIS package which includes WMS client support.
• uDig is a desktop package that allows users to add WMS layers.
• Deegree provides a WMS client.
• owsview Viewer Client Generator is an online application that allows users to add WMS layers.
This list is not exhaustive, there are several Open Source or proprietary packages that offer WMS support and could
be used to interact with your new MapServer WMS server instance.
As mentioned in the section “Setup a Mapfile / wms_onlineresource metadata” above, the following Online Resource
URL is perfectly valid for a MapServer WMS according to section 6.2.2 or the WMS 1.1.1 specification:
http://my.host.com/cgi-bin/mapserv?map=mywms.map&
However, some people will argue that the above URL contains mandatory vendor-specific parameters and that this is
illegal. First we would like to point that “map=...” is not considered a vendor-specific parameter in this case since it
is part of the Online Resource URL which is defined as an opaque string terminated by “?” or “&” (See WMS 1.1.1
section 6.2.2).
But anyway, even if it’s valid, the above URL is still ugly. And you might want to use a nicer URL for your WMS
Online Resource URL. Here are some suggestions:
1. On Unix servers, you can setup a wrapper shell script that sets the MS_MAPFILE environment variable and
then passes control to the mapserv executable... that results on a cleaner OnlineResource URL:
#! /bin/sh
MS_MAPFILE=/path/to/demo.map
export MS_MAPFILE
/path/to/mapserv
2. Another option is to use the “setenvif” feature of Apache: use symbolic links that all point to a same mapserv
binary, and then for each symbolic link test the url, and set the MAP environment accordingly.
For Windows and Apache users the steps are as follows (this requires Apache 1.3 or newer):
• Copy mapserv.exe to a new name for your WMS, such as “mywms.exe”.
• In httpd.conf, add:
3. On IIS servers (Windows), you can use the following ASP script:
Note: The script below, while functional, is intended only as an example of using ASP to filter
MapServer requests. Using ASP in a production WMS server will likely require additional ASP
especially in the area of error handling and setting timeouts.*
<%
Server.ScriptTimeout = 360
Dim objHTTP
Set objHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
objHTTP.open "GET", strURL, false
objHTTP.send ""
Response.ContentType = objHTTP.getResponseHeader("content-type")
Response.BinaryWrite objHTTP.responseBody
4. Some OGC services (WFS, SOS) support both GET and POST requests. Here, you can use a minimal MapScript
WxS wrapper. Here’s a Python example:
#!/usr/bin/python
import mapscript
req = mapscript.OWSRequest()
req.loadParams()
map = mapscript.mapObj(’/path/to/config.map’)
map.OWSDispatch(req)
GetLegendGraphic Request
This request returns a legend image (icon) for the specified layer. The request will draw an icon and a label for all
classes defined on the layer. If the requested layername is a GROUP-name, all included layers will be returned in the
legend-icon.
Requirements
The following are required in the WMS server mapfile to enable this request:
• a LEGEND object.
• a CLASS object for each layer.
• a NAME in the CLASS object.
• the STATUS of each LAYER must be set to ON.
Parameters
MapServer 5.4 adds support for WMS 1.3.0. Although the general mechanism in Mapserver to support this new
specification are the same, there are some notable upgrades.
Example of requests
Users can use the CRS:84 coordinate system and order the BBOX coordinates as long/lat: -
...&CRS=CRS:84&BBOX=-180.0,-90.0,180.0,90.0&... (example request)
Users can also use the ESPG:4326 coordinates and use the axis odering of lat/long: - ...&EPSG:4326&BBOX=-90.0,-
180.0,90,180.0&... (example request)
• valid values for the EXCEPTIONS parameter in a GetMap request are XML, INIMAGE, BLANK
• valid value for the EXCEPTIONS parameter in a GetFeatureInfo request is XML
• LayerLimit is introduced, allowing a server to advertise and limit the number of layers a client is allowed to
include in a GetMap request
• WMS 1.3.0 Post request should be an XML document containing the different operations and parameters.
• SLD documents containing elements form the Feature Encoding 1.1 specification could potentially use ESPG
projections with some filters. It is not yet clear nor implemented if the axis ordering should be taken into account
in these specific cases.
As of version 5.4, MapServer passes all the basic and query tests of the OGC CITE test suite for WMS 1.3.0.
ows_http_max_age
• Description: (Optional) an integer (in seconds) to specify how long a given map response should be con-
sidered new. Setting this directive allows for aware WMS clients to use this resulting HTTP header
value as a means to optimize (and minimize) requests to a WMS Server. More info is available at
http://www.mnot.net/cache_docs/#CACHE-CONTROL
ows_updatesequence
• Description: (Optional) The updateSequence parameter can be used for maintaining the consistency of a client
cache of the contents of a service metadata document. The parameter value can be an integer, a timestamp in
[ISO 8601:2000] format, or any other number or string.
ows_sld_enabled
• Description: (Optional) A value (true or false) which, when set to “false”, will ignore SLD and SLD_BODY
parameters in order to disable remote styling of WMS layers. Also, SLD is not advertised in WMS Capabilities
as a result
ows_schemas_location
• Description: (Optional) (Note the name ows_schemas_location and not wms_... this is because all OGC Web
Services (OWS) use the same metadata) Root of the web tree where the family of OGC WMS XMLSchema
files are located. This must be a valid URL where the actual .xsd files are located if you want your WMS output
to validate in a validating XML parser. Default is http://schemas.opengis.net. See http://ogc.dmsolutions.ca for
an example of a valid schema tree.
wms_abstract
• WMS TAG Name: Abstract (WMS1.1.1, sect. 7.1.4.2)
• Description: (Optional) A blurb of text providing more information about the WMS server.
wms_accessconstraints
• WMS TAG Name: AccessConstraints (WMS1.1.1, sect. 7.1.4.2)
• Description: (Optional) Access constraints information. Use the reserved word “none” if there are no access
constraints.
wms_addresstype, wms_address, wms_city, wms_stateorprovince, wms_postcode, wms_country
• WMS TAG Name: ContactAddress and family (WMS1.1.1, sect. 7.1.4.2)
• Description: Optional contact address information. If provided then all six metadata items are required.
wms_attribution_logourl_format
• Description: (Optional) The MIME type of the logo image. (e.g. “image/png”). Note that the other
wms_attribution_logourl_* metadata must also be specified.
• refer to section 7.1.4.5.11 of the WMS 1.1.1 spec.
wms_attribution_logourl_height
• Description: (Optional) Height of the logo image in pixels. Note that the other wms_attribution_logourl_*
metadata must also be specified.
• refer to section 7.1.4.5.11 of the WMS 1.1.1 spec.
wms_attribution_logourl_href
• Description: (Optional) URL of the logo image. Note that the other wms_attribution_logourl_* metadata must
also be specified.
• refer to section 7.1.4.5.11 of the WMS 1.1.1 spec.
wms_attribution_logourl_width
• Description: (Optional) Width of the logo image in pixels. Note that the other wms_attribution_logourl_*
metadata must also be specified.
• refer to section 7.1.4.5.11 of the WMS 1.1.1 spec.
wms_attribution_onlineresource
• Description: (Optional) The data provider’s URL.
• refer to section 7.1.4.5.11 of the WMS 1.1.1 spec.
wms_attribution_title
• Description: (Optional) Human-readable string naming the data provider.
• refer to section 7.1.4.5.11 of the WMS 1.1.1 spec.
wms_contactelectronicmailaddress
• WMS TAG Name: ContactElectronicMailAddress (WMS1.1.1, sect. 7.1.4.2)
• Description: Optional contact Email address.
wms_contactfacsimiletelephone
• WMS TAG Name: ContactFacsimileTelephone (WMS1.1.1, sect. 7.1.4.2)
• Description: Optional contact facsimile telephone number.
wms_contactperson, wms_contactorganization, wms_contactposition
• WMS TAG Name: ContactInformation, ContactPerson, ContactOrganization, ContactPosition (WMS1.1.1, sect.
7.1.4.2)
• Description: Optional contact information. If provided then all three metadata items are required.
wms_contactvoicetelephone
wms_service_onlineresource
• Description: (Optional) Top-level onlineresource URL. MapServer uses the onlineresource metadata (if pro-
vided) in the following order:
1. wms_service_onlineresource
2. ows_service_onlineresource
3. wms_onlineresource (or automatically generated URL, see the onlineresource section of this document)
wms_srs
• WMS TAG Name: SRS (WMS1.1.1, sect. 6.5.5)
• Description: (Recommended) Contains a list of EPSG projection codes that should be advertized as being
available for all layers in this server. The value can contain one or more EPSG:<code> pairs separated by spaces
(e.g. “EPSG:4269 EPSG:4326”) This value should be upper case (EPSG:42304.....not epsg:42304) to avoid
problems with case sensitive platforms.
• See Also: section “Setup a Mapfile / Map PROJECTION and wms_srs metadata” above.
wms_timeformat
• Description: The time format to be used when a request is sent. (e.g. “wms_timeformat” “%Y-%m-%d %H,
%Y-%m-%d %H:%M”). Please see the WMS Time Support Howto for more information.
wms_title
• WMS TAG Name: Title (WMS1.1.1, sect. 7.1.4.1)
• Description: (Required) A human-readable name for this Layer.
wms_rootlayer_title
• WMS TAG Name: Title (WMS1.1.1, sect. 7.1.4.1)
• Description: (Optional) Same as wms_title, applied to the root Layer element. If not set, then wms_title will be
used.
wms_rootlayer_abstract
• WMS TAG Name: Abstract (WMS1.1.1, sect. 7.1.4.2)
• Description: (Optional) Same as wms_abstract, applied to the root Layer element. If not set, then wms_abstract
will be used.
wms_rootlayer_keywordlist
• WMS TAG Name: KeywordList (WMS1.1.1, sect. 7.1.4.2)
• Description: (Optional) Same as wms_keywordlist, applied to the root Layer element. If not set, then
wms_keywordlist will be used.
wms_layerlimit
• WMS TAG Name: LayerLimit (WMS1.3.0, sect. 7.2.4.3)
• Description: (Optional) The maximum number of layers a WMS client can specify in a GetMap request. If not
set, then no limit is imposed.
gml_exclude_items
• Description: (Optional, applies only to GetFeatureInfo GML requests) A comma delimited list of items to
exclude. As of MapServer 4.6, you can control how many attributes (fields) you expose for your data layer with
metadata. The previous behaviour was simply to expose all attributes all of the time. The default is to expose
no attributes at all. An example excluding a specific field would be:
"gml_include_items" "all"
"gml_exclude_items" "Phonenum"
gml_groups
• Description: (Optional, applies only to GetFeatureInfo GML requests) A comma delimited list of group names
for the layer.
gml_[group name]_group
• Description: (Optional, applies only to GetFeatureInfo GML requests) A comma delimited list of attributes in
the group. Here is an example:
"gml_include_items" "all"
"gml_groups" "display"
"gml_display_group" "Name_e,Name_f"
gml_include_items
• Description: (Optional, applies only to GetFeatureInfo GML requests) A comma delimited list of items to
include, or keyword “all”. As of MapServer 4.6, you can control how many attributes (fields) you expose for
your data layer with this metadata. The previous behaviour was simply to expose all attributes all of the time.
You can enable full exposure by using the keyword “all”, such as:
"gml_include_items" "all"
You can specify a list of attributes (fields) for partial exposure, such as:
"gml_include_items" "Name,ID"
gml_[item name]_type
• Description: (Optional, applies only to GetFeatureInfo GML requests) Specifies the type of the attribute. Valid
values are Integer|Real|Character|Date|Boolean.
gml_xml_items
• Description: (Optional, applies only to GetFeatureInfo GML requests) A comma delimited list of items that
should not be XML-encoded.
gml_geometries
• Description: (Optional, applies only to GetFeatureInfo GML requests) Provides a name for geometry elements.
The value is specified as a string to be used for geometry element names. By default, GML geometries are
not written in GML GetFeatureInfo output, unless gml_geometries and gml_[name]_type are both set. By
default, only the bounding box is written. If gml_geometries is set to “none”, neither the bounding box
nor the geometry are written.
gml_[name]_type
• Description: (Optional, applies only to GetFeatureInfo GML requests) When employing gml_geometries, it
is also necessary to specify the geometry type of the layer. This is accomplished by providing a value for
gml_[name]_type, where [name] is the string value specified for gml_geometries, and a value which is
one of:
– point
– multipoint
– line
– multiline
– polygon
– multipolygon
wms_abstract
• Same as wms_abstract in the Web Object.
wms_attribution_logourl_format
• Description: (Optional) The MIME type of the logo image. (e.g. “image/png”). Note that the other
wms_attribution_logourl_* metadata must also be specified.
• refer to section 7.1.4.5.11 of the WMS 1.1.1 spec.
wms_attribution_logourl_height
• Description: (Optional) Height of the logo image in pixels. Note that the other wms_attribution_logourl_*
metadata must also be specified.
• refer to section 7.1.4.5.11 of the WMS 1.1.1 spec.
wms_attribution_logourl_href
• Description: (Optional) URL of the logo image. Note that the other wms_attribution_logourl_* metadata must
also be specified.
• refer to section 7.1.4.5.11 of the WMS 1.1.1 spec.
wms_attribution_logourl_width
• Description: (Optional) Width of the logo image in pixels. Note that the other wms_attribution_logourl_*
metadata must also be specified.
• refer to section 7.1.4.5.11 of the WMS 1.1.1 spec.
wms_attribution_onlineresource
• Description: (Optional) The data provider’s URL.
• refer to section 7.1.4.5.11 of the WMS 1.1.1 spec.
wms_attribution_title
• Description: (Optional) Human-readable string naming the data provider.
• refer to section 7.1.4.5.11 of the WMS 1.1.1 spec.
wms_authorityurl_name, wms_authorityurl_href - Description: (Optional) AuthorityURL is used in tan-
dem with Identifier values to provide a means of linking identifier information back to a web service.
The wms_identifier_authority should provide a string that matches a declared wms_authorityurl_name. Both
wms_authorityurl_name and wms_authorityurl_href must be present for an AuthorityURL tag to be written to the
capabilities. - refer to section 7.1.4.5.12 of the WMS 1.1.1 spec.
wms_metadataurl_format
• Description: (Optional) The file format MIME type of the metadata record (e.g. “text/plain”). The layer
metadata wms_metadataurl_type and wms_metadataurl_href must also be specified.
• refer to section 7.1.4.5.10 of the WMS 1.1.1 spec.
wms_metadataurl_href
• Description: (Optional) The URL to the layer’s metadata. The layer metadata wms_metadataurl_format and
wms_metadataurl_type must also be specified.
• refer to section 7.1.4.5.10 of the WMS 1.1.1 spec.
wms_metadataurl_type
• Description: (Optional) The standard to which the metadata complies. Currently only two types are valid:
“TC211” which refers to [ISO 19115], and “FGDC” which refers to [FGDC-STD-001-1988]. The layer meta-
data wms_metadataurl_format and wms_metadataurl_href must also be specified.
• refer to section 7.1.4.5.10 of the WMS 1.1.1 spec.
wms_opaque
• WMS TAG Name: Opaque (WMS1.1.1, sect. 7.1.4.6.3)
• Description: (Optional) Set this metadata to “1” to indicate that the layer represents an area-filling coverage of
space (e.g. a bathymetry and elevation layer). This should be taken by the client as a hint that this layer should
be placed at the bottom of the stack of layers.
wms_srs
• Same as wms_srs in the Web Object .
wms_style
• Description: (Optional) The LegendURL style name. Requires the following meta-
data: wms_style_<style’s_name>_width, wms_style_<style’s_name>_legendurl_height,
wms_style_<style’s_name>_legendurl_format, wms_style_<style’s_name>_legendurl_href
• refer to section 7.1.4.5.4 of the WMS 1.1.1 spec.
wms_style_<style’s_name>_legendurl_height
• Description: (Optional) The height of the legend image in pixels. Requires the following
metadata: wms_style_<style’s_name>_width, wms_style, wms_style_<style’s_name>_legendurl_format,
wms_style_<style’s_name>_legendurl_href.
• refer to section 7.1.4.5.4 of the WMS 1.1.1 spec.
wms_style_<style’s_name>_legendurl_href
• Description: (Optional) The URL to the layer’s legend. Requires the following
metadata: wms_style_<style’s_name>_width, wms_style_<style’s_name>_legendurl_height,
wms_style_<style’s_name>_legendurl_format, wms_style.
• refer to section 7.1.4.5.4 of the WMS 1.1.1 spec.
wms_style_<style’s_name>_legendurl_format
• Description: (Optional) The file format MIME type of the legend image. Requires the follow-
ing metadata: wms_style_<style’s_name>_width, wms_style_<style’s_name>_legendurl_height, wms_style,
wms_style_<style’s_name>_legendurl_href.
• refer to section 7.1.4.5.4 of the WMS 1.1.1 spec.
wms_style_<style’s_name>_legendurl_width
• Description: (Optional) The width of the legend image in pixels. Requires the following
metadata: wms_style_<style’s_name>_format, wms_style_<style’s_name>_legendurl_height, wms_style,
wms_style_<style’s_name>_legendurl_href.
• refer to section 7.1.4.5.4 of the WMS 1.1.1 spec.
wms_timedefault
• Description: (Optional for Time Support) This value is used if it is defined and the Time value is missing in the
request. Please see the WMS Time Support Howto for more information.
wms_timeextent
• Description: (Mandatory for Time Support) This is used in the capabilities to return the valid time values for
the layer. The value defined here should be a valid time range. Please see the WMS Time Support Howto for
more information.
wms_timeitem
• Description: (Mandatory for Time Support) This is the name of the field in the DB that contains the time values.
Please see the WMS Time Support Howto for more information.
wms_title
• Same as wms_title in the Web Object.
1 NAME "WMS-test"
2 STATUS ON
3 SIZE 400 300
4 SYMBOLSET ../ e t c / s y m b o l s . s y m
5 EXTENT -2200000 -712631 3072800 3840000
6 UNITS METERS
7 SHAPEPATH "../data"
8 IMAGECOLOR 255 255 255
9 FONTSET ../ e t c / f o n t s . t x t
10
11 WEB
12 IMAGEPATH "/ms4w/tmp/ms_tmp/"
13 IMAGEURL "/ms_tmp/"
14 METADATA
15 "wms_title" "WMS Demo Server" ##required
16 "wms_onlineresource" "http://yourpath/cgi-bin/mapserv.exe?" ##required
17 "wms_srs" "EPSG:42304 EPSG:42101 EPSG:4269 EPSG:4326" ##recommended
18 END
19 END
20
21 PROJECTION
22 "init=epsg:42304" ##required
23 END
24
25 #
26 # Start of layer definitions
27 #
28
29 LAYER
30 NAME "park"
31 METADATA
32 "wms_title" "Parks" ##required
33 END
34 TYPE POLYGON
35 STATUS OFF
36 DATA p a r k
37 PROJECTION
38 "init=epsg:42304" ##recommended
39 END
40 CLASS
41 NAME "Parks"
42 STYLE
43 COLOR 200 255 0
44 OUTLINECOLOR 120 120 120
45 END
46 END
47 END # Layer
48
49 LAYER
50 NAME p o p p l a c e
51 METADATA
52 "wms_title" "Cities" ##required
53 END
54 TYPE POINT
55 STATUS ON
56 DATA p o p p l a c e
57 PROJECTION
58 "init=epsg:42304" ##recommended
59 END
60 CLASS
61 NAME "Cities"
62
414 STYLE Chapter 9. OGC Support and Configuration
63 SYMBOL 2
64 SIZE 8
65 COLOR 0 0 0
MapServer Documentation, Release 6.0
Q My WMS server produces the error “msProcessProjection(): no system list, errno: ..”
A That’s likely PROJ4 complaining that it cannot find the “epsg” projection definition file. Make sure
you have installed PROJ 4.4.3 or more recent and that the “epsg” file is installed at the right location.
On Unix it should be under /usr/local/share/proj/, and on Windows PROJ looks for it under C:/PROJ/
or C:/PROJ/NAD (depending on the installation). You should also check the error documentation to
see if your exact error is discussed.
If you don’t have the “epsg” file then you can get it as part of the PROJ4 distribution at
http://trac.osgeo.org/proj/ or you can download it at http://www.maptools.org/dl/proj4-epsg.zip.
WEB
...
METADATA
"wms_title" "WMS Demo Server"
"wms_onlineresource" "http://my.host.com/cgi-bin/mapserv?map=wms.map&"
"wms_srs" "AUTO:42001 AUTO:42002"
END
END
Table of Contents
• WMS Client
– Introduction
– Compilation / Installation
– MapFile Configuration
– Limitations/TODO
9.2.1 Introduction
A WMS (or Web Map Server) allows for use of data from several different servers, and enables for the creation
of a network of Map Servers from which clients can build customized maps. The following document contains
information about using MapServer’s WMS connection type to include layers from remote WMS servers in MapServer
applications.
This document assumes that you are already familiar with certain aspects of MapServer:
• MapServer application development and setting up .map files.
• Familiarity with the WMS spec would be an asset. A link to the WMS specification document is included below.
WMS-Related Information
The WMS connection type is enabled by the –with-wmsclient configure switch. It requires PROJ4, GDAL and libcurl
version 7.10.1 or more recent. Windows users who do not want to compile MapServer should use MS4W (which
comes ready for WMS/WFS client and server use), or check for the availability of other Windows binaries with WMS
support.
• For PROJ4 and GDAL installation, see the MapServer Compilation HowTo (Compiling on Unix / Compiling on
Win32)
• For libcurl, make sure you have version 7.10.1 or more recent installed on your system. You can find out your
libcurl version using curl-config –version. (if your system came with an older version of libcurl preinstalled
then you MUST uninstall it prior to installing the new version)
Once the required libraries are installed, then configure MapServer using the –with-wmsclient switch (plus all the other
switches you used to use) and recompile. This will give you a new set of executables (and possibly php_mapscript.so
if you requested it). See the MapServer Compilation HowTo (links above) for installation details.
To check that your mapserv executable includes WMS support, use the “-v” command-line switch and look for “SUP-
PORTS=WMS_CLIENT”.
Example 1. Mapserv Version Info on Unix:
$ ./mapserv -v
MapServer version 5.2.0-rc1 OUTPUT=GIF OUTPUT=PNG OUTPUT=JPEG OUTPUT=WBMP
OUTPUT=PDF OUTPUT=SWF OUTPUT=SVG SUPPORTS=PROJ SUPPORTS=AGG
SUPPORTS=FREETYPE SUPPORTS=ICONV SUPPORTS=WMS_SERVER SUPPORTS=WMS_CLIENT
SUPPORTS=WFS_SERVER SUPPORTS=WFS_CLIENT SUPPORTS=WCS_SERVER
SUPPORTS=SOS_SERVER SUPPORTS=FASTCGI SUPPORTS=THREADS
SUPPORTS=GEOS SUPPORTS=RGBA_PNG INPUT=JPEG INPUT=POSTGIS
INPUT=ORACLESPATIAL INPUT=OGR INPUT=GDAL INPUT=SHAPEFILE
(Note: installing these PROJ4 codes is optional, install only if you need them)
Some Canadian WMS servers will use some non-standard projection codes not included in the default distribution
(e.g. EPSG:42304, etc.). If you are planning to use MapServer to connect to Canadian WMS servers then you might
want to download a custom Canadian epsg file with those codes, and unzip it in the /usr/local/share/proj directory (or
/ms4w/proj/nad/ for MS4W users).
Finally, ESRI WMS servers also come with their own series of non-standard codes. If you are planning to connect
to ESRI WMS servers then you might want to get a custom epsg file that contains the canadian codes and the ESRI
codes, allowing you to connect to any server. Download the custom ESRI epsg file and unzip it in /usr/local/share/proj
(or /ms4w/proj/nad/ for MS4W users).
Q But why not always install and distribute the proj4-epsg-with-42xxx-and-esri.zip file then since it’s
more complete?
A You should install only the epsg projection codes that you need, the epsg file with all ESRI codes in it
is 20% larger than the default one, so it comes with extra overhead that you may not need. Also note
that when creating WMS servers, in order to be really interoperable, only EPSG codes that are part
of the standard EPSG list should be used. i.e. it is a bad idea for interoperability to use the custom
canadian codes or the custom ESRI codes and we do not want to promote their use too much.
Note: A PROJECTION must be set in the mapfile for the MAP unless you are sure that all your WMS layers support
only a single projection which is the same as the PROJECTION of the map. The MAP PROJECTION can be set using
“init=epsg:xxxx” codes or using regular PROJ4 parameters. Failure to set a MAP PROJECTION may result in blank
maps coming from remote WMS servers (because of inconsistent BBOX+SRS combination being used in the WMS
connection URL).
Before version 6.0, and in version 6.0 when wms_cache_to_disk metadata is turned on, you have to set the IM-
AGEPATH value in the WEB object of your mapfile to point to a valid and writable directory. MapServer will use this
directory to store temporary files downloaded from the remote servers. The temporary files are automatically deleted
by MapServer so you won’t notice them.
Example 3. Setting IMAGEPATH Parameter in Mapfile
MAP
...
WEB
IMAGEPATH "/tmp/ms_tmp/"
IMAGEURL ...
END
...
END
If you want to keep this temporary file for debugging purposes, you should add the following statement to the LAYER
object of your mapfile:
LAYER
....
DEBUG ON
...
END
WMS layers are accessed via the WMS connection type in the Mapfile. Here is an example of a layer using this
connection type:
LAYER
NAME "country_bounds"
TYPE RASTER
STATUS ON
CONNECTION "http://demo.mapserver.org/cgi-bin/wms?"
CONNECTIONTYPE WMS
METADATA
"wms_srs" "EPSG:4326"
"wms_name" "country_bounds"
"wms_server_version" "1.1.1"
"wms_format" "image/gif"
END
END
• CONNECTIONTYPE WMS
• CONNECTION - this is the remote server’s online resource URL, just the base URL without any of the WMS
parameters. The server version, image format, layer name, etc. will be provided via metadata, see below.
Note: Note that if the CONNECTION parameter value is not set the the value of the “wms_onlineresource” metadata
will be used. If both CONNECTION and “wms_onlineresource” are set then the “wms_onlineresource” metadata
takes precedence.
• MINSCALE, MAXSCALE - if the remote server’s capabilities contains a ScaleHint value for this layer then
you might want to set the MINSCALE and MAXSCALE in the LAYER object in the mapfile. This will allow
MapServer to request the layer only at scales where it makes sense
• PROJECTION object - it is optional at this point. MapServer will create one internally if needed. Including
one may
allow MapServer to avoid looking up a definition in the PROJ.4 init files.
• “wms_auth_username” metadata - msEncrypt-style authorization string. Empty strings are also accepted.
METADATA
"wms_auth_username" "foo"
"wms_auth_password" "{FF88CFDAAE1A5E33}"
END
• “wms_connectiontimeout” metadata - the maximum time to wait for a remote WMS layer to load, set in
seconds (default is 30 seconds). This metadata can be added at the layer level so that it affects only that
layer, or it can be added at the map level (in the web object) so that it affects all of the layers. Note that
wms_connectiontimeout at the layer level has priority over the map level.
METADATA
...
"wms_connectiontimeout" "60"
...
END
• “wms_exceptions_format” metadata - set the format for exceptions (as of MapServer 4.6). MapServer de-
faults to application/vnd.ogc.se_inimage (the exception will be in a picture format). You can check the GetCa-
pabilities of the server to see what formats are available for exceptions. The application/vnd.ogc.se_inimage
exception format is actually a non-required exception format in the WMS 1.1.1 spec, so there are servers out
there which don’t support this format. In that case you would use:
LAYER
...
METADATA
"wms_exceptions_format " a p p l i c a t i on/ v n d . o g c . s e _ x m l "
END
...
END
• “wms_force_separate_request” metadata - set this to “1” to force this WMS layer to be requested using its
own separate GetMap request. By default MapServer will try to merge multiple adjacent WMS layers from the
same server into a single multi-layer GetMap request to reduce the load on remote servers and improve response
time. This metadata is used to bypass that behavior.
• “wms_formatlist” metadata - comma-separated list of image formats supported by the remote WMS server.
Note that wms_formatlist is used only if wms_format is not set. If both wms_format and wms_formatlist are
provided then wms_format takes precedence.
• “wms_latlonboundingbox” metadata - the bounding box of this layer in geographic coordinates in the format
“lon_min lat_min lon_max lat_max”. If it is set then MapServer will request the layer only when the map view
overlaps that bounding box. You normally get this from the server’s capabilities output.
METADATA
"wms_latlonboundingbox" "-124 48 -123 49"
END
• “wms_proxy_auth_type” metadata - the authorization type to use for a proxy connection. Supported types
include:
– basic
– digest
– ntlm
– any (the underlying http library picks the best among the opotions supported by the remote server)
– anysafe (the underlying http library picks only safe methods among the options supported by the remote
server)
METADATA
"wms_proxy_auth_type" "ntlm"
END
• “wms_proxy_host” metadata - the hostname of the proxy to use, in “dot-quad” format, with an optional port
component (e.g. ‘192.168.2.10:8080’).
METADATA
"wms_proxy_host" "192.168.2.10"
END
• “wms_proxy_type” metadata - the type of the proxy connection. Valid values are ‘http’ and ‘socks5’, which
are case sensitive.
METADATA
"wms_proxy_type" "http"
END
• “wms_proxy_username” metadata - msEncrypt-style string for a proxy connection. Empty strings are also
accepted.
METADATA
"wms_proxy_username" "foo"
"wms_proxy_password" "{FF88CFDAAE1A5E33}"
END
For more information on SLDs in MapServer see the SLD HowTo document.
• “wms_time” metadata - value to use for the TIME parameter in GetMap requests for this layer. Please see the
WMS Time HowTo for more information.
• “wms_bgcolor” metadata - specifies the color to be used as the background of the map. The general format of
BGCOLOR is a hexadecimal encoding of an RGB value where two hexadecimal characters are used for each of
Red, Green, and Blue color values. The values can range between 00 and FF for each (0 and 255, base 10). The
format is 0xRRGGBB; either upper or lower case characters are allowed for RR, GG, and BB values. The “0x”
prefix shall have a lower case “x”.
• “wms_transparent” metadata - specifies whether the map background is to be made transparent or not.
TRANSPARENT can take on two values, “TRUE” or “FALSE”. If not specified, MapServer sets default to
“TRUE”
• “wms_cache_to_disk” metadata - set this to “1” to force MapServer to write fetched images to disk. Writing
to disk is necessary to take advantage of MapServer’s caching logic to avoid refetching WMS requests made
previously. This feature is new to MapServer 6.0 - previously results were always written to disk.
• “wms_nonsquare_ok” metadata - set this to “0” to indicate that the remote WMS only supports requests
for square pixels. In this case MapServer will be careful to only make square pixel requests even if it means
oversampling in one dimension compared to the resolution of image data required. This feature is new to
MapServer 6.0.
• “wms_extent” metadata - If there is exactly one SRS supported by this layer (as listed in the wms_srs meta-
data), and if the wms_extent metadata item (or an extent specified via the EXTENT keyword) is set then
MapServer will take care to only making requests within this area. This can short circuit requests completely
outside the layer, reduce processing for layers that only partially overlap the target map area and avoid poor
behaviors with reprojection in some areas. The contents of this metadata item should be of the form “minx miny
maxx maxy”. This feature is new to MapServer 6.0.
Note: Note that each of the above metadata can also be referred to as ‘ows_*’ instead of ‘wms_*’. MapServer tries
the ‘wms_*’ metadata first, and if not found it tries the corresponding ‘ows_*’ name. Using this reduces the amount of
duplication in mapfiles that support multiple OGC interfaces since “ows_*” metadata can be used almost everywhere
for common metadata items shared by multiple OGC interfaces.
Old CONNECTION parameter format from version 3.5 and 3.6 (deprecated)
In MapServer version 3.5 and 3.6, the CONNECTION parameter had to include at a minimum the VERSION, LAY-
ERS, FORMAT and TRANSPARENT WMS parameters. This mode of operation is still supported but is deprecated
and you are encouraged to use metadata items for those parameters as documented in the previous section above.
Here is an example of a layer definition using this deprecated CONNECTION parameter format:
LAYER
NAME "bathymetry_elevation"
TYPE RASTER
STATUS ON
CONNECTIONTYPE WMS
CONNECTION "http://demo.mapserver.org/cgi-bin/wms?VERSION=1.1.0&LAYERS=bluemarble&FORMAT=image/png"
PROJECTION
"init=epsg:4326"
END
END
9.2.4 Limitations/TODO
1. GetFeatureInfo is not fully supported since the output of getFeatureInfo is left to the discretion of the remote
server. A method layer.getWMSFeatureInfoURL() has been added to MapScript for applications that want to
access featureInfo results and handle them directly.
2. MapServer does not attempt to fetch the layer’s capabilities. Doing so at every map draw would be extremely
inefficient. And caching that information does not belong in the core of MapServer. This is better done at
the application level, in a script, and only the necessary information is passed to the MapServer core via the
CONNECTION string and metadata.
Table of Contents
• WMS Time
– Introduction
– Enabling Time Support in MapServer
– Future Additions
– Limitations and Known Bugs
9.3.1 Introduction
A WMS server can provide support to temporal requests. This is done by providing a TIME parameter with a time
value in the request. MapServer 4.4 and above provides support to interpret the TIME parameter and transform the
resulting values into appropriate requests.
Time Patterns
WMS specifies that the basic format used for TIME requests is based on the ISO 8601:1988(E) “extended” format.
MapServer supports a limited set of patterns that are defined in the ISO 8601 specifications, as well as few other
patterns that are useful but not compliant to ISO 8601. Here is a list of patterns currently supported:
Table 1. Supported Time Patterns
Time Patterns Examples
YYYYMMDD 20041012
YYYY-MM-DDTHH:MM:SSZ 2004-10-12T13:55:20Z
YYYY-MM-DDTHH:MM:SS 2004-10-12T13:55:20
YYYY-MM-DD HH:MM:SS 2004-10-12 13:55:20
YYYY-MM-DDTHH:MM 2004-10-12T13:55
YYYY-MM-DD HH:MM 2004-10-12 13:55
YYYY-MM-DDTHH 2004-10-12T13
YYYY-MM-DD HH 2004-10-12 13
YYYY-MM-DD 2004-10-12
YYYY-MM 2004-10
YYYY 2004
THH:MM:SSZ T13:55:20Z
THH:MM:SS T13:55:20
To have a valid WMS layer with time support, the user has to define the following metadata at the layer level:
• wms_timeextent: (Mandatory) this is used in the capabilities document to return the valid time values for the
layer. The value defined here should be a valid time range. (more on this in ‘Specifying Time Extents’ below)
• wms_ timeitem: (Mandatory) this is the name of the field in the DB that contains the time values.
• wms_timedefault: (Optional) this value is used if it is defined and the TIME value is missing in the request.
Time Extents can be declared with the following syntax for the wms_timeextent metadata (see Annex C.3 in the WMS
1.1.1 specification document for a full description):
1. value - a single value. This is not directly supported in MapServer but there is an easy workwound by specifying
the same value as min and max.
2. value1,value2,value3,... - a list of multiple values.
3. min/max/resolution - an interval defined by its lower and upper bounds and its resolution. This is supported in
MapServer (note that the resolution is not supported however).
4. min1/max1/res1,min2/max2/res2,... - a list of multiple intervals.
LAYER
NAME "earthquakes"
METADATA
"wms_title" "Earthquakes"
"wms_timeextent" "2004-01-01/2004-02-01"
"wms_timeitem" "TIME"
"wms_timedefault" "2004-01-01 14:10:00"
END
TYPE POINT
STATUS ON
DATA "quakes"
CLASS
..
END
END
GetCapabilities Output
If your layer is set up properly, requesting the capabilities on the server outputs a Dimension element. Here is an
example of a GetCapabilities result for a layer configured for time support:
<Layer queryable="0" opaque="0" cascaded="0">
<Name>earthquakes</Name>
<Title>Earthquakes</Title>
<SRS>EPSG:4326</SRS>
<LatLonBoundingBox minx="-131.02" miny="24.84" maxx="-66.59" maxy="48.39" />
<BoundingBox SRS="EPSG:4326"
minx="-131.02" miny="24.84" maxx="-66.59" maxy="48.39" />
When sending a request with the TIME parameter, different types of time values can be specified. The following are
supported by MapServer:
• single value: for example: ...&TIME=2004-10-12&...
• multiple values: for example: ...&TIME=2004-10-12, 2004-10-13, 2004-10-14&...
• single range value: for example: ...&TIME=2004-10-12/2004-10-13&...
• multiple range values: for example: ...&TIME=2004-10-12/2004-10-13, 2004-10-15/2004-10-16&...
When MapServer receives a request with a TIME parameter, it transforms the time requests into valid expressions that
are assigned to the filter parameter on layers that are time-aware. Here are some examples of how different types of
requests are treated (wms_timeitem is defined here as being “time_field”):
• single value (2004-10-12) transforms to (‘[time_field]‘ eq ‘2004-10-12‘)
• multiple values (2004-10-12, 2004-10-13) transform to (‘[time_field]‘ eq ‘2004-10-12‘ OR ‘[time_field]‘ eq
‘2004-10-13‘)
• single range : 2004-10-12/2004-10-13 transforms to ((‘[time_field]‘ ge ‘2004-10-12‘) AND (‘[time_field]‘ le
‘2004-10-13‘))
• multiple ranges (2004-10-12/2004-10-13, 2004-10-15/2004-10-16) transform to ((‘[time_field]‘ ge ‘2004-10-
12‘ AND ‘[time_field]‘ le ‘2004-10-13‘) OR (‘[time_field]‘ ge ‘2004-10-15‘ AND ‘[time_field]‘ le ‘2004-10-
16‘))
As shown in the above examples, all fields and values are written inside back tics (‘) - this is the general way of
specifying time expressions inside MapServer.
Exceptions to this rule:
1. When dealing with layers that are not Shapefiles nor through OGR, the expression built has slightly different
syntax. For example, the expression set in the filter for the first example above would be ([time_field] = ‘2004-
10-12’).
2. For PostGIS/PostgreSQL layers, the time expression built uses the date_trunc function available in PostgreSQL.
For example, if the user passes a time value of ‘2004-10-12’, the expression set in the filter is date_trunc(‘day’,
time_field) = ‘2004-10-12’. The use of the date_trunc function allows requests to use the concept of time
resolution. In the example above, for a request of ‘2004-10-12’, MapServer determines that the resolution is
“day” by parsing the time string and the result gives all records matching the date 2004-10-12 regardless of the
values set for Hours/Minutes/Seconds in the database. For more information on the date_trunc function, please
refer to the PostgreSQL documentation.
The user has the ability to define the time format(s) to be used when a request is sent, in metadata at the WEB level.
For example, the user can define the following two formats:
Another example is for a WMS layer that is based on time data that contains precise time values taken every minute
(e.g., 2004-10-12T13:55, 2004-10-12T13:56, 2004-10-12 T13:57, ...). Normally, a valid request on such a layer
would require the time value to be as complete as the data underneath. By defining a set of patterns to use, MapServer
introduces the notion of resolution to be used when doing a query. Using the example above, a request TIME= 2004-
10-12T13:55 would be valid and a request TIME= 2004-10-12T13 would also be valid and would return all elements
taken for that hour.
Note that this functionality is only available on layers based on Shapefiles and OGR.
19 # raster layer
20 LAYER
21 NAME "nexrad-n0r-wmst"
22 TYPE RASTER
23 STATUS ON
24 DEBUG ON
25 DUMP TRUE
26 PROJECTION
27 "init=epsg:4326"
28 END
29 METADATA
30 "wms_title" "NEXRAD BASE REF WMS-T"
31 "wms_srs" "EPSG:4326"
32 "wms_extent" "-126 24 -66 50"
33 "wms_timeextent" "2003-08-01/2006-12-31/PT5M"
34 "wms_timeitem" "datetime" #datetime is a column in postgis table of type timestamp
35 "wms_timedefault" "2006-06-23T03:10:00Z"
36 END
37 OFFSITE 0 0 0
38 TILEITEM "filepath" #filepath is a column in postgis table with varchar of the filepath to each imag
39 TILEINDEX "time_idx"
40 END
You can find more information on Time and tileindexes in the WCS documentation.
Contents
• Map Context
– Introduction
– Implementing a Web Map Context
9.4.1 Introduction
The term ‘map context’ comes from the Open Geospatial Constortium’s (OGC) Web Map Context Specification v1.0.0,
which coincides with the OGC Web Map Server Specification (WMS) v1.1.1. A map context is a XML document
that describes the appearance of layers from one or more WMS servers, and can be transferred between clients while
maintaining startup views, the state of the view (and its layers), and storing additional layer information.
Support for OGC Web Map Context was added to MapServer in version 3.7/4.0. This allows client applications to load
and save a map configuration in a standard XML format. MapServer can read context documents of versions 0.1.2,
0.1.4, 0.1.7, 1.0.0, 1.1.0 and can export contents in versions 0.1.4, 0.1.7, 1.0.0, 1.1.0. Web Map Context 1.1.0 support
was added to MapServer 4.10
This document assumes that you are already familiar with certain aspects of MapServer:
• MapServer application development and setting up mapfiles.
• Familiarity with the WMS spec would be an asset. Please see the following section for links to associated
sources.
Map Context support requires PROJ4, GDAL/OGR and PHP support libraries.
Build/install the above libraries on your system and then build MapServer with the ‘–with-wmsclient –with-proj –with-
ogr –with-gdal –with-php’ configure options. Also make sure that your build uses the USE_WMS_LYR and USE_OGR
flags. For more details on MapServer compilation see the appropriate HowTo: Unix / Windows
Windows users can use MS4W, which is ready for Map Context use.
A map context document can ONLY contain WMS layers (e.g. CONNECTIONTYPE WMS). Please refer to the
MapServer WMS Client HowTo for more information on declaring WMS layers.
MapFile Metadata
The following mapfile metadata are used by MapServer to handle map context information:
(Note that some parameters have width, height, format, and href, and some only have format and href. This is because
width and height are only used for images and parameters that do not have them are text or html. For consistency with
the spec MapServer supports height and width for all parameters, but they should only be used for images)
• wms_abstract : A blurb of text providing more information about the WMS server.
• wms_dataurl_href : Link to an online resource where data corresponding to the layer can be found.
• wms_dataurl_format : Format of the online resource where data corresponding to the layer can be found.
• wms_dimension : Current dimension used. New in version 4.10.
• wms_dimensionlist : List of available dimensions. New in version 4.10.
• wms_dimension_%s_default : Default dimension value. MapServer will check for wms_time and
wms_timedefault metadata when this is not specified. %s = the name of the dimension. New in version 4.10.
• wms_dimension_%s_multiplevalues : Multiple dimension values. %s = the name of the dimension. New in
version 4.10.
• wms_dimension_%s_nearestvalue : Nearest dimension value. The default value is 0. %s = the name of the
dimension. New in version 4.10.
• wms_dimension_%s_units : Units for the dimension values. The default value is ISO8601. %s = the name of
the dimension. New in version 4.10.
• wms_dimension_%s_unitsymbol : Symbol for dimension units. The default value is t. %s = the name of the
dimension. New in version 4.10.
• wms_dimension_%s_uservalue : User dimension value. MapServer will check for wms_time and
wms_timedefault metadata when this is not specified. %s = the name of the dimension. New in version 4.10.
• wms_format : Current format used.
• wms_formatlist : List of available formats for this layer.
• wms_metadataurl_href : Link to an online resource where descriptive metadata of the corresponding layer can
be found.
• wms_metadataurl_format : Format of the online resource where descriptive metadata of the corresponding layer
can be found.
• wms_name : Name of the WMS layer on the server.
• wms_onlineresource : Required URL to access the server.
• wms_server_version : The version of the web map server specification.
• wms_server_title : The title of the web map server.
• wms_stylelist : Current style used.
• wms_style_%s_legendurl_width : Width of an image describing the style. %s = the name of the style.
• wms_style_%s_legendurl_height : Height of an image describing the style. %s = the name of the style.
• wms_style_%s_legendurl_format : Format of an image describing the style. %s = the name of the style.
• wms_style_%s_legendurl_href : Location of an image describing the style. %s = the name of the style.
• wms_style_%s_sld : URL to the SLD document of this style. %s = the name of the style.
• wms_style_%s_sld_body : SLD_BODY document of this style. %s = the name of the style.
• wms_style_%s_title : Title of the layer. %s = the name of the style.
• wms_title : (Required) A human-readable name for this Layer.
1 MAP
2
3 NAME "mapcontext"
4 STATUS ON
5 SIZE 400 300
6 SYMBOLSET "../etc/symbols.txt"
7 EXTENT -180 -90 180 90
8 UNITS DD
9 SHAPEPATH "../data"
10 IMAGECOLOR 255 255 255
11 FONTSET "../etc/fonts.txt"
12
13
14 #
15 # Start of web interface definition
16 #
17 WEB
18 IMAGEPATH "/ms4w/tmp/ms_tmp/"
19 IMAGEURL "/ms_tmp/"
20 METADATA
21 "wms_abstract" "Demo for map context document. Blah blah..."
22 "wms_title" "Map Context demo" #### REQUIRED
23 END
24 END
25
26 PROJECTION
27 "init=epsg:4326"
28 END
29
30 #
31 # Start of layer definitions
32 #
33
34 LAYER
35 NAME "country_bounds"
36 TYPE RASTER
37 STATUS ON
38 CONNECTION "http://demo.mapserver.org/cgi-bin/wms?"
39 CONNECTIONTYPE WMS
40 METADATA
41 "wms_title" "World Country Boundaries" #### REQUIRED
42 "wms_onlineresource" "http://demo.mapserver.org/cgi-bin/wms?" #### REQUIRED
43 "wms_srs" "EPSG:4326"
44 "wms_name" "country_bounds"
45 "wms_server_version" "1.1.1"
46 "wms_format" "image/gif"
47 "wms_dimensionlist" "time,width"
48 "wms_dimension" "time"
49 "wms_dimension_time_unitsymbol" "t"
50 "wms_dimension_time_units" "ISO8601"
51 "wms_dimension_time_uservalue" "1310"
52 "wms_dimension_time_default" "1310"
53 "wms_dimension_time_multiplevalues" "1310,1410"
54 "wms_dimension_time_nearestvalue" "0"
55 END
56 END
57
1. The first thing to do is to save your mapfile using the saveMapContext function available from the
PHP/MapScript library. An example script is shown below:
<?php
if (!extension_loaded("MapScript")) dl(MODULE);
$oMap = ms_newMapObj("mapcontext.map");
$oMap->saveMapContext("mapcontext_output.xml");
?>
2. Scan the XML output to look for <!– WARNING: ... –> comments. Then make the necessary changes to fix
every warning that you encounter. At the end of this you should have a mapfile compatible with the Map Context
specification.
3. Now you can load your new Map Context document into an application using the loadMapContext function
from the PHP/MapScript library.
MapServer CGI allows you to load a map context through the use of a CONTEXT parameter, and you can point
this parameter to a locally stored context file or a context file accessible through a URL. For more information on
MapServer CGI see the CGI Reference.
There is a new cgi parameter called CONTEXT that is used to specify a local context file. The user can then use
MapServer to request a map using the following syntax:
http://localhost/mapserver.cgi?MODE=map&MAP=/path/to/mapfile.map&CONTEXT=
/path/to/contextfile.xml&LAYERS=layer_name1 layers_name2
Note: All layers created from a context file have their status set to ON. To be able to display layers, the user needs to
add the LAYERS argument in the URL.
The syntax of using a web accessible context file would be similar to accessing a local context file:
http://localhost/mapserver.cgi?MODE=map&MAP=/path/to/mapfile.map&CONTEXT=
http://URL/path/to/contextfile.xml&LAYERS=layers_name1 layer_name2
Due to security concerns loading a file from a URL is disabled by default. To enable this functionality, the user needs
to set a CONFIG parameter called CGI_CONTEXT_URL in the default mapfile that will allow this functionality. Here
is an example of a map file with the CONFIG parameter:
END
Default Mapfile
To smoothly run a MapServer CGI application with a Map Context, the application administrator needs to provide a
default mapfile with at least the basic required parameters that will be used with the Context file. This default mapfile
can contain as little information as the imagepath and imageurl or contain a list of layers. Information coming from
the context (e.g.: layers, width, height, ...) would either be appended or will replace values found in the mapfile.
Here is an example of a default map file containing the minimum required parameters:
1 NAME "CGI-CONTEXT-DEMO"
2 STATUS ON
3 SIZE 400 300
4 EXTENT -2200000 -712631 3072800 3840000
5 UNITS METERS
6 IMAGECOLOR 255 255 255
7 IMAGETYPE png
8 #
9 # Start of web interface definition
10 #
11 WEB
12 MINSCALE 2000000
13 MAXSCALE 50000000
14 #
15 # On Windows systems, /tmp and /tmp/ms_tmp/ should be created at the root
16 # of the drive where the .MAP file resides.
17 #
18 IMAGEPATH "/ms4w/tmp/ms_tmp/"
19 IMAGEURL "/ms_tmp/"
20 END
21 END # Map File
MapServer can also output your WMS layers as a Context document. MapServer extends the WMS standard by adding
a request=GetContext operation that allows you to retrieve a context for a WMS-based mapfile with a call like:
http://localhost/mapserver.cgi?map=/path/to/mapfile.map&service=WMS&
request=GetContext&version=1.1.0
Contents
• WFS Server
– Introduction
– Configuring your MapFile to Serve WFS layers
– Reference Section
– To-do Items and Known Limitations
9.5.1 Introduction
A WFS ( Web Feature Service ) publishes feature-level geospatial data to the web. This means that instead of re-
turning an image, as MapServer has traditionally done, the client now obtains fine-grained information about specific
geospatial features of the underlying data, at both the geometry AND attribute levels. As with other OGC specifica-
tions, this interface uses XML over HTTP as it’s delivery mechanism, and, more precisely, GML (Geography Markup
Language), which is a subset of XML.
WFS-Related Information
Here are some WFS related links (including a newly added OGC services workshop with MapServer). Since these
are highly detailed technical specifications, there is no need to read through them in their entirety to get a MapServer
WFS up and running. It is still recommended however to read them over and get familiar with the basics of each of
them, in order to understand how it all works:
• The OGC Web Feature Service Implementation Specification.
• The Geography Markup Language Implementation Specification.
• MapServer OGC Web Services Workshop package.
Working knowledge of MapServer is of course also required.
Software Requirements
In order to enable MapServer to serve WFS, it MUST be compiled against certain librairies:
• PROJ.4: The reprojection library. Version 4.4.3 or greater is required.
• GDAL/OGR: I/O support libraries. Version 1.1.8 or greater is required.
Please see the MapServer UNIX Compilation and Installation HowTo for detailed instructions on compiling mapserver
with support for these libraries and features. For Windows users, the MS4W installer comes ready to serve both WFS
and WMS.
MapServer can output both GML2 and GML3. By default MapServer serves GML2. You can test this by adding an
‘OUTPUTFORMAT’ parameter to a GetFeature request, such as:
• GML2 request output
• GML3 request output
For a detailed discussion on the versions supported, see bug#884.
Much as in the WMS support, WFS publishing is enabled by adding certain magic METADATA keyword/value pairs
to a MapFile.
MapServer will serve and include in its WFS capabilities only the layers that meet the following conditions:
• Data source is of vector type (Shapefile, OGR, PostGIS, SDE, SDO, ...)
• LAYER NAME must be set. Layer names must start with a letter when setting up a WFS server (layer names
should not start with a digit or have spaces in them).
• LAYER TYPE is one of: LINE, POINT, POLYGON
• LAYER DUMP parameter set to TRUE
• The “wfs_onlineresource” metadata:
The wfs_onlineresource metadata is set in the map’s web object metadata and specifies the URL that should be
used to access your server. This is required for the GetCapabilities output. If wfs_onlineresource is not provided
then MapServer will try to provide a default one using the script name and hostname, but you shouldn’t count
on that too much. It is strongly recommended that you provide the wfs_onlineresource metadata.
See section 12.3.3 of the WFS 1.0.0 specification for the whole story about the online resource URL. Basically,
what you need is a complete HTTP URL including the http:// prefix, hostname, script name, potentially a
“map=” parameter, and and terminated by “?” or “&”.
Here is a valid online resource URL:
http://my.host.com/cgi-bin/mapserv?map=mywfs.map&
By creating a wrapper script on the server it is possible to hide the “map=” parameter from the URL and then
your server’s online resource URL could be something like:
http://my.host.com/cgi-bin/mywfs?
This is covered in more detail in the “More About the Online Resource URL” section of the WMS Server
document.
The following is an example of a bare minimum WFS Server mapfile. Note the comments for the required parameters.
MAP
NAME "WFS_server"
STATUS ON
SIZE 400 300
SYMBOLSET "../etc/symbols.txt"
EXTENT -180 -90 180 90
UNITS DD
SHAPEPATH "../data"
IMAGECOLOR 255 255 255
FONTSET "../etc/fonts.txt"
#
# Start of web interface definition
#
WEB
IMAGEPATH "/ms4w/tmp/ms_tmp/"
IMAGEURL "/ms_tmp/"
METADATA
"wfs_title" "WFS Demo Server for MapServer" ## REQUIRED
"wfs_onlineresource" "http://demo.mapserver.org/cgi-bin/wfs?" ## Recommended
"wfs_srs" "EPSG:4326 EPSG:4269 EPSG:3978 EPSG:3857" ## Recommended
"wfs_abstract" "This text describes my WFS service." ## Recommended
END
END
PROJECTION
"init=epsg:4326"
END
#
# Start of layer definitions
#
##################
# World Continents
##################
LAYER
NAME "continents"
METADATA
"wfs_title" "World continents" ##REQUIRED
"wfs_srs" "EPSG:4326" ## REQUIRED
"gml_include_items" "all" ## Optional (serves all attributes for layer)
"gml_featureid" "ID" ## REQUIRED
END
TYPE POLYGON
STATUS ON
DATA ’shapefile/countries_area’
PROJECTION
"init=epsg:4326"
END
DUMP TRUE ## REQUIRED
CLASS
NAME ’World Continents’
STYLE
COLOR 255 128 128
OUTLINECOLOR 96 96 96
END
END
END #layer
END #mapfile
Contrary to WMS, the OGC WFS specification doesn’t allow a layer (feature type) to be advertised in more than one
SRS. Also, there is no default SRS that applies to all layers by default in the OGC WFS spec. However, it is possible
to have every layer in a WFS server advertised in a different SRS.
Here is how MapServer decides the SRS to advertise and use for each layer in your WFS:
• If a top-level map SRS is defined* then this SRS is used and applies to all layers (feature types) in this WFS. In
this case the SRS of individual layers is simply ignored even if it’s set.
• If there is no top-level map SRS defined* then each layer is advertised in its own SRS in the capabilities.
• By “SRS is defined”, we mean either the presence of a PROJECTION object defined using an EPSG code, or of
a “wfs_srs” metadata at this level.
Note that at the map top-level the “wfs_srs” metadata value takes precedence over the contents of the PROJECTION
block.
At the layer level, if both the wfs_srs metadata and the PROJECTION object are set to different values, then the
wfs_srs metadata defines the projection to use in advertising this layer (assuming there is no top-level map SRS), and
the PROJECTION value is assumed to be the projection of the data. So this means that the data would be reprojected
from the PROJECTION SRS to the one defined in the wfs_srs metadata before being served to WFS clients.
Confusing? As a rule of thumb, simply set the wfs_srs at the map level (in web metadata) and never set the wfs_srs
metadata at the layer level and things will work fine for most cases.
The axis order in previous versions of the WFS specifications was to always use easting (x or lon ) and northing (y or
lat). WMS 1.1 specifies that, depending on the particular SRS, the x axis may or may not be oriented West-to-East, and
the y axis may or may not be oriented South-to-North. The WFS portrayal operation shall account for axis order. This
affects some of the EPSG codes that were commonly used such as ESPG:4326. The current implementation makes
sure that coordinates returned to the server for the GetFeature request reflect the inverse axis orders for EPSG codes
between 4000 and 5000.
OK, now that we’ve got a mapfile, we have to check the XML capabilities returned by our server to make sure nothing
is missing.
Using a web browser, access your server’s online resource URL to which you add the parameter “RE-
QUEST=GetCapabilities” to the end, e.g.
http://demo.mapserver.org/cgi-bin/wfs?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetCapabilities
If everything went well, you should have a complete XML capabilities document. Search it for the word “WARN-
ING”... MapServer inserts XML comments starting with “<!–WARNING: ” in the XML output if it detects missing
mapfile parameters or metadata items. If you notice any warning in your XML output then you have to fix all of them
before you can register your server with a WFS client, otherwise things are likely not going to work.
Note that the SERVICE parameter is required for all WFS requests. When a request happens, it is passed through
WMS, WFS, and WCS in MapServer (in that order) until one of the services respond to it.
OK, now that we know that our server can produce a valid XML GetCapa-
bilities response we should test the GetFeature request. Simply adding “SER-
VICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME=yourlayername1,yourlayername2” to
your server’s URL should return the GML associated with those layers.
http://demo.mapserver.org/cgi-bin/wfs?SERVICE=WFS&VERSION=1.0.0&REQUEST=getfeature&TYPENAME=continents&MAXF
If you have access to a WFS client, then register your new server’s online resource with it and you should be off and
running.
If you don’t have your own WFS client installed already, here are a few pointers:
• MapServer itself can be used as a WFS client, see the WFS Client HowTo.
• Quantum GIS is a full GIS package which includes WFS client support. (recommended)
• Deegree provides a WFS client.
• uDig can add layers from WMS/WFS servers.
• The owsview Viewer Client Generator is an online application that allows users to validate WFS Capabilities
XML (it does not allow you to view WFS data).
Starting from version 4.2 MapServer supports XML-encoded POST requests and GET requests. The default in
MapServer is POST.
Starting from version 4.2 MapServer supports Filter Encoding (FE) in WFS GetFeature requests. For more information
on the server side of Filter Encoding see the Filter Encoding HowTo.
STARTINDEX In addition to the MAXFEATURES=n keyword, MapServer also supports a STARTINDEX=n key-
word in WFS GetFeature requests. This can be used to skip some features in the result set and in combination
with MAXFEATURES provides for the ability to use WFS GetFeature to page through results. Note that
STARTINDEX=1 means start with the first feature, skipping none.
OUTPUTFORMAT Normally OUTPUTFORMAT should be GML2 for WFS 1.0 and either “text/xml; sub-
type=gml/2.1.2” or “text/xml; subtype=gml/3.1.1” for WFS 1.1. However as an extension to the specification, it
is also possible to configure MapServer for a variety of other feature output formats. This is discussed in some
detail in the OGR Output document.
The following metadata are available in the setup of the WFS Server mapfile:
Note
Each of the metadata below can also be referred to as ‘ows_*’ instead of ‘wfs_*’. MapServer tries the ‘wfs_*’
metadata first, and if not found it tries the corresponding ‘ows_*’ name. Using this reduces the amount of duplication
in mapfiles that support multiple OGC interfaces since “ows_*” metadata can be used almost everywhere for common
metadata items shared by multiple OGC interfaces.
ows_updatesequence
• Description: (Optional) The updateSequence parameter can be used for maintaining the consistency of a client
cache of the contents of a service metadata document. The parameter value can be an integer, a timestamp in
[ISO 8601:2000] format, or any other number or string.
ows_schemas_location
• Description: (Optional) (Note the name ows_schemas_location and not wfs/_... this is because all OGC Web
Services (OWS) use the same metadata) Root of the web tree where the family of OGC WFS XMLSchema files
are located. This must be a valid URL where the actual .xsd files are located if you want your WFS output to
validate in a validating XML parser. Default is http://schemas.opengis.net. See http://ogc.dmsolutions.ca for an
example of a valid schema tree.
wfs_abstract
• WFS TAG Name: Abstract (WFS 1.0.0, sect. 12.3.3)
• Description: (Optional) Descriptive narrative for more information about the server.
wfs_accessconstraints
• WFS TAG Name: Accessconstraints (WFS 1.0.0, sect. 12.3.3)
• Description: (Optional) Text describing any access constraints imposed by the service provider on the WFS or
data retrieved from this service.
wfs_encoding
• Description: (Optional) XML encoding for all XML documents returned by the server. The default is ISO-
8859-1.
wfs_fees
• WFS TAG Name: Fees (WFS 1.0.0, sect. 12.3.3)
• Description: (Optional) Any fees imposed by the service provider for usage of this service or for data retrieved
from the WFS.
wfs_getcapabilities_version
• Description: (Optional) Default version to use for GetCapabilities requests that do not have a version parameter.
If not set, the latest supported version will be returned.
wfs_keywordlist
• WFS TAG Name: Keyword (WFS 1.0.0, sect. 12.3.3)
• Description: (Optional) List of words to aid catalog searching.
wfs_maxfeatures
• Description: (Optional) The number of elements to be returned by the WFS server. This has priority over the
‘maxfeatures’ parameter passed by the user. If the not set the current behaviour is not changed.
wfs_namespace_prefix
• Description: (Optional) User defined namespace prefix to be used in the response of a WFS GetFeature request.
e.g. “wfs_namespace_prefix” “someprefix”.
wfs_namespace_uri
• Description: (Optional) User defined namespace URI to be used in the response of a WFS GetFeature request.
e.g. “wfs_namespace_uri” “http://somehost/someurl“.
wfs_onlineresource
• WFS TAG Name: Onlineresource (WFS 1.0.0, sect. 12.3.3)
• Description: (Recommended) The URL prefix for HTTP GET requests.
wfs_service_onlineresource
• Description: (Optional) Top-level onlineresource URL. MapServer uses the onlineresource metadata (if pro-
vided) in the following order:
1. wfs_service_onlineresource
2. ows_service_onlineresource
3. wfs_onlineresource (or automatically generated URL, see the onlineresource section of this document)
wfs_title
• WFS TAG Name: Title (WFS 1.0.0, sect. 12.3.3)
• Description: (Required) Human readable title to identify server.
wfs_srs
• Description: (Recommended) The SRS to use for all layers in this server. (e.g. EPSG:4326) See the notes below
about the SRS rules in the WFS.
wfs_feature_collection
• Description: Replaces the default name of the feature-containing element (<msFeatureCollection>) with a user-
defined value.
Layer Object
gml_exclude_items
• Description: (Optional) A comma delimited list of items to exclude. As of MapServer 4.6, you can control how
many attributes (fields) you expose for your data layer with metadata. The previous behaviour was simply to
expose all attributes all of the time. The default is to expose no attributes at all. An example excluding a specific
field would be:
"gml_include_items" "all"
"gml_exclude_items" "Phonenum"
gml_featureid
• Description: (Required for MapServer 4.10) Field to be used for the ID of the feature in the output GML.
wfs_featureid or ows_feature_id can be specified instead.
gml_groups
• Description: (Optional) A comma delimited list of group names for the layer.
gml_[group name]_group
• Description: (Optional) A comma delimited list of attributes in the group. Here is an example:
"gml_include_items" "all"
"gml_groups" "display"
"gml_display_group" "Name_e,Name_f"
gml_include_items
• Description: (Optional) A comma delimited list of items to include, or keyword “all”. As of MapServer 4.6,
you can control how many attributes (fields) you expose for your data layer with this metadata. The previous
behaviour was simply to expose all attributes all of the time. You can enable full exposure by using the keyword
“all”, such as:
"gml_include_items" "all"
You can specify a list of attributes (fields) for partial exposure, such as:
"gml_include_items" "Name,ID"
gml_[item name]_type
• Description: (Optional) Specifies the type of the attribute. Valid values are Integer|Real|Character|Date|Boolean.
gml_[item name]_width (Optional) Specifies the width of the indicated field for formats where this is significant,
such as Shapefiles.
gml_[item name]_precision (Optional) Specifies the precision of the indicated field for formats where this is sig-
nificant, such as Shapefiles. Precision is the number of decimal places, and is only needed for “Real” fields.
Currently this is only used for OGR based output formats, not the WFS GML2/GML3 output.
gml_types (Optional) If this field is “auto” then some input feature drivers (ie. OGR, POSTGIS, ORACLESPATIAL
and native shapefiles) will automatically populate the type, width and precision metadata for the layer based on
the source file. Currently this is only used for OGR based output formats, not the WFS GML2/GML3 output.
"gml_types" "auto"
gml_xml_items
• Description: (Optional) A comma delimited list of items that should not be XML-encoded.
gml_geometries
• Description: provides a name other than the default “msGeometry” for geometry elements. The value is speci-
fied as a string to be used for geometry element names.
gml_[name]_type
• Description: When employing gml_geometries, it is also necessary to specify the geometry type of the layer.
This is accomplished by providing a value for gml_[name]_type, where [name] is the string value specified for
gml_geometries, and a value which is one of:
– point
– multipoint
– line
– multiline
– polygon
– multipolygon
gml_[name]_occurances
• Description: MapServer applies default values of 0 and 1, respectively, to the “minOccurs” and “maxOccurs”
attributes of geometry elements, as can be seen in the preceding examples. To override these defaults, a value is
assigned to a gml_[name]_occurances layer metadata item, where again [name] is the string value specified for
gml_geometries, and the value is a comma-delimited pair containing the respective lower and upper bounds.
wfs_abstract
• Same as wfs_abstract in the Web Object.
wfs_extent
• Description: (Optional) Used for the layer’s BoundingBox tag for cases where it is impossible (or very ineffi-
cient) for MapServer to probe the data source to figure its extents. The value for this metadata is “minx miny
maxx maxy” separated by spaces, with the values in the layer’s projection units. If wfs_extent is provided then
it has priority and MapServer will NOT try to read the source file’s extents.
wfs_featureid
• Description: (Required for MapServer 4.10) Field to be used for the ID of the feature in the output GML.
gml_featureid or ows_feature_id can be specified instead.
wfs_getfeature_formatlist
• Description: (Optional) Comma-separted list of formats that sould be valid for a GetFeature request. If defined,
only these formats are advertised through in the Capabilities document.
wfs_keywordlist
• Same as wfs_keywordlist in the Web Object.
wfs_metadataurl_format
• Description: (Optional) The file format of the metadata record. Valid values are “XML”, “SGML”, or “HTML”.
The layer metadata wfs_metadataurl_type and wfs_metadataurl_href must also be specified.
• refer to section 12.3.5 of the WFS 1.0.0 spec.
wfs_metadataurl_href
• Description: (Optional) The URL to the layer’s metadata. The layer metadata wfs_metadataurl_type and
wfs_metadataurl_format must also be specified.
• refer to section 12.3.5 of the WFS 1.0.0 spec.
wfs_metadataurl_type
• Description: (Optional) The standard to which the metadata complies. Currently only two types are valid:
“TC211” which refers to [ISO 19115], and “FGDC” which refers to [FGDC CSDGM]. The layer metadata
wfs_metadataurl_format and wfs_metadataurl_href must also be specified.
• refer to section 12.3.5 of the WFS 1.0.0 spec.
wfs_srs
• Description: If there is no SRS defined at the top-level in the mapfile then this SRS will be used to advertize
this feature type (layer) in the capabilities. See the note below about the SRS rules in the WFS.
wfs_title
• Same as wfs_title in the Web Object.
• This is just a basic WFS (read-only): transaction requests are not supported and probably never will given the
nature of MapServer. GeoServer or TinyOWS is recommended for those needing WFS-T support.
• WFS spec. seems to require that features of a given feature type must all be of the same geometry type (point,
line, polygon). This works fine for shapefiles, but some data source formats supported by MapServer allow
mixed geometry types in a single layer and this goes against the WFS spec. Suggestions on how to handle this
are welcome (send suggestions to the mapserver-dev mailing list.
Contents
• WFS Client
– Introduction
– Setting up a WFS-client Mapfile
– TODO / Known Limitations
9.6.1 Introduction
MapServer can retrieve and display data from a WFS server. The following document explains how to display data
from a WFS server using MapServer.
A WFS ( Web Feature Service ) publishes feature-level geospatial data to the web. This means that it is possible to
use this data as a data source to render a map. In effect, this is not unlike having a shapefile accessible over the web,
only it’s not a shapefile, it’s XML-Encoded geospatial data (GML to be exact), including both geometry AND attribute
information.
WFS-Related Information
Although in-depth understanding of WFS and GML is neither necessary nor required in order to implement a
MapServer application that reads remote WFS data, it is recommended to at least get aquainted with the concepts and
basic functionality of both. Here are the official references (including a newly added OGC workshop with MapServer):
• OGC Web Feature Service Implementation Specification.
• Geography Markup Language Implementation Specification.
• MapServer OGC Web Services Workshop package.
Software Requirements
In order to enable MapServer to serve WFS, it MUST be compiled against certain libraries:
• PROJ.4: The reprojection library. Version 4.4.3 or greater is required.
• GDAL/OGR: I/O support librairies. Version 1.1.8 or greater is required.
• LibCURL: Used to help MapServer act as an HTTP client. Version 7.10 or greater is required.
Please see the MapServer UNIX Compilation and Installation HOWTO for detailed instructions on compiling
mapserver with support for these librairies and features. For Windows users, look on the MapServer website to
see if there are any binaries available that meet these requirements.
You must set the IMAGEPATH parameter in your mapfile since MapServer uses this directory to store temporary
files downloaded from the remote WFS server. Windows users must specify a full path for IMAGEPATH, such as:
IMAGEPATH “C:/tmp/ms_tmp/”
MAP
...
WEB
IMAGEPATH "/tmp/ms_tmp/"
IMAGEURL ...
END
...
END
WFS Layer
A WFS layer is a regular mapfile layer, which can use CLASS objects, with expressions, etc.
As of MapServer 4.4, the suggested method to define a WFS Client layer is through the CONNECTION parameter
and the layer’s METADATA. The necessary mapfile parameters are defined below:
• CONNECTIONTYPE: must be “wfs”
• CONNECTION: The URL to the WFS Server. e.g. http://demo.mapserver.org/cgi-bin/wfs? The
path to the mapfile on the WFS server is required if it was required in the GetCapabilities re-
quest e.g. you would have to specify the MAP parameter in the CONNECTION for the following
server: http://map.ns.ec.gc.ca/MapServer/mapserv.exe?MAP=/mapserver/services/envdat/config.map &SER-
VICE=WFS&VERSION=1.0.0&REQUEST=GetCapabilities
• METADATA: The LAYER’s must contain a METADATA object with the following parameters:
– wfs_connectiontimeout (optional): The maximum time to wait for a remote WFS layer to load, set in
seconds (default is 30 seconds). This metadata can be added at the layer level so that it affects only that
layer, or it can be added at the map level (in the web object) so that it affects all of the layers. Note that
wfs_connectiontimeout at the layer level has priority over the map level.
– wfs_filter: This can be included to include a filter encoding parameter in the getFeature request (see the
Filter Encoding Howto for more information on filtering). The content of the wfs_filter is a valid filter
encoding element.
...
METADATA
"wfs_filter" "<PropertyIsGreaterThan><PropertyName>POP_RANGE</PropertyName><Literal>
</ L i t e r a l ></ P r o p e r t y I s G r e a t e r T h a n >"
END
...
– wfs_latlongboundingbox (optional): The bounding box of this layer in geographic coordinates in the for-
mat “lon_min lat_min lon_max lat_max”. If it is set then MapServer will request the layer only when the
map view overlaps that bounding box. You normally get this from the server’s capabilities output.
– wfs_maxfeatures (optional): Limit the number of GML features to return.
– wfs_request_method (optional): Can be set to “GET” to do a Get request to WFS servers that do not
support Post requests. The default method in MapServer is Post.
...
METADATA
"wfs_filter" "GET"
END
...
LAYER
NAME "continents"
TYPE POLYGON
STATUS ON
CONNECTION "http://demo.mapserver.org/cgi-bin/wfs?"
CONNECTIONTYPE WFS
METADATA
"wfs_typename" "continents"
"wfs_version" "1.0.0"
"wfs_connectiontimeout" "60"
"wfs_maxfeatures" "10"
END
PROJECTION
"init=epsg:4326"
END
CLASS
NAME "Continents"
STYLE
COLOR 255 128 128
OUTLINECOLOR 96 96 96
END
END
END # Layer
Connection - deprecated
As of MapServer v4.4 the method of specifying all of the connection information in the CONNECTION parameter has
beendeprecated. The preferred method is mentioned above. If the metadata is not provided, VERSION, SERVICE,
and TYPENAME will be fetched from the CONNECTION, as shown below
CONNECTION "http://demo.mapserver.org/cgi-bin/wfs?SERVICE=WFS&VERSION=1.0.0&TYPENAME=continents"
1. Temporary WFS (gml) files are written to the IMAGEPATH directory, but this could become a security concern
since it makes the raw GML data downloadable by someone who could guess the gml filename. We should
consider having a “wfs_cache_dir” metadata that, if it is set will define a directory where temp files should be
written. The default would still be to use the value of IMAGEPATH if “wfs_tmpdir” is not set.
Table of Contents
• WFS Filter Encoding
– Introduction
– Currently Supported Features
– Get and Post Requests
– Use of Filter Encoding in MapServer
– Limitations
– Tests
9.7.1 Introduction
This document describes the procedures for taking advantage of the Filter Encoding (FE) support in WFS GetFeature
requests, which was added to MapServer in version 4.2.
This document assumes that you are already familiar with the following aspects of MapServer:
• MapServer application development and setting up .map files.
• Familiarity with the WFS specification would be an asset. Links to the MapServer WFS documents are included
in the next section.
The following table lists the currently supported features for FE.
Table 1. Currently Supported Features
Feature Set Feature
Spatial Capabilities
Equals
Disjoint
Touches
Within
Overlaps
Crosses
Intersects
Contains
DWithin
BBOX
Scalar Capabilities
Logical Operators
And
Or
Not
Comparison Operators
PropertyIsEqualTo (=)
PropertyIsNotEqualTo (<>)
PropertyIsLessThan (<)
PropertyIsGreaterThan (>)
PropertyIsLessThanOrEqualTo (<=)
PropertyIsGreaterThanOrEqualTo (>=)
PropertyIsLike
PropertyIsBetween (range)
MapServer already has the capability to receive and parse Get requests and URL-encoded Post requests. The ability
for MapServer to be able to receive Post requests with XML-encoded information sent in the body of the request has
been added. Also, the ability to generate XML-encoded Post requests for WFS layers has been added.
Both Get and Post request are now supported for all WFS requests:
• GetCapabilities
• GetFeatures
• DescribeFeatureType
Supporting these WFS requests in Post was implemented to keep consistency between all supported WFS requests.
When sending requests, the default request method used is Post. To change this behavior, we have introduced a layer
level meta data, wfs_request_method, which can be set to “GET”.
This section describes how to use FE on both the server and client sides.
Server Side
To be able to use Filter Encoding, you need to create a valid WFS server using MapServer. Please refer to the WFS
Server HOWTO for specifics.
There is nothing special that should be added to a WFS server for Filter Encoding, but you should note that, when
requesting the capabilities of your WFS server, the document returned should contain the supported filters. Here is
part of a Capabilities document (note the “Filter_Capabilities” section):
1 <?xml version="1.0" encoding="ISO-8859-1"?>
2 <WFS_Capabilities version="1.0.0" updateSequence="0" xmlns="http://www.opengis.net/wfs" xmlns:ogc
3
4 <!-- MapServer version 5.6.5 OUTPUT=GIF OUTPUT=PNG OUTPUT=JPEG OUTPUT=WBMP OUTPUT=SWF OUTPUT=SVG
5
6 <Service>
7 <Name>MapServer WFS</Name>
8 <Title>WMS Demo Server for MapServer</Title>
9 <Abstract>This demonstration server showcases MapServer (www.mapserver.org) and its OGC support
10 <OnlineResource>http://demo.mapserver.org/cgi-bin/wfs?</OnlineResource>
11 </Service>
12
13 <Capability>
14 <Request>
15 <GetCapabilities>
16 <DCPType>
17 <HTTP>
18 <Get onlineResource="http://demo.mapserver.org/cgi-bin/wfs?"/>
19 </HTTP>
20 </DCPType>
21 <DCPType>
22 <HTTP>
23 <Post onlineResource="http://demo.mapserver.org/cgi-bin/wfs?"/>
24 </HTTP>
25 </DCPType>
26 </GetCapabilities>
27 ...
28 </Request>
29 </Capability>
30 ...
31 <ogc:Filter_Capabilities>
32 <ogc:Spatial_Capabilities>
33 <ogc:Spatial_Operators>
34 <ogc:Equals/>
35 <ogc:Disjoint/>
36 <ogc:Touches/>
37 <ogc:Within/>
38 <ogc:Overlaps/>
39 <ogc:Crosses/>
40 <ogc:Intersect/>
41 <ogc:Contains/>
42 <ogc:DWithin/>
43 <ogc:BBOX/>
44 </ogc:Spatial_Operators>
45 </ogc:Spatial_Capabilities>
46 <ogc:Scalar_Capabilities>
47 <ogc:Logical_Operators/>
48 <ogc:Comparison_Operators>
49 <ogc:Simple_Comparisons/>
50 <ogc:Like/>
51 <ogc:Between/>
52 </ogc:Comparison_Operators>
53 </ogc:Scalar_Capabilities>
54 </ogc:Filter_Capabilities>
55
56 </WFS_Capabilities>
Client Side
To be able to generate a Filter to a WFS server, a layer level metadata called wfs_filter has been added, which should
contain the filter to be sent to the server. Following is an example of a valid WFS client layer with a filter:
LAYER
NAME "cities"
TYPE POINT
STATUS ON
CONNECTION "http://demo.mapserver.org/cgi-bin/wfs?"
CONNECTIONTYPE WFS
METADATA
"wfs_typename" "cities"
"wfs_version" "1.0.0"
"wfs_connectiontimeout" "60"
"wfs_maxfeatures" "100"
"wfs_filter" "<PropertyIsGreaterThan><PropertyName>POPULATION</PropertyName>
< L i t e r a l >10000000</ L i t e r a l ></ P r o p e r t y I
END
PROJECTION
"init=epsg:4326"
END
LABELITEM ’NAME’
DUMP TRUE
CLASS
NAME ’World Cities’
STYLE
COLOR 255 128 128
OUTLINECOLOR 128 0 0
SYMBOL ’circle’
SIZE 9
END
LABEL
COLOR 0 0 0
OUTLINECOLOR 255 255 255
TYPE TRUETYPE
FONT s a n s
SIZE 7
POSITION UC
PARTIALS FALSE
END
END
END
Note:
• The filter given as a value of the wfs_filter metadata should not contain <Filter> start and end tags.
• The CONNECTION points to a valid WFS server supporting filters
• The returned shapes will be drawn using the class defined in the layer.
9.7.5 Limitations
9.7.6 Tests
Here are some test URLs for the different supported filters:
• PropertyIsEqualTo
http://demo.mapserver.org/cgi-bin/wfs?&VERSION=1.0.0&SERVICE=WFS&REQUEST=GetFeature&
TYPENAME=cities&Filter=<Filter><PropertyIsEqualTo><PropertyName>NAME</PropertyName>
<Literal>Halifax</Literal></PropertyIsEqualTo></Filter>
• PropertyIsNotEqualTo
http://demo.mapserver.org/cgi-bin/wfs?&VERSION=1.0.0&SERVICE=WFS&REQUEST=GetFeature&
TYPENAME=cities&Filter=<Filter><PropertyIsNotEqualTo><PropertyName>NAME</PropertyName>
<Literal>Halifax</Literal></PropertyIsNotEqualTo></Filter>
• PropertyIsLessThan
http://demo.mapserver.org/cgi-bin/wfs?&VERSION=1.0.0&SERVICE=WFS&REQUEST=GetFeature&
TYPENAME=cities&Filter=<Filter><PropertyIsLessThan><PropertyName>POPULATION</PropertyName>
<Literal>1000</Literal></PropertyIsLessThan></Filter>
• PropertyIsGreaterThan
http://demo.mapserver.org/cgi-bin/wfs?&VERSION=1.0.0&SERVICE=WFS&REQUEST=GetFeature&
TYPENAME=cities&Filter=<Filter><PropertyIsGreaterThan><PropertyName>POPULATION</PropertyName>
<Literal>10000000</Literal></PropertyIsGreaterThan></Filter>
• PropertyIsLessThanOrEqualTo
http://demo.mapserver.org/cgi-bin/wfs?&VERSION=1.0.0&SERVICE=WFS&REQUEST=GetFeature&
TYPENAME=cities&Filter=<Filter><PropertyIsLessThanOrEqualTo><PropertyName>POPULATION</PropertyName>
<Literal>499</Literal></PropertyIsLessThanOrEqualTo></Filter>
• PropertyIsGreaterThanOrEqualTo
http://demo.mapserver.org/cgi-bin/wfs?&VERSION=1.0.0&SERVICE=WFS&REQUEST=GetFeature&
TYPENAME=cities&Filter=<Filter><PropertyIsGreaterThanOrEqualTo><PropertyName>POPULATION</PropertyName
<Literal>10194978</Literal></PropertyIsGreaterThanOrEqualTo></Filter>
• PropertyIsBetween
http://demo.mapserver.org/cgi-bin/wfs?&VERSION=1.0.0&SERVICE=WFS&REQUEST=GetFeature&
TYPENAME=cities&Filter=<Filter><PropertyIsBetween><PropertyName>POPULATION</PropertyName>
<LowerBoundary>10194978</LowerBoundary><UpperBoundary>12116379</UpperBoundary></PropertyIsBetween></F
• PropertyIsLike
http://demo.mapserver.org/cgi-bin/wfs?&VERSION=1.0.0&SERVICE=WFS&REQUEST=GetFeature&
TYPENAME=cities&Filter=<Filter><PropertyIsLike wildcard=’*’ singleChar=’.’ escape=’!’>
<PropertyName>NAME</PropertyName><Literal>Syd*</Literal></PropertyIsLike></Filter>
• Logical operator OR
http://demo.mapserver.org/cgi-bin/wfs?&VERSION=1.0.0&SERVICE=WFS&REQUEST=GetFeature&
TYPENAME=cities&Filter=<Filter><OR><PropertyIsEqualTo><PropertyName>NAME</PropertyName>
<Literal>Sydney</Literal></PropertyIsEqualTo><PropertyIsEqualTo><PropertyName>NAME</PropertyName>
<Literal>Halifax</Literal></PropertyIsEqualTo></OR></Filter>
• The OGC conformance tests (http://cite.opengeospatial.org/test_engine) have been run on the FE support. The
following table and notes reflect the current status.
Table 2. WFS OGC test suite (over the HTTP Get and Post method)
Test # Description # of Tests # of Failed Tests
1 Basic WFS tests over the HTTP Get and Post method 402 281
1.1 GetCapabilities 16 0
1.2 DescribeFeatureType 18 0
1.3 GetFeature 368 281
1.3.1 Basic WFS tests 20 1
1.3.2 Complex WFS tests 18 18
1.3.3 Arithmetic filter WFS tests 8 8
1.3.4 Comparison WFS tests 50 26
1.3.4.1 GetFeature PropertyIsGreaterThanOrEqualTo filter 2 0
1.3.4.2 GetFeature PropertyIsBetween filter 6 2
1.3.4.3 GetFeature PropertyIsEqualTo filter 4 0
1.3.4.4 GetFeature PropertyIsGreaterThan filter 4 2
1.3.4.5 GetFeature PropertyIsGreaterThanOrEqualTo filter 6 6
1.3.4.6 GetFeature PropertyIsLessThan filter 6 4
1.3.4.7 GetFeature PropertyIsLessThanOrEqualTo filter 6 4
1.3.4.8 GetFeature PropertyIsLike filter 2 0
1.3.4.9 GetFeature PropertyIsNotEqualTo filter 6 0
1.3.4.10 GetFeature PropertyIsNull filter 8 8
1.3.5 Logical WFS test 20 0
1.3.5.1 GetFeature AND PropertyIsEqualTo PropertyIsEqualTo filter 8 0
1.3.5.2 GetFeature OR PropertyIsEqualTo PropertyIsEqualTo filter 8 0
1.3.5.3 GetFeature NOT PropertyIsNotEqualTo filter 4 0
1.3.6 Spatial operator WFS test 252 228
1.3.6.1 GetFeature BBOX filter 36 12
1.3.6.2 GetFeature with other filter types 216 216
2 Transactional WFS test 69 69
The OGC Cite WFS test suite can be found on the OGC Cite portal.
Following are some MapServer specific notes on this test suite:
1. Test number 1.3.1:
• There is a contradiction between the wfs/1.0.0/basic/getfeature/post/3 assertion and the XPath expected
value of the test. The assertion says: “Test that a GetFeature request with no output format de-
fined returns a wfs:FeatureCollection with GML data.” and the expected XPath value for this request:
“boolean(/ogc:ServiceExceptionReport)” is supposed to be true. So, the assertion means that when a WFS
server receives a request which contains an undefined output format or no output format at all, the WFS
server must return a WFS collection containing GML data. The XPath expected value means that when a
WFS server receives a request with an undefined output format or no output format at all, the WFS server
must return a service exception report.
2. Tests number 1.3.2 and 1.3.3:
• Not supported.
3. Tests number 1.3.4.2, 1.3.4.4 to 1.3.4.7:
• The string comparison is not supported using >, <, >=, <=.
• The date comparison is not supported.
See Also:
bug 461
4. Test number 1.3.4.10:
• This property is not supported in MapServer.
5. Test number 1.3.6.1:
• The returned feature xml won’t validate because the validation is done against a specific xsd (geoma-
try.xsd).
• The data conversion on multipoints and multilayers are not supported within GDAL.
See Also:
bug 461
6. Test number 2:
• The transaction requests are not supported.
9.8 SLD
Contents
• SLD
– Introduction
– Server Side Support
– Client Side Support
– Named Styles support
– Other Items Implemented
– Issues Found During Implementation
9.8.1 Introduction
This document describes the procedures for taking advantage of the Styled Layer Descriptor (SLD) support in WMS
GetMap requests with MapServer. SLD support exists for the server side (ability to read an SLD and apply it with a
GetMap request) and for the client side (includes sending SLD requests to server and generate SLD files on the fly
from MapServer map file). SLD support was added to MapServer in version 4.2.
This document assumes that you are already familiar with the following aspects of MapServer:
• MapServer application development and setting up .map files.
• Familiarity with the WMS specification would be an asset. Links to the MapServer WMS documents are in-
cluded in the next section.
General Information
There are two ways a WMS request can pass an SLD document with a GetMap request to MapServer:
• SLD parameter pointing to remote SLD (SLD=http://URL_TO_SLD).
• SLD_BODY parameter to send the SLD definition in the URL.
These two methods are both available through MapServer. An example of a request would be:
http://demo.mapserver.org/cgi-bin/wms?SERVICE=wms&VERSION=1.1.1&REQUEST=GetMap
&LAYERS=country_bounds&SLD=http://demo.mapserver.org/ogc-demos/map/sld/sld_line_simple.xml
When MapServer gets a valid SLD through a request, it parses this SLD to extract all the styles attached to the
NamedLayers, and then it applies these styles to the map before it is returned to the client. When applying the SLD,
MapServer compares the <Name> parameter of the NamedLayers in the SLD document to the WMS layer names
(WMS layer names are available in a GetCapabilities request).
Note: All the examples given in this document are live uses of valid SLDs and a MapServer installation with SLD
support.
Additional WMS features related to SLDs have also been developed:
Table1. Additional WMS Features
Features Supported Notes
Method GET : SLD URL Yes
Method GET : SLD_BODY Yes Additional item
Describer Layer Yes
GetLegendGraphic Yes
GetStyles Yes Uses MapScript to get the SLD
Note: As of MapServer version 4.2.3, the GetLegendGraphic request (see section 12 of the Styled Layer Descriptor
Implementation Specification) works as follows: if the RULE keyword is absent from the request, an image containing
the entire legend for the specified layer will be returned. This image consists of the layer name and a symbolization
graphic and label for each class.
The following tables give a lot of additional details about SLD support in MapServer.
Table2. Named Layers and User Layers
the offset values in the label object. SLD 1.1.0 introduces the IsAligned parameter for LinePlacement: if this
parameter is set to false, the angle will be set to 0.
The following are examples of valid requests using the TextSymbolizer:
• annotation layer : test for label, font, point placement, color, angle: sld 10a / full request 10a
• annotation layer with text and symbols using 2 symbolizers: sld 10b / full request 10b
Table 11. RasterSymbolizer
Features Supported Notes
Geometry No
Opacity Yes
ChannelSelection No
OverlapBehaviour No
ColorMap Yes
ContrastEnhancement No
ShadedRelief No
ImageOutline No
The current support in MapServer includes only ColorMap parameter support. It can be used to classify 8-bit rasters.
Inside the ColorMap parameters, the color and quantity parameters are extracted and used to do the classification.
Table 12. ColorMap
The following Features are available in SLD 1.0
Features Supported Notes
Color Yes
Opacity No
Quantity Yes
Label No
The following is an example of ColorMap usage for SLD 1.0.
If we have following ColorMap in an SLD:
<ColorMap>
<ColorMapEntry color="#00ff00" quantity="22"/>
<ColorMapEntry color="#00bf3f" quantity="30"/>
<ColorMapEntry color="#007f7f" quantity="37"/>
<ColorMapEntry color="#003fbf" quantity="45"/>
<ColorMapEntry color="#0000ff" quantity="52"/>
<ColorMapEntry color="#000000" quantity="60"/>
</ColorMap>
– wms_sld_body, which takes a valid SLD string and appends SLD_BODY=xxx to the GetMap request.
If the value of wms_sld_body is set to AUTO, MapServer generates an SLD based on the classes found in
the layer and send this SLD as the value of the SLD_BODY parameter in the GetMap request.
• The other major item is the generation of an SLD document from MapServer classes. These functions are
currently available through MapServer/MapScript interface. Here are the functions available:
– on a map object: generatesld
– on a layer object: generatesld
Additional MapScript functions have been added or will be added to complement these functions:
– on a map object: applysld
– on a layer object: applysld
Note: When generating an SLD from MapServer classes, if there is a pixmap symbol you need to have this symbol
available through a URL so it can be converted as an ExternalGraphic symbol in the SLD. To do this, you need to
define the URL through a web object level metadata called WMS_SLD_SYMBOL_URL in your map file. The SLD
generated uses this URL and concatenates the name of the pixmap symbol file to get the value that is generated as the
ExternaGraphic URL.
The following is a small script that calls the generateSLD() function to create an SLD for a specific layer in a mapfile:
1 <?php
2
3 // define variables
4 define( "MAPFILE", "D:/ms4w/apps/cadastra/map/cadastra.map" );
5 define( "MODULE", "php_mapscript.dll" );
6
10 // open map
11 $oMap = ms_newMapObj( MAPFILE );
12
24 ?>
Named styles support are introduced in MapServer 5.2. The support is base on MS RFC 39: Support of WMS/SLD
Named Styles
MapServer 5.2 introduces the possibility to assign a group to a series of classes defined on a layer object using two
new non-mandatory keywords CLASSGROUP (at the layer level) and GROUP at the class level:
LAYER
...
CLASSGROUP "group1"
...
CLASS
NAME "name1"
GROUP "group1"
...
END
CLASS
NAME "name2"
GROUP "group2"
...
END
CLASS
NAME "name3"
GROUP "group1"
...
END
...
At rendering time, if the CLASSGROUP is defined, only classes that have the same group name would be used.
Based on this concept, WMS/SLD support uses the class groups as named styles. Each group of classes is considered
equivalent to a named style:
• The GetCapbilities request will output all the styles that are available
• The GetMap request can use the STYLES parameter to specify a named style
• The GetLegendGraphic can use the STYLES parameter to specify a named style
• Limitation of the FilterEncoding to comparison and logical filters. The spatial filters were not made available
since it required major changes in MapServer WMS support.
Table of Contents
• WCS Server
– Introduction
– Configuring Your Mapfile to Serve WCS Layers
– Test Your WCS 1.0 Server
– WCS 1.1.0+ Issues
– WCS 2.0
– HTTP-POST support
– Reference Section
– Rules for handling SRS in a MapServer WCS
– Spatio/Temporal Indexes
– WCS 2.0 Application Profile - Earth Observation (EO-WCS)
– To-do Items and Known Limitations
9.9.1 Introduction
A WCS (or Web Coverage Service) allows for the publication of “coverages”- digital geospatial information repre-
senting space-varying phenomena. In the MapServer world it allows for unfiltered access to raster data. Conceptually
it is easy think of WCS as a raster equivalent of WFS. The following documentation is based on the Open Geospatial
Consortium’s (OGC) Web Coverage Service Interfaces Implementation Specification version 1.0.0.
Software Requirements
In order to enable MapServer to serve WCS data, it MUST be compiled against certain libraries:
• PROJ.4: The reprojection library. Version 4.4.3 or greater is required.
• GDAL: raster support library.
• MapServer: version >= 4.4 (tested with 5.0.2 while updating this document)
For WCS 1.1.x (MapServer 5.2) and WCS 2.0 (MapServer 6.0) support there is an additional requirement:
• libxml2: An xml parser and generation library.
Please see the MapServer UNIX Compilation and Installation HowTo for detailed instructions on compiling MapServer
with support for these libraries and features. For Windows users, MapServer for Windows (MS4W) comes with WCS
Server support.
Much as in the WMS and WFS support, WCS publishing is enabled by adding certain magic METADATA key-
word/value pairs to a .map file.
MapServer will serve and include in its WCS capabilities only the layers that meet the following conditions:
• Data source is a raster, which is processed using GDAL (e.g GeoTIFF, Erdas Imagine, ...)
• LAYER NAME must be set
• LAYER TYPE is set to RASTER
• LAYER DUMP parameter set to TRUE
• WEB metadata “wcs_label” must be set
• LAYER metadata “wcs_label” must be set
• LAYER metadata “wcs_rangeset_name” must be set
• LAYER metadata “wcs_rangeset_label” must be set
• LAYER is enabled to be served via WCS (see MS RFC 67)
The following is an example of a simple WCS Server mapfile. Note the comments for the required parameters.
NAME W C S _ s e r v e r
STATUS ON
SIZE 400 300
SYMBOLSET "../etc/symbols.txt"
EXTENT -2200000 -712631 3072800 3840000
UNITS METERS
SHAPEPATH "../data"
IMAGECOLOR 255 255 255
FONTSET "../etc/fonts.txt"
#
# Start of web interface definition
#
WEB
IMAGEPATH "/ms4w/tmp/ms_tmp/"
IMAGEURL "/ms_tmp/"
METADATA
"wcs_label" "GMap WCS Demo Server" ### required
"wcs_description" "Some text description of the service"
"wcs_onlineresource" "http://127.0.0.1/cgi-bin/mapserv.exe?" ### recommended
"wcs_fees" "none"
"wcs_accessconstraints" "none"
"wcs_keywordlist" "wcs,test"
"wcs_metadatalink_type" "TC211"
"wcs_metadatalink_format" "text/plain"
"wcs_metadatalink_href" "http://someurl.com"
"wcs_address" "124 Gilmour Street"
"wcs_city" "Ottawa"
"wcs_stateorprovince" "ON"
"wcs_postcode" "90210"
"wcs_country" "Canada"
"wcs_contactelectronicmailaddress" "blah@blah"
"wcs_contactperson" "me"
"wcs_contactorganization" "unemployed"
"wcs_contactposition" "manager"
"wcs_contactvoicetelephone" "613-555-1234"
"wcs_contactfacimiletelephone" "613-555-1235"
"wcs_service_onlineresource" "http://127.0.0.1/cgi-bin/mapserv.exe?"
END
END
PROJECTION
"init=epsg:42304"
END
LAYER
NAME b a t h y m e t r y
METADATA
"wcs_label" "Elevation/Bathymetry" ### required
"wcs_rangeset_name" "Range 1" ### required to support DescribeCoverage request
"wcs_rangeset_label" "My Label" ### required to support DescribeCoverage request
END
TYPE RASTER ### required
STATUS ON
DATA b a t h _ m a p s e r v e r . t i f
PROJECTION
"init=epsg:42304"
END
DUMP TRUE ### required
END
Output Formats
The raster formats supported by MapServer WCS are determined by the wcs_formats metadata item on the LAYER.
This should contain a space separated list of OUTPUTFORMAT driver names separated by spaces. If absent, all raster
OUTPUTFORMATs are allowed.
WCS is a “raw data” oriented format. So it often most suitable to use it with format using the BYTE, INT16 and
FLOAT32 IMAGEMODEs with GDAL related output formats rather than the built in “rendering oriented” output
formats. By default the only GDAL format driver defined is the GTiff driver. The following are example output format
declarations utilizing the raw image modes:
OUTPUTFORMAT
NAME GEOTIFF_16
DRIVER "GDAL/GTiff"
MIMETYPE "image/tiff"
IMAGEMODE FLOAT32
EXTENSION "tif"
END
OUTPUTFORMAT
NAME AAIGRID
DRIVER "GDAL/AAIGRID"
MIMETYPE "image/x-aaigrid"
IMAGEMODE INT16
EXTENSION "grd"
FORMATOPTION "FILENAME=result.grd"
END
The FORMATOPTION FILENAME defines the preferred name of the result file when returned WCS GetCoverage
results.
OK, now that we’ve got a mapfile, we have to check the XML capabilities returned by our server to make sure nothing
is missing.
Using a web browser, access your server’s online resource URL to which you add the parameters “SER-
VICE=WCS&VERSION=1.0.0&REQUEST=GetCapabilities” to the end, e.g.
http://my.host.com/cgi-bin/mapserv?map=mywcs.map&SERVICE=WCS&VERSION=1.0.0&REQUEST=GetCapabilities
If you get an error message in the XML output then take necessary actions. Common problems and solutions are listed
in the FAQ at the end of this document.
If everything went well, you should have a complete XML capabilities document. Search it for the word “WARN-
ING”... MapServer inserts XML comments starting with “<!–WARNING: ” in the XML output if it detects missing
mapfile parameters or metadata items.
Note that when a request happens, it is passed through WMS, WFS, and WCS in MapServer (in that order) until one
of the services respond to it.
Here is a working example of a GetCapabilities request:
http://demo.mapserver.org/cgi-bin/wcs?SERVICE=wcs&VERSION=1.0.0&REQUEST=GetCapabilities
OK, now that we know that our server can produce a valid XML GetCapabilities response we should test the De-
scribeCoverage request. The DescribeCoverage request lists more information about specific coverage offerings.
Using a web browser, access your server’s online resource URL to which you add the parameters “SER-
VICE=WCS&VERSION=1.0.0&REQUEST=DescribeCoverage&COVERAGE=layername” to the end, e.g.
http://my.host.com/cgi-bin/mapserv?map=mywcs.map&SERVICE=WCS&VERSION=1.0.0&REQUEST=DescribeCoverage&C
The GetCoverage request allows for the retrieval of coverages in a specified output format to the client.
The following is a list of the required GetCoverage parameters according to the WCS spec:
VERSION=version: Request version
REQUEST=GetCoverage: Request name
COVERAGE=coverage_name: Name of an available coverage, as stated in the GetCapabilities
CRS=epsg_code: Coordinate Reference System in which the request is expressed.
BBOX=minx,miny,maxx,maxy: Bounding box corners (lower left, upper right) in CRS units. One of
BBOX or TIME is required.
TIME=time1,time2: Request a subset corresponding to a time. One of BBOX or TIME is required..
WIDTH=output_width: Width in pixels of map picture. One of WIDTH/HEIGHT or RESX/Y is re-
quired.
HEIGHT=output_height: Height in pixels of map picture. One of WIDTH/HEIGHT or RESX/Y is
required.
RESX=x: When requesting a georectified grid coverage, this requests a subset with a specific spatial
resolution. One of WIDTH/HEIGHT or RESX/Y is required.
RESY=y: When requesting a georectified grid coverage, this requests a subset with a specific spatial
resolution. One of WIDTH/HEIGHT or RESX/Y is required.
FORMAT=output_format: Output format of map, as stated in the DescribeCoverage response.
The following are optional GetCoverage parameters according to the WCS spec:
RESPONSE_CRS=epsg_code: Coordinate Reference System in which to express coverage responses.
So to follow our above examples, a valid DescribeCoverage request would look like:
http://my.host.com/cgi-bin/mapserv?map=mywcs.map&SERVICE=wcs&VERSION=1.0.0&REQUEST=GetCoverage
&coverage=bathymetry&CRS=EPSG:42304&BBOX=-2200000,-712631,3072800,3840000
&WIDTH=3199&HEIGHT=2833&FORMAT=GTiff
Here is a working example of a GetCoverage request (note that a 350KB tif is being requested, so this may take a
second):
http://demo.mapserver.org/cgi-bin/wcs?SERVICE=wcs&VERSION=1.0.0&REQUEST=GetCoverage&COVERAGE=modis-
001&CRS=EPSG:26915&BBOX=159707,4597395,1400707,5501395&WIDTH=400&HEIGHT=300&FORMAT=GEOTIFF_RGB
WCS 1.1.0 and later versions of the WCS protocol are supported by MapServer 5.2. For the most part the map file
setup for WCS 1.1.0 is similar to WCS 1.0.0, but the actual protocol is substantially changed.
GetCapabilities
The GetCapabilities request is the same as WCS 1.0 but with a different VERSION value:
SERVICE=WCS&VERSION=1.1.0&REQUEST=GetCapabilities
The format of the returned capabilities document is substantially altered from WCS 1.0, and makes use of OWS
Common for service descriptions.
DescribeCoverage
The DescribeCoverage request is similar to WCS 1.0, but the IDENTIFIER keyword is used instead of COVERAGE
to name the coverage being requested:
SERVICE=WCS&VERSION=1.1.0&REQUEST=DescribeCoverage&IDENTIFIER=spaceimaging
GetCoverage
The format for GetCoverage is substantially changed from 1.0. The following is a list of GetCoverage required
parameters:
VERSION=version: Request version
REQUEST=GetCoverage: Request name
IDENTIFIER=coverage_name: Name of an available coverage, as stated in the GetCapabilities
BOUNDINGBOX=minx,miny,maxx,maxy,crs: Bounding box corners (lower left, upper right), and the
CRS they are in. The CRS is described using a URN.
FORMAT=output_format: Output format (mime type) of grid product, as stated in the GetCapabilities.
If an alternate spatial resolution is desired, then the following set of keywords must be used to specify the sample
origin and step size of the output grid to be produced. The produced grid will be of a number of pixels and lines as
can be fit in the BOUNDINGBOX starting at GridOrigin, at GridOffsets resolution.
GRIDBASECRS=crs: The grid base CRS (URN).
GRIDCS=crs: The grid CRS (URN).
GridType=urn:ogc:def:method:WCS:1.1:2dGridIn2dCrs: This is the only supported value for
MapServer.
GridOrigin=x_origin,y_origin: The sample point for the top left pixel.
GridOffsets=xstep,ystep: The x and y step size for grid sampling (resolution). Both are positive.
As well, the following optional parameters are available.
RangeSubset=selection: Selects a range subset, and interpolation method. Currently only subsetting on
bands are allowed. Depending on rangeset names, this might take the form “BandsName[bands[1]]” to
select band 1, or “BandsName:bilinear[bands[1]]” to select band 1 with bilinear interpolation.
So a simple GetCoverage might look like:
SERVICE=WCS&VERSION=1.1.0&REQUEST=GetCoverage&IDENTIFIER=dem&FORMAT=image/tiff
&BOUNDINGBOX=43,33,44,34,urn:ogc:def:crs:EPSG::4326
It should also be noted that return results from WCS 1.1 GetCoverage requests are in multi-part mime format. Typically
this consists of a first part with an xml document referencing the other parts of the message, and an image file part.
However, for output formats that return multiple files, each will be a separate part. For instance, this means it is
possible to return a jpeg file with a world file, the OUTPUTFORMAT is appropriately configured.
URNs
In WCS 1.1 protocol coordinate systems are referenced by URN. Some typical URNs are:
urn:ogc:def:crs:EPSG::4326
urn:ogc:def:crs:EPSG:27700
urn:ogc:def:crs:OGC::CRS84
The first two are roughly equivalent to EPSG:4326, and EPSG:27700 while the third is a CRS defined by OGC (es-
sentially WGS84). One critical thing to note is that WCS 1.1 follows EPSG defined axis/tuple ordering for geographic
coordinate systems. This means that coordinates reported, or provided in urn:ogc:def:EPSG::4326 (WGS84) are ac-
tually handled as lat, long, not long,lat. So, for instance the BOUNDINGBOX for an area in California might look
like:
BOUNDINGBOX=34,-117,35,-116,urn:ogc:def:crs:EPSG::4326
And, likewise the bounds reported by GetCapabilities, and DescribeCoverage will be in this ordering as appropriate.
Overview
Version 6.0 introduces support for the new version 2.0 of the WCS specification. This section documents the usage of
the new WCS version.
This specification adopts the new OGC Core and Extension model and at the moment the following documents are
available from the OGC’c WCS Standard page:
• GML 3.2.1 Application Schema Coverages
• WCS 2.0 Specification - Core
• WCS 2.0 Specification - KVP Protocol Binding Extension
• WCS 2.0 Specification - XML/POST Protocol Binding Extension
Technical changes from WCS version 1.1.2 include entirely building on the GML 3.2.1 Application Schema Coverages
and adoption of OWS Common 2.0. Another major change is the introduction of trim and slice concepts which is
explained in more detail below.
There are WCS 2.0 Schemas defined against which all requests and responses should validate.
definition (like EPSG:4326), an URN or an URI or ‘imageCRS’ (which is the default). All crs sub-
parameters from all SUBSET parameters must be equal. (e.g: you cannot subset one axis in imageCRS
and another in EPSG:4326).
SIZE=axis(value): This parameter sets the size of the desired axis to the desired value (pixels).
RESOLUTION=axis(value): This parameter sets the resolution of the desired axis to the desired value
(pixels/unit).
Note: The SIZE and RESOLUTION are mutually exclusive on one axis, but can be mixed on different axes (e.g:
SIZE on x-axis and RESOLUTION on y-axis). Also axis names in SUBSET, SIZE and RESOLUTION parameters
cannot be mixed. E.g: ...&SUBSET=x(0,100)&SIZE=lon(200)&... is not legal although the axis names logically refer
to the same axis.
Note: Recognized values for the axis sub-parameter are: “x”, “xaxis”, “x-axis”, “x_axis”, “long”, “long_axis”, “long-
axis”, “lon”, “lon_axis”, “lon-axis”, “y”, “yaxis”, “y-axis”, “y_axis”, “lat”, “lat_axis” and “lat-axis”.
OUTPUTCRS=crs: This parameter defines in which crs the output image should be expressed in.
MEDIATYPE=mediatype: This parameter is relevant to GetCoverage requests, when multipart
XML/image output is desired. It should be set to ‘multipart/mixed’ (which is currently the only pos-
sible value for this parameter).
INTERPOLATION=intperolation_method: This defines the interpolation method used, for rescaled
images. Possible values are “NEAREST”, “BILINEAR” and “AVERAGE”.
RANGESUBSET=band1[,band2[,...]]: With this parameter, a selection of the bands can be made. Also
the bands can be reordered. The bands can be referred to either by name (which can be retrieved using
the DescribeCoverage request) or by index (starting with ‘1’ for the first band).
Unchanged KVP parameters The following parameters have not (or just slightly) changed since the last version of
the WCS standard.
VERSION=version: For WCS 2.0, this should be set to ‘2.0.0’.
SERVICE=service
REQUEST=request
ACCEPTVERSIONS=versions
SECTIONS=sections
UPDATESEQUENCE=updatesequence
ACCEPTFORMATS=formats: This parameter is currently ignored.
ACCEPTLANGUAGES=languages: This parameter is currently ignored.
FORMAT=format: The desired format can now also be set with the name of the outputformat object
defined in the mapfile.
MAP=mapfile
All other parameter keys are invalid in WCS 2.0 and will therefore produce an exception message.
KVP request examples The below sample request outline the new KVP request syntax:
# GetCapabilities
http://www.yourserver.com/wcs?SERVICE=wcs&VERSION=2.0.0&REQUEST=GetCapabilities
# DescribeCoverage 2.0
http://www.yourserver.com/wcs?SERVICE=wcs&VERSION=2.0.0&REQUEST=DescribeCoverage&COVERAGEID=grey
# GetCoverage 2.0 image/tiff full
http://www.yourserver.com/wcs?SERVICE=wcs&VERSION=2.0.0&REQUEST=GetCoverage&COVERAGEID=grey&FORMAT=im
# GetCoverage 2.0 multipart/mixed (GML header & image/tiff) full
http://www.yourserver.com/wcs?SERVICE=wcs&VERSION=2.0.0&REQUEST=GetCoverage&COVERAGEID=grey&FORMAT=im
# GetCoverage 2.0 image/tiff trim x y both
http://www.yourserver.com/wcs?SERVICE=wcs&VERSION=2.0.0&REQUEST=GetCoverage&COVERAGEID=grey&FORMAT=im
# GetCoverage 2.0 reproject to EPSG 4326
http://www.yourserver.com/wcs?SERVICE=wcs&VERSION=2.0.0&REQUEST=GetCoverage&COVERAGEID=grey&FORMAT=im
Please refer to the WCS 2.0 tests in msautotest for further sample requests.
The layer name must be a valid NCName, i.e: must not start with a number and can only contain alphanumerical
characters. This constraint derives of the gml:id property which has to be a NCName, that relates to the coverage ID
which is itself taken from the layers name.
In this section new WCS 2.0.0 specific layer metadata entries are discussed.
The following layer metadata fields can be used to return a more detailed description for the range type of a “virtual
dataset” coverage. A coverage is considered as a “virtual dataset” if the (wcs|ows)_extent metadata entry and one of
the (wcs|ows)_size or (wcs|ows)_resolution metadata entries are set.
First of all, the used version of metadata has to be identified. To identify the bands of a coverage, one of the following
fields must be present:
• (wcs|ows)_band_names (corresponding to WCS 2.0)
• (wcs|ows)_rangeset_axes (corresponding to WCS 1.1)
The type of these fields is a space delimited list of names, whereas the count of the names has to match the “bandcount”
metadata field. These names are then used as a prefix for other metadata fields only concerning this band. The possible
metadata keys are the following:
• WCS 2.0:
– {band_name}_band_interpretation
– {band_name}_band_uom
– {band_name}_band_definition
– {band_name}_band_description
– {band_name}_interval
• WCS 1.1
– {band_name}_semantic
– {band_name}_values_types
– {band_name}_values_semantic
– {band_name}_description
– {band_name}_interval
All values are interpreted as strings, only “interval” is interpreted as 2 double precision float values separated with a
space.
Also default values can be configured for every key. These have the same suffix as the band specific keys but start with
(wcs|ows) instead of the bands name:
• WCS 2.0:
– (wcs|ows)_band_interpretation
– (wcs|ows)_band_uom
– (wcs|ows)_band_definition
– (wcs|ows)_band_description
– (wcs|ows)_interval
• WCS 1.1
– (wcs|ows)_semantic
– (wcs|ows)_values_types
– (wcs|ows)_values_semantic
– (wcs|ows)_description
– (wcs|ows)_interval
If no specific or default value is given, the output is dependant on the metadata key. The UOM, for example will be
set to ‘W.m-2.Sr-1’, interval and significant figures will be determined according to the image type and definition,
description, and interpretation will not be visible in the output at all.
This example demonstrates the use of the band-specific metadata fields with their default values:
METADATA
"ows_srs" "EPSG:4326"
"wcs_extent" "47.5070762077246 16.038578977182 49.0103258976982 17.2500586851354"
"wcs_bandcount" "3"
"wcs_band_names" "BandA BandB BandC"
#default values
"wcs_band_interpretation" "This is default interpretation"
"wcs_band_uom" "DefaultUOM"
"wcs_band_definition" "DefaultDefinition"
"wcs_band_description" "This is default description"
"wcs_interval" "0 125"
"wcs_significant_figures" "3"
The above example would result in having BandA a more specific description, and BandB and BandC having the
default description. It would also be possible to only use some of the specific values for BandA and others from the
default.
If no default and specific values are given for the interval or significant figures metadata field, the a default is generated
from the “imagemode” field, which itself defaults to FLOAT32.
The new metadata fields also contain the (wcs|ows)_nilvalues and (wcs|ows)_nilvalues_reasons
• (wcs|ows)_nilvalues
With this field, specific nilvalues can be set. The values have to be delimited by a space.
• (wcs|ows)_nilvalues_reasons
This field defines the reasons for the specific nilvalues. The reasons are also space delimited and reference the nilvalue
with the same index. The values for the reasons should be URIs or URNs.
The following example demonstrates the use of both metadata fields:
METADATA
"ows_srs" "EPSG:4326"
"wcs_extent" "47.5070762077246 16.038578977182 49.0103258976982 17.2500586851354"
Since version 6.0 MapServer also supports HTTP-POST XML requests. All requests possible via HTTP GET can also
be sent via POST. POST requests are possible for WCS 1.1 or WCS 2.0 which adhere to the according standard.
This is an example GetCapabilities request:
<?xml version="1.0" encoding="UTF-8"?>
<ows:GetCapabilities service="WCS">
<ows:AcceptVersions>
<ows:Version>2.0.0</ows:Version>
</ows:AcceptVersions>
<ows:updatesequence>2010-12-21</ows:updatesequence>
<ows:Sections>
<ows:Section>OperationsMetadata</ows:Section>
<ows:Section>ServiceIdentification</ows:Section>
</ows:Sections>
</ows:GetCapabilities>
This is an example DescribeCoverage request, which is only valid for WCS 2.0:
<wcs:DescribeCoverage
xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance’
xsi:schemaLocation="http://www.opengis.net/wcs/2.0 http://schemas.opengis.net/wcs/2.0/wcsAll.xsd"
xmlns="http://www.opengis.net/wcs/2.0"
xmlns:wcs="http://www.opengis.net/wcs/2.0"
service="WCS"
version="2.0.0">
<wcs:CoverageID>SOME_ID</wcs:CoverageID>
</wcs:DescribeCoverage>
This example demonstrates the usage of a WCS 2.0 POST-XML GetCoverage request:
<?xml version="1.0" encoding="UTF-8"?>
<wcs:GetCoverage
xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance’
xsi:schemaLocation="http://www.opengis.net/wcs/2.0 http://schemas.opengis.net/wcs/2.0/wcsAll.xsd"
xmlns="http://www.opengis.net/wcs/2.0"
xmlns:wcs="http://www.opengis.net/wcs/2.0"
service="WCS"
version="2.0.0">
<wcs:Format>image/tiff</wcs:Format>
<wcs:Mediatype>multipart/mixed</wcs:Mediatype>
<wcs:Resolution dimension="x">0.01</wcs:Resolution>
<wcs:Size dimension="y">50</wcs:Size>
<wcs:CoverageID>SOME_ID</wcs:CoverageID>
<wcs:DimensionTrim>
<wcs:Dimension crs="http://www.opengis.net/def/crs/EPSG/0/4326">x</wcs:Dimension>
<wcs:TrimHigh>17.25</wcs:TrimHigh>
<wcs:TrimLow>16.5</wcs:TrimLow>
</wcs:DimensionTrim>
<wcs:DimensionTrim>
<wcs:Dimension crs="http://www.opengis.net/def/crs/EPSG/0/4326">y</wcs:Dimension>
<wcs:TrimLow>47.9</wcs:TrimLow>
</wcs:DimensionTrim>
</wcs:GetCoverage>
Please refer to the WCS 2.0 Specification - XML/POST Protocol Binding Extension and the WCS 2.0 Schemas for
further information on POST request in WCS 2.0.
To avoid confusion only “wcs_*” and “ows_*” prefixed metadata entries are evaluated in OGC WCS services. Pre-
vious versions used “wms_*” prefixed entries as fallback which is dropped in version 6.0 in favor of forcing explicit
decisions. The module will look for the “wcs_*” and “ows_*” metadata prefixes in this order.
The following metadata are available in the setup of the mapfile:
wcs_abstract
• Description: (Optional) A brief description of the service, maps to ows:Abstract (WCS 1.1+ only).
wcs_accessconstraints
• Description: (Optional) A list of codes describing any access constraints imposed by the service provider. The
keyword NONE is reserved to mean no access constraints are imposed.
wcs_address, wcs_city, wcs_contactelectronicmailaddress, wcs_contactfacimiletelephone,
wcs_contactorganization, wcs_contactperson, wcs_contactposition, wcs_contactvoicetelephone, wcs_country,
wcs_postcode, wcs_service_onlineresource, wcs_stateorprovince
• Description: (Optional) Contact address information. If provided then all twelve metadata items are required.
You can also use the responsibleparty* metadata instead.
wcs_description
• Description: (Optional) A description of the server.
wcs_fees
• Description: (Optional) A text string indicating any fees imposed by the service provider.
wcs_keywords
• Description: (Optional) Short words for catalog searching.
wcs_label
• Description: (Required) A human-readable label for the server.
wcs_metadatalink_format
• Description: (Optional) The file format MIME type of the metadata record (e.g. “text/plain”). The web metadata
wcs_metadatalink_type and wcs_metadatalink_href must also be specified.
wcs_metadatalink_href
• Description: (Optional) The URL to the server’s metadata. The web metadata wcs_metadatalink_format and
wcs_metadatalink_type must also be specified.
wcs_metadatalink_type
• Description: (Optional) The standard to which the metadata complies. Currently only two types are valid:
“TC211” which refers to [ISO 19115], and “FGDC” which refers to [FGDC-STD-001-1988]. The web metadata
wcs_metadatalink_format and wcs_metadatalink_href must also be specified.
wcs_name
• Description: (Optional) A name for the server.
wcs_responsibleparty_address_administrativearea, wcs_responsibleparty_address_city,
wcs_responsibleparty_address_country, wcs_responsibleparty_address_deliverypoint,
wcs_responsibleparty_address_electronicmailaddress, wcs_responsibleparty_address_postalcode,
wcs_responsibleparty_individualname, wcs_responsibleparty_onlineresource, wcs_responsibleparty_organizationname,
wcs_responsibleparty_phone_facsimile, wcs_responsibleparty_phone_voice, wcs_responsibleparty_postionname
• Description: (Optional) Contact address information. If provided then all twelve metadata items are required.
You can also use the address* metadata instead.
wcs_abstract
• Description: (Optional) A brief description of the service, maps to ows:Abstract (WCS 1.1+ only).
wcs_description
• Description: (Optional) A description of the layer.
wcs_extent
• Description: (Optional) Bounding box of layer, which must be provided for tiled data. Comma-delimited, in
the format of: minx,miny,maxx,maxy
wcs_formats
• Description: (Optional) The formats which may be requested for this layer, separated by a space. (e.g. “GTiff
MrSID”)
wcs_keywords
wcs_srs
• Description: (Optional) Spatial reference system of the layer, in the form of: EPSG:code (e.g. EPSG:42304)
wcs_timeitem
• Description: (Optional) The attribute in the spatio/temporal index that contains time values.
wcs_timeposition
• Description: (Optional) A list of the start and end time of a given coverage (i.e. “2000-11-11T11:11:11Z,2001-
11-11T11:11:11Z”), used when advertising GetCapabilities.
TODO!
MapServer has long supported a method of breaking a dataset into smaller, more manageable pieces or tiles. In this
case a shapefile is used to store the boundary of each tile, and an attribute holds the location of the actual data. Within
a MapServer mapfile the layer keywords TILEINDEX and TILEITEM are used to activate tiling.
Consider the example where an organization wants to serve hundreds or even thousands of MODIS scenes. Five
images cover the spatial extent and each group of five varies by date of acquisition. This turns out to be a fairly
common scenario for organizations interested in WCS, one that the existing tiling support does not adequately address.
In previous versions of MapServer a developer would have to create one tile index and one layer definition for each
group of five images. This could result in configuration files that are prohibitively long and difficult to manage.
In order to more efficiently support the WCS specification a new tiling scheme has been implemented within
MapServer. One that supports spatial sub-setting, but also ad hoc sub-setting based on any attributes found within
tile index. In many cases a temporal attribute could be used, but sub-setting is not limited to that case. The new
scheme introduces the concept of tile index layers, that is, a separate layer definition is used to describe the tile index
dataset. With this we get all the benefits of any MapServer layer, most importantly we can apply MapServer filters
to the data. Filters can be defined at runtime using MapServer CGI, MapScript or via the WCS server interface. The
syntax for the layer using the index remains unchanged except that the value for Tile Indexes refers to the index layer
instead of an external shapefile.
So, looking at the example above again we can reduce our MapServer configuration to two layer definitions, one for
the tile index and one for the imagery itself. Extracting a single dates worth of imagery is now a matter of setting the
appropriate filter within the tile index layer.
Developing these tile indexes is more difficult than basic indexes simply because there are no ready-made tools to do
so. Fortunately we can leverage existing tool available within MapServer or supporting libraries such as GDAL by
post processing their output.
Taking the above example, building an index is relatively simple task if you are willing to roll up your sleeves and
write a bit of code. First, the basic spatial index needs to be built. The GDAL utility gdaltindex already does this.
Simply point gdaltindex at the directory containing the collection of MODIS images and it will build a shapefile index
suitable for use with MapServer. The next step would be to add the temporal information. The pseudo code would
look something like:
• open the index .dbf file for reading
• create a new column to hold the image acquisition date
• for each image; 1) extract the image acquisition date and 2) insert it into the new column
• close the index .dbf file
This general approach could be used for many cases. A scripting language such as Perl, PHP or Python works well
since they all have readily available modules for manipulating .dbf files. A worst case would involve hand editing the
resulting .dbf file using a desktop tool such as Mircosoft Access or ESRI Arcview.
OGC is currently discussing the adoption of an Earth Observation (EO) Application Profile for WCS 2.0 (EO-WCS).
A draft will be available soon for a public RFC period. For an implementation please refer to the Open Source project
EOxServer which already implements this proposed EO-WCS based on MapServer.
• MapServer does not derive all of the metadata it could from a given dataset. For example, you must explicitly
list time periods covered by a layer. This should get better with time.
• Only spatial, simple temporal and radiometric band subsetting is possible with the current implementation.
Furture enhancements should allow for arbitrary subsets based on pixel values or tile/image attributes.
• The available set of WCS 2.0 specification documents is not yet complete. Thus, for some implementation
details, the content of some forthcoming extensions had to be anticipated based on the approaches taken for WCS
1.1 and 1.0. The implementation will be adjusted as soon as new specification documents become available.
• If you want to use libxml2 or its derived tools (like xmllint) for validation be aware that there is a currently bug
in libxml2 that breaks the validation of GML 3.2.1.
Contents
• WCS Use Cases
– Landsat
– SPOT
– DEM
– NetCDF
This document explains how to use MapServer to deliver Landsat, SPOT, DEM, and NetCDF temporal/banded data
through the MapServer WCS interface. Thanks go to Steve Lime and Frank Warmerdam for their assistance with these
projects
9.10.1 Landsat
To serve Landsat imagery through the MapServer Web Coverage Service specify the OUTPUTFORMAT object. For
format support install the GDAL library and from the command prompt and cd to where GDAL is installed and use
the command, gdalinfo –formats. A list of all supported formats will appear and will specify if the format is read only
<ro> or read and write <rw> for WCS the format needs to be supported for read and write (except for GDAL’s own
WCS format, however).
For the example below the Landsat 7 15m resolution mosaic is in a Enhanced Compressed Wavelets format (ECW).
By running the gdalinfo.exe program I could verify that the ECW format has write permissions, therefore the format
can be specified in the MapFile and requested using the GetCoverage request.
OUTPUTFORMAT
NAME "ECW"
DRIVER "GDAL/ECW"
MIMETYPE "image/ecw"
IMAGEMODE "BYTE"
EXTENSION "ecw"
END
The keyword “DUMP” must be set to true to allow the data to download during a GetCoverage request.
LAYER
NAME "Landsat7"
STATUS OFF
TYPE RASTER
PROCESSING "SCALE=AUTO"
UNITS Meters
DUMP TRUE
TILEINDEX "MapServer/wcs/landsat7/l7mosaic15m.shp"
TILEITEM "Location"
METADATA
"wcs_description" "Landsat 7 15m resolution mosaic"
"wcs_name" "Landsat7"
"wcs_label" "Landsat 7 15m resolution mosaic"
"ows_srs" "EPSG:27700"
"ows_extent" "0 0 700005 1050000"
"wcs_resolution" "75 75"
"wcs_bandcount" "3"
"wcs_formats" "ECW"
END
END
A GetCoverage request can then be requested (using the parameters set in the MapFile) by creating a URL with the
elements: - Your Server, MapServer Program, Location of MapFile, Type of Service (WCS), Request (GetCoverage),
Coverage (Landsat7), BBOX (0,0,700005,1050000), CRS (EPSG:27700), ResX (75) ResY (75), Format (ECW).
9.10.2 SPOT
SPOT imagery can be delivered through MapServer Web Coverage Service similarly to the Landsat example above.
The main difference is that as SPOT is a greyscale image the wcs_bandcount = 1 rather than a Landsat image which
consists of 3 bands. For this example the well known GeoTiff format will be used to demonstrate what to specify in a
MapFile for SPOT data.
OUTPUTFORMAT
NAME "GEOTIFF"
DRIVER "GDAL/GTiff"
MIMETYPE "image/tiff"
IMAGEMODE "BYTE"
EXTENSION "tif"
END
LAYER
NAME "SPOT"
STATUS OFF
TYPE RASTER
PROCESSING "SCALE=AUTO"
UNITS Meters
DUMP TRUE
TILEINDEX "MapServer/wcs/orthospot/spot.shp"
TILEITEM "Location"
METADATA
"wcs_description" "Orthospot mosaic"
"wcs_name" "SPOT"
"wcs_label" "Orthospot mosaic"
"ows_srs" "EPSG:27700"
"ows_extent" "375960 64480 497410 200590"
"wcs_resolution" "100 100"
"wcs_bandcount" "1"
"wcs_formats" "GEOTIFF"
"wcs_nativeformat" "8-bit GeoTIF"
END
END
The key parameters to specify in the WCS MapFile for any data layer and format are:
- Layer Name = Create a short name for the data
- Layer Type = Raster
- Layer Dump = True
The following examples further demonstrate how WCS can be implemented and also how to create WCS containing
layers with a temporal dimension (see NetCDF example).
9.10.3 DEM
It is possible to deliver 16 bit DEM data through the MapServer Web Coverage Service.
Firstly it is necessary to specify the output format in the map file
OUTPUTFORMAT
NAME "GEOTIFFINT16"
DRIVER "GDAL/GTiff"
MIMETYPE "image/tiff"
IMAGEMODE "INT16"
EXTENSION "tif"
END
END
METADATA
"wcs_label" "SRTM WCS TIF Server"
"ows_extent" "-180 -90 180 90"
"wcs_resolution" "0.00083 -0.00083"
"ows_srs" "EPSG:4326"
"wcs_formats" "GEOTIFFINT16"
"wcs_nativeformat" "geotiff"
END
END
9.10.4 NetCDF
Firstly GDAL doesn’t support all versions of netCDF (there are a lot, it is a generic format), so for stability it
may be necessary to convert the files into GeoTiff format first. This can be achieved using the netCDF libraries
here http://my.unidata.ucar.edu/content/software/netcdf/index.html. Denis Nadeau and Frank Warmerdam have added
netCDF CF as a read only format within GDAL, so it now possible to read the CF convention netCDF files directly
from disk.
We placed the Z-levels in the bands of the GDAL data file (either GeoTiff or netCDF), and created a shape index for
the time levels. GDAL data is a 2-D format (x,y) and bands. netCDF is an N-D file format, supporting time, x,y,z, and
experiment parameters. By using a set of GDAL netCDF / geoTiff files it is possible to represent this, and to store the
z-level (height) as bands within the data file. Although a hack, it is possible for a custom client to receive important
metadata from the describeCoverage operation of a WCS about the which z-level a band of a geotiff represents by
encoding this in the returned axes description tag.
To create the shape file for the temporal dimension we had to do some hacking with Java code, but we also got it to
work with Steve Lime’ s perl script in the MODIS MapServer demo download (which doesn’t seem to be available
now).
The perl script used in Modis demo by Steve Lime is as follows, and I have placed inline comments below. The script
assumes that gdaltindex has already been run in this directory to create a tile index shape and dbf file. It assumes that
the filenames of your data files have the date in the filename, for example myfileYYYYMMDDHH.tif
1 #!/usr/bin/perl
2 use XBase;
3 opendir(DIR, ’.’); # open the current directory
4 foreach $file (readdir(DIR)) {
5 next if !($file =~ /\.dbf$/); # read the dbf file in this directory created by gdaltindex
6 print "Working on $file...\n";
7 $tfile = ’temporary.dbf’;
8 system("mv $file $tfile");
9 $oldtable = new XBase $tfile or die XBase->errstr;
10 print join("\t", $oldtable->field_names) ."\n";
11 print join("\t", $oldtable->field_types) ."\n";
12 print join("\t", $oldtable->field_lengths) ."\n";
13 print join("\t", $oldtable->field_decimals) ."\n";
14 $newtable = XBase->create("name" => $file,
15 "field_names" => [$oldtable->field_names, "IMGDATE"], # this is the FILTERITEM in
16 "field_types" => [$oldtable->field_types, "C"], # character column type
17 "field_lengths" => [$oldtable->field_lengths, 13], # length of the date string
18 "field_decimals" => [$oldtable->field_decimals, undef]) or die "Error creating new
19 foreach (0 .. $oldtable->last_record) {
20 ($deleted, @data) = $oldtable->get_record($_);
If have used the perl script then skip to the layer definitions below, if you wish to code your own the description is
here.
The DBF file has to have the column ‘location’ that indicates the location of the data file (either absolute path or
relative to the map file location, and the second column that can be called whatever you want but indexes time. In our
case we called it ‘time’ :-)
The corresponding shapefile then has to contain Polygons with the bounding boxes of the tif file for each time. So
OGRInfo timeIndex.shp looks something like:
OGRFeature(timeIndex):116
location(String) = mytime.tif
time(String) = 2001-01-31T18:00:00
POLYGON ((xxx,xxxx,.......))
Then you need to define your tile index within the map file
LAYER
NAME ’time_idx’
TYPE TILEINDEX
DATA ’timeIndex’
FILTERITEM ’time’
FILTER ’%time%’
END
"init=epsg:4326"
END
METADATA
"wcs_label" ’Temperature data’
"ows_extent" ’-180 -90 180 90’
"wcs_resolution" ’1.125 -1.125’
"ows_srs" ’EPSG:4326’
"wcs_formats" ’GEOTIFF_FLOAT’
"wcs_nativeformat" ’netCDF’
"wcs_bandcount" ’27’
"wcs_rangeset_axes" ’bands’
"wcs_rangeset_label" ’Pressure (hPa units) Levels’
"wcs_rangeset_name" ’bands’
"wcs_rangeset_description" ’Z levels ’
"wcs_timeposition" ’2001-01-01T06:00:00,2001-01-01T12:00:00,2001-01-01T18:00:00,2001-01-02T00:00:
"wcs_timeitem" ’time’
END
END
The TempData coverage layer will now let you subset with the &bands=... &time=... subset parameters!
To do a coordinate reprojection specify in the request &Response_CRS=ESPG:xxxx
When you start doing temporal subsetting with WCS and MapServer you can see the need for an automatic way of
generating map files such as using an XSL stylesheet!
For a tile-index layer you need to provide the following extra metadata in order to use it for WCS:
"OWS_EXTENT" "10050 299950 280050 619650"
"WCS_RESOLUTION" "100 100"
"WCS_SIZE" "2700 3197"
"WCS_BANDCOUNT" "3"
If your image has a colortable and only one band, it will come out greyscale unless you set the IMAGEMODE to
PC256 instead of BYTE.
Table of Contents
• SOS Server
– Introduction
– Setting Up an SOS Server Using MapServer
– Limitations / TODO
– Reference Section
– Use of sos_procedure and sos_procedure_item
9.11.1 Introduction
SOS (Sensor Observation Service), currently an OGC discussion paper, is part of of the OGC’s SensorWeb Enablement
(SWE) group of specifications. These specifications describe how applications and services will be able to access
sensors of all types over the Web. Specifically, SOS provides an API for managing deployed sensors and retrieving
sensor data.
SOS support is available in MapServer 4.10.0 or more recent. Note that no client tools currently exist in MapServer
for SOS. More SWE based software is available at http://www.52north.org/
SOS support was implemented in MapServer to the guidelines of MapServer MS RFC 13: Support of Sensor Obser-
vation Service in MapServer.
This document assumes that you are already familiar with certain aspects of MapServer:
• MapServer application development and setting up .map files.
Relevant Definitions
SOS requests are handled by the “mapserv” CGI program. The first step is to check that your mapserv exe-
cutable includes SOS support. One way to verify this is to use the “-v” command-line switch and look for “SUP-
PORTS=SOS_SERVER”.
Example 1. On Unix:
$ ./mapserv -v
MapServer version 4.9 OUTPUT=GIF OUTPUT=PNG OUTPUT=JPEG OUTPUT=WBMP OUTPUT=SVG S
UPPORTS=PROJ SUPPORTS=FREETYPE SUPPORTS=WMS_SERVER SUPPORTS=WMS_CLIENT SUPPORTS=
WFS_SERVER SUPPORTS=WFS_CLIENT SUPPORTS=WCS_SERVER SUPPORTS=SOS_SERVER SUPPORTS=
THREADS INPUT=JPEG INPUT=OGR INPUT=GDAL INPUT=SHAPEFILE DEBUG=MSDEBUG
Example 2. On Windows:
C:\Apache\cgi-bin> mapserv -v
MapServer version 4.9 OUTPUT=GIF OUTPUT=PNG OUTPUT=JPEG OUTPUT=WBMP OUTPUT=SVG S
UPPORTS=PROJ SUPPORTS=FREETYPE SUPPORTS=WMS_SERVER SUPPORTS=WMS_CLIENT SUPPORTS=
WFS_SERVER SUPPORTS=WFS_CLIENT SUPPORTS=WCS_SERVER SUPPORTS=SOS_SERVER SUPPORTS=
THREADS INPUT=JPEG INPUT=OGR INPUT=GDAL INPUT=SHAPEFILE DEBUG=MSDEBUG
If you don’t have SOS support in your MapServer build, then you must compile MapServer with the following in
mind:
• flag -DUSE_SOS_SVR is required
• requires either -DUSE_WMS_SVR or -DUSE_WFS_SVR flags to be enabled
• requires libxml2 and proj libraries
• requires ICONV support (-DUSE_ICONV) on Windows
For more help with MapServer compilation see the appropriate HowTo: Unix / Windows
Each instance of SOS server that you setup needs to have its own mapfile. It is just a regular MapServer mapfile in
which some parameters and some metadata entries are mandatory. Most of the metadata is required in order to produce
a valid GetCapabilites output.
Here is the list of parameters and metadata items that usually optional with MapServer, but are required (or strongly
recommended) for a SOS configuration:
MAP level:
• Map NAME
• Map PROJECTION
• Map Metadata (in the WEB Object):
– sos_title
– sos_onlineresource
– sos_srs
– see the Reference Section of this document for a full list of metadata and descriptions
LAYER level:
• Layer NAME
• Layer PROJECTION
• Layer METADATA
– sos_offering_id
– sos_observedproperty_id
– sos_observedproperty_id
– sos_describesensor_url
– see the Reference Section of this document for a full list of metadata and descriptions
Onlineresource URL
The sos_onlineresource metadata is set in the map’s web object metadata and specifies the URL that should be used
to access your server. This is required for the GetCapabilities output. If sos_onlineresource is not provided then
MapServer will try to provide a default one using the script name and hostname, but you shouldn’t count on that too
much. It is strongly recommended that you provide the wfs_onlineresource metadata.
Here is a valid online resource URL:
http://my.host.com/cgi-bin/mapserv?map=mysos.map&
By creating a wrapper script on the server it is possible to hide the “map=” parameter from the URL and then your
server’s online resource URL could be something like:
http://my.host.com/cgi-bin/mapserv?
This is covered in more detail in the “More About the Online Resource URL” section of the WMS Server document.
The following is an example of a bare minimum SOS Server mapfile. Note the comments for the required parameters.
NAME "SOS_DEMO"
STATUS ON
SIZE 300 300
EXTENT -66 44 -62 45
UNITS METERS
SHAPEPATH "./data/"
IMAGECOLOR 255 255 0
SYMBOLSET "./etc/symbols.sym"
IMAGETYPE png
WEB
IMAGEPATH "/ms4w/tmp/ms_tmp/"
IMAGEURL "/ms_tmp/"
METADATA
"sos_onlineresource" "http://127.0.0.1/cgi-bin/mapserv.exe?map=D:/ms4w/apps/sos/sos_test.map" ## R
"sos_title" "My SOS Demo Server" ## Recommended
"sos_srs" "EPSG:4326" ## REQUIRED
END
END
PROJECTION
"init=epsg:4326"
END
LAYER
NAME "test_sos_layer"
METADATA
"sos_procedure" "NS01EE0014" ## REQUIRED
"sos_offering_id" "WQ1289" ## REQUIRED
"sos_observedproperty_id" "Water Quality" ## REQUIRED
"sos_describesensor_url" "http://some/url/NS01EE0014.xml" ## REQUIRED
END
TYPE POINT
STATUS ON
DATA "sos_test"
PROJECTION
"init=epsg:4326"
END
CLASS
NAME "water quality"
STYLE
COLOR 255 0 0
SYMBOL "circle"
SIZE 8
END
END
END
END #map
GetCapabilities Request
The GetCapabilities request allows the clients to retrieve service metadata about a specific service instance. For an
SOS service, it allows to identify such things as offerings and observed property available, as well as information on
sensors that are used.
Using a web browser, access your server’s online resource URL to which you add the parameters “SER-
VICE=SOS&REQUEST=GetCapabilities” to the end, e.g.
http://my.host.com/cgi-bin/mapserv?MAP=mysos.map&SERVICE=SOS&REQUEST=GetCapabilities
If everything went well, you should have a complete XML capabilities document. Search it for the word “WARN-
ING”... MapServer inserts XML comments starting with “<!–WARNING: ” in the XML output if it detects missing
mapfile parameters or metadata items. If you notice any warning in your XML output then you have to fix all of them
before you can try your server with an SOS client, otherwise things are likely not going to work.
Note: The SERVICE parameter is required for all SOS requests.
GetObservation Request
The GetObservation request is designed to query sensor systems to retrieve observation data in the form defined in
the Observation and Measurement specification (O&M), and more information on this O&M spec can be found at
http://www.opengeospatial.org/functional/?page=swe. Upon receiving a GetObservation request, a SOS shall either
satisfy the request or return an exception report.
The following is a list of the possible parameters for a GetObservation request:
request: (Required) value must be “GetObservation”.
service: (Required) value must be “SOS”.
version: (Required) value must be “1.0.0”.
offering: (Required) The Offering identified in the capabilities document.
observedProperty: (Required) The property identified in the capabilities document.
Example 2:
http://127.0.0.1/cgi-bin/mapserv.exe?map=D:/ms4w/apps/sos/sos_test.map&Request=GetObservation&service
Offering=WQ1289&observedproperty=Water Quality&eventtime=<ogc:TM_Equals><gml:TimePeriod><gml:beginPos
<PropertyName>COLOUR</PropertyName><Literal>180</Literal></PropertyIsEqualTo><PropertyIsEqualTo>
<PropertyName>COLOUR</PropertyName><Literal>200</Literal></PropertyIsEqualTo></or></Filter>&version=1
Example 3:
http://127.0.0.1/cgi-bin/mapserv.exe?map=D:/ms4w/apps/sos/sos_test.map&Request=GetObservation&service
Offering=WQ1289&observedproperty=Water Quality&featureofinterest=
<gml:Envelope><gml:lowerCorner srsName=’EPSG:4326’>-66 43</gml:lowerCorner><gml:upperCorner srsName=’
-64 45</gml:upperCorner></gml:Envelope>&version=1.0.0&responseFormat=text/xml; subtype="om/1.0.0"
Example 4:
http://127.0.0.1/cgi-bin/mapserv.exe?map=D:/ms4w/apps/sos/sos_test.map&Request=GetObservation&service
Offering=WQ1289&observedproperty=Water Quality&version=1.0.0&responseFormat=text/xml; subtype="om/1.0
DescribeSensor Request
The DescribeSensor request gives the client the ability to retrieve the characteristics of a particular sensor and return
the information in a SensorML xml document. In this implementation, MapServer does not generate the SensorML
document but only redirect the request to an existing SensorML document.
The following is a list of the possible parameters for a DescribeSensor request:
request: (Required) value must be “DescribeSensor”
service: (Required) value must be “SOS”.
1. Have MapServer generate the SensorML document, instead of redirecting the request to an existing SensorML
document.
The following metadata are available in the setup of the SOS Server mapfile:
Note: Each of the metadata below can also be referred to as ‘ows_*’ instead of ‘sos_*’. MapServer tries the ‘sos_*’
metadata first, and if not found it tries the corresponding ‘ows_*’ name. Using this reduces the amount of duplication
in mapfiles that support multiple OGC interfaces since “ows_*” metadata can be used almost everywhere for common
metadata items shared by multiple OGC interfaces.
ows_updatesequence
• Description: (Optional) The updateSequence parameter can be used for maintaining the consistency of a client
cache of the contents of a service metadata document. The parameter value can be an integer, a timestamp in
[ISO 8601:2000] format, or any other number or string.
ows_language
• Description: (Optional) Descriptive narrative for more information about the server. Identifier of the language
used by all included exception text values. These language identifiers shall be as specified in IETF RFC 1766.
When this attribute is omitted, the language used is not identified. Examples: “en-CA”, “fr-CA”, “en-US”.
Default is “en-US”.
ows_schemas_location
• Description: (Optional) (Note the name ows_schemas_location and not sos/_... this is because all OGC Web
Services (OWS) use the same metadata) Root of the web tree where the family of OGC SOS XMLSchema files
are located. This must be a valid URL where the actual .xsd files are located if you want your SOS output to val-
idate in a validating XML parser. Default is http://www.opengeospatial.net/sos. See http://ogc.dmsolutions.ca
for an example of a valid schema tree.
sos_abstract
• Description: (Optional) Descriptive narrative for more information about the server.
sos_keywordlist
• Description: (Optional) A comma-separated list of keywords or keyword phrases to help catalog searching.
sos_accessconstraints
• Description: (Optional) Text describing any access constraints imposed by the service provider on the SOS or
data retrieved from this service.
sos_addresstype, sos_address, sos_city, sos_stateorprovince, sos_postcode, sos_country
• Description: Optional contact address information. If provided then all six metadata items are required.
sos_contactelectronicmailaddress
• Description: Optional contact Email address.
sos_contactperson, sos_contactposition, sos_contactorganization
• Description: Optional contact information. If provided then all three metadata items are required.
sos_contactvoicetelephone
• Description: Optional contact voice telephone number.
sos_contactfacsimiletelephone - * Description: Optional contact facsimile telephone number.
sos_fees
• Description: (Optional) Fees information. Use the reserved word “none” if there are no fees.
sos_onlineresource
• Description: (Required) The URL that will be used to access this OGC server. This value is used in the
GetCapabilities response.
• See the section “Onlineresource URL” above for more information.
sos_service_onlineresource
• Description: (Optional) Top-level onlineresource URL.
sos_srs
• Description: (Required) Contains a list of EPSG projection codes that should be advertized as being available
for all layers in this server. The value can contain one or more EPSG:<code> pairs separated by spaces (e.g.
“EPSG:4269 EPSG:4326”) This value should be upper case (EPSG:42304.....not epsg:42304) to avoid problems
with case sensitive platforms.
sos_title
• Description: (Recommended) A human-readable name for this Layer.
sos_hoursofservice
• Description: (Optional) Time period (including time zone) when individuals can contact the organization or
individual.
sos_contactinstructions
• Description: (Optional) Supplemental instructions on how or when to contact the individual or organization.
sos_role
• Description: (Optional) Function performed by the responsible party. Possible values of this Role shall include
the values and the meanings listed in Subclause B.5.5 of ISO 19115:2003.
sos_maxfeatures
• Description: (Optional) The number of elements to be returned by the WFS server. If the not set all observations
are returned
sos_encoding_blockSeparator
• Description: (Optional) For GetObservation requests using resultModel=om:Observation (SWE DataBlock en-
coding). Record separator to be used. Default is ‘\n’
sos_encoding_tokenSeparator
• Description: (Optional) For GetObservation requests using resultModel=om:Observation (SWE DataBlock en-
coding). Token (field) separator to be used. Default is ‘,’
sos_describesensor_url
• Description: (Required) This metadata item is only a temporary measure until the describe sensor is generated
from MapServer. Right now when a DescribeSensor request is sent with a procedure (sensorid), it will redirect
it to the url defined by this metadata item.
• In MapServer 5.0, it is possible to use variable substituion on the url. For example “sos_describesensor_url”
“http://foo/foo?mysensor=%procedure%” will substitute the %procedure% in the metadata with the procedure
value coming from the request.
"sos_describesensor_url" "http://some/url/NS01EE0014.xml"
sos_[item name]_alias
• Description: (Optional) An alias for an attribute’s name that will be returned when executing a GetObservation
request.
sos_[item name]_definition
• Description: (Optional) An associated definition (usually a URN) for a component, that will be returned when
executing a GetObservation request. Default is “urn:ogc:object:definition”
sos_[item name]_uom
• Description: (Optional) An associated unit of measure URN) for a component, that will be returned when
executing a GetObservation request. Default is “urn:ogc:object:uom”
sos_observedproperty_id
• Description: (Required) ID of observed property, possibly in number format.
sos_observedproperty_name
• Description: (Optional) Name of observed property, possibly in string format.
sos_observedproperty_authority
• Description: (Optional) An associated authority for a given component of an observed property
sos_observedproperty_version
• Description: (Optional) An associated version for a given component of an observed property
sos_offering_description
• Description: (Optional) Description of offering.
sos_offering_extent
• Description: (Optional) Spatial extents of offering, in minx, miny, maxx, maxy format:
"sos_offering_extent" "-66, 43, -62, 45"
The logic for the bounding box returned as part of the offering is the following:
– note that it is a mandatory element that needs an espg code and lower/upper corner coordinates
– looks for the espg parameter in the first layer of the offering (this could be an ows/sos_srs or a projection
object with the epsg code (mandatory)
– looks for sos_offering_extent. If the metadata is not available, the extents of all layers in the offering will
be used to compute it.
Here is an example result from a GetCapabilities request:
<gml:boundedBy>
<gml:Envelope>
<gml:lowerCorner srsName="EPSG:4326">-66 43</gml:lowerCorner>
<gml:upperCorner srsName="EPSG:4326">-62 45</gml:upperCorner>
</gml:Envelope>
</gml:boundedBy>
sos_offering_id
• Description: (Required) ID of offering, possibly in number format.
sos_offering_intendedapplication
• Description: (Optional) The intended category of use for this offering.
sos_offering_name
• Description: (Optional) Name of offering, possibly in string format.
sos_offering_timeextent
• Description: (Optional) Time extent of offering, in the format of “begin/end”. Here is an example:
"sos_offering_timeextent" "1990/2006"
If end is not specified it will be set to now. Here is an example result from a GetCapabilities request:
<sos:eventTime>
<gml:TimePeriod>
<gml:beginPosition>1990</gml:beginPosition>
<gml:endPosition>2006</gml:endPosition>
</gml:TimePeriod>
</sos:eventTime>
sos_procedure
• Description: (Required) Normally a sensor unique id. One per layer:
"sos_procedure" "NS01EE0014"
All sos_procedure links from layers in the offerings will be outputed together, such as the following taken from
a GetCapabilities response:
<procedure xlink:href="urn:ogc:object:feature:Sensor:3eTI:csi-sensor-1"/>
<procedure xlink:href="urn:ogc:object:feature:Sensor:3eTI:csi-sensor-2"/>
sos_procedure_item
• Description: (Required if sos_procedure is not present): See section 5 for more details
"sos_procedure_item" "attribute_field_name"
sos_timeitem
• Description: (Optional) Name of the time field. It will be used for queries when a GetObservation request is
called with an EVENTTIME parameter. It is layer specific and should be set on all layers.
"sos_timeitem" "TIME"
In MapServer 5.0 SOS support has been upgraded to use a new metadata called sos_procedure_item. The value for
sos_procedure_item is the field/attribute name containing the procedure values. The use of this metadata as well as
the sos_procedure is described here per type of request (refer to http://trac.osgeo.org/mapserver/ticket/2050 for more
description):
It should be noted that, for very large datasets defined only with sos_procedure_item, this may result in costly process-
ing, because MapServer has to process attribute data. It is advised to setup and manage datasets accordingly if dealing
with large observation collections.
GetCapabilities
DescribeSensor
GetObservation
Both sos_procedure and sos_procedure_item can be define. Here are the cases:
• case 1 [only sos_procedure is defined.]
– Use this metadata to match the layer with the procedure value sent in the request
– When outputing the <member/procedure> output the value of the metadata
Note: If more than one procedure is defined per LAYER object, output observations will have incorrect sos:procedure
values, because there is no way to map procedures to observations. This is where sos_procedure_item should be used
(i.e. when more than one procedure makes up a LAYER object).
• case 2: only procedure_item is defined.
– Use the sos_procedure_item and do a query on the layer to match the procedure with the layer.
– When outputting the <member/procedure> use the procedure_item as a way to only output the at-
tribute value corresponding to the feature.
• case 3: both are defined.
– check in sos_procedure to match the procedure with the layer.
– When outputting the <member/procedure> use the procedure_item as a way to only output the at-
tribute value corresponding to the feature.
Contents
• MapScript Wrappers for WxS Services
– Introduction
– Python Examples
– Perl Example
– Java Example
– PHP Example
– Use in Non-CGI Environments (mod_php, etc)
– Post Processing Capabilities
9.12.1 Introduction
With the implementation of MapServer MS RFC 16: MapScript WxS Services in MapServer 4.9, MapScript now has
the ability to invoke MapServer’s ability to execute OGC Web Service requests such as WMS, WCS, and WFS as well
as capturing the results of processing the requests.
This makes it possible to dynamically configure a map object based on information in the original request, and to
capture the output of processing requests for further post-processing.
The following trivial example, in Python, demonstrates a script that internally provides the map name, but otherwise
uses normal mapserver processing.
import mapscript
req = mapscript.OWSRequest()
req.loadParams()
The OWSRequest object is used to manage a parsed list of OWS processing options. In the above example they are
loaded from the environment using the loadParams() call which fetches and parses them from QUERY_STRING in
the same way the mapserv executable would.
Then we load a map, and invoke OWSDispatch with the given arguments on that map. By default the results of the
dispatched request are written to stdout which returns them back to the client.
The following example ignores all passed in arguments, and manually constructs a request argument by argument. It
is likely more useful for testing purposes than for deploying WxS services, but demonstrates direct manipulation of
the request object.
import mapscript
req = mapscript.OWSRequest()
req.setParameter( ’SERVICE’, ’WMS’ )
req.setParameter( ’VERSION’, ’1.1.0’ )
req.setParameter( ’REQUEST’, ’GetCapabilities’ )
The previous example have all let results be returned directly to the client. But in some cases we want to be able to
capture, and perhaps modify the results of our requests in some custom way. In the following example we force the
hated OGC required mime type for errors to simple text/xml (warning - non-standard!)
import mapscript
req = mapscript.OWSRequest()
req.loadParams()
mapscript.msIO_installStdoutToBuffer()
map.OWSDispatch( req )
content_type = mapscript.msIO_stripStdoutBufferContentType()
content = mapscript.msIO_getStdoutBufferBytes()
if content_type == ’vnd.ogc.se_xml’:
content_type = ’text/xml’
This example demonstrates capture capturing output of OWSRequest to a buffer, capturing the “Content-type:” header
value, and capturing the actual content as binary data. The msIO_getStdoutBufferBytes() function returns the stdout
buffer as a byte array. If the result was known to be text, the msIO_getStdoutBufferString() function could have been
used to fetch it as a string instead, for easier text manipulation.
Most of the same capabilities are accessable in all SWIG based mapscript languages. In perl, we could script creation
of a request like this:
#!/usr/bin/perl
use mapscript;
mapscript::msIO_installStdoutToBuffer();
One issue in Perl is that there is currently no wrapping for binary buffers so you cannot call
msIO_getStdoutBufferBytes(), and so cannot manipulate binary results.
#!/usr/bin/perl
############################################################################
#
# Name: wxs.pl
# Project: MapServer
# Purpose: MapScript WxS example
#
# Author: Tom Kralidis
#
##############################################################################
#
# Copyright (c) 2007, Tom Kralidis
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies of this Software or works derived from this Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
############################################################################/
my $dispatch;
=comment
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:wfs="http://www.opengis.net/wfs">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<WFSLayers>
<xsl:for-each select="//wfs:FeatureType">
<wfs_layer>
<name><xsl:value-of select="wfs:Name"/></name>
<title><xsl:value-of select="wfs:Title"/></title>
</wfs_layer>
</xsl:for-each>
</WFSLayers>
</xsl:template>
</xsl:stylesheet>
=cut
my $mapfile = "/tmp/config.map";
# init OWSRequest object
my $req = new mapscript::OWSRequest();
# init mapfile
my $map = new mapscript::mapObj($mapfile);
my $xml = XML::LibXML->new();
my $xslt = XML::LibXSLT->new();
my $source = $xml->parse_string($content);
One benefit of redirection of output to a buffer is that it is thread-safe. Several threads in the same process can
be actively processing requests and writing their results to distinct output buffers. This Java example, used to test
multi-threaded access demonstrates that.
import edu.umn.gis.mapscript.mapObj;
import edu.umn.gis.mapscript.OWSRequest;
import edu.umn.gis.mapscript.mapscript;
mapscript.msIO_installStdoutToBuffer();
if( owsResult != 0 )
System.out.println( "OWSDispatch Result (expect 0): " + owsResult );
resultBytes = mapscript.msIO_getStdoutBufferBytes();
}
}
try {
WxSTest_thread tt[] = new WxSTest_thread[100];
int i;
int expectedLength=0, success = 0, failure=0;
} catch( Exception e ) {
e.printStackTrace();
}
}
}
Most of the same capabilities are accessible in php mapscript. Here is an example displaying a wms capabilities.
Example1 : get the capabilities
This is for example what a url could look like :
http://.../php/ows.php?service=WMS&version=1.1.1&Request=GetCapabilities
<?php
dl("php_mapscript_4.10.0.dll");
$request = ms_newowsrequestobj();
$request->loadparams();
ms_ioinstallstdouttobuffer();
$oMap = ms_newMapobj("../../service/wms.map");
$oMap->owsdispatch($request);
$contenttype = ms_iostripstdoutbuffercontenttype();
$buffer = ms_iogetstdoutbufferstring();
header(’Content-type: application/xml’);
echo $buffer;
ms_ioresethandlers();
?>
http://.../php/ows.php?SERVICE=WMS&VeRsIoN=1.1.1&Request=GetMap&
LAYERS=WorldGen_Outline
<?php
dl("php_mapscript_4.10.0.dll");
$request = ms_newowsrequestobj();
$request->loadparams();
ms_ioinstallstdouttobuffer();
$oMap = ms_newMapobj("../../service/wms.map");
$oMap->owsdispatch($request);
$contenttype = ms_iostripstdoutbuffercontenttype();
if ($contenttype == ’image/png’)
header(’Content-type: image/png’);
ms_iogetStdoutBufferBytes();
ms_ioresethandlers();
?>
The loadParams() call establish parses the cgi environment varabiables (QUERY_STRING, and RE-
QUEST_METHOD) into parameters in the OWSRequest object. In non-cgi environments, such as when php, python
and perl are used as “loaded modules” in Apache, or Java with Tomcat, the loadParams() call will not work - in fact in
4.10.x it will terminate the web server instance.
It is necessary in these circumstances for the calling script/application to parse the request url into keyword/value pairs
and assign to the OWSRequest object by other means, as shown in some of the above examples explicitly setting the
request parameters.
In the following python example, we process any incoming WxS request, but if it is a GetCapabilities request we
replace the Service section in the capabilities with a section read from a file, that is carefully tailored the way we want.
#!/usr/bin/env python
import sys
import elementtree.ElementTree as ET
import mapscript
req = mapscript.OWSRequest()
req.loadParams()
#
# Handle anything but a GetCapabilities call normally.
#
if req.getValueByName(’REQUEST’) <> ’GetCapabilities’:
map.OWSDispatch( req )
#
# Do special processing for GetCapabilities
#
else:
mapscript.msIO_installStdoutToBuffer()
map.OWSDispatch( req )
ct = mapscript.msIO_stripStdoutBufferContentType()
content = mapscript.msIO_getStdoutBufferString()
mapscript.msIO_resetHandlers()
tree = ET.fromstring(content)
# Strip out ordinary Service section, and replace from custom file.
tree.remove(tree.find(’Service’))
tree.insert(0,ET.parse(’./Service.xml’).getroot())
print ’Content-type: ’ + ct
print
print ET.tostring(tree)
Optimization
Table of Contents
• Debugging MapServer
– Introduction
* Links to Related Information
– Steps to Enable MapServer Debugging
* Step 1: Set the MS_ERRORFILE Variable
* Step 2: Set the DEBUG Level
* Step 3: Turn on CPL_DEBUG (optional)
* Step 4: Turn on PROJ_DEBUG (optional)
* Step 5: Test your Mapfile
* Step 6: Check your Web Server Logs
* Step 7: Verify your Application Settings
– Debugging MapServer using Compiler Debugging Tools
* Running MapServer in GDB (Linux/Unix)
– Debugging Older Versions of MapServer (before 5.0)
10.1.1 Introduction
When developing an application for the Internet, you will inevitably across problems many problems in your environ-
ment. The goal of this guide is to assist you with locating the problem with your MapServer application.
503
MapServer Documentation, Release 6.0
• MapServer Errors
Starting with MapServer 5.0, you are able to control the levels of debugging/logging information returned to you by
MapServer, and also control the location of the output log file.
In technical terms, there are msDebug() calls in various areas of the MapServer code that generate information that
may be useful in tuning and troubleshooting applications.
The MS_ERRORFILE variable is used to specify the output of debug messages from MapServer. You can pass the
following values to MS_ERRORFILE:
[filename] Full path and filename of a log file, to contain MapServer’s debug messages. Any file extension can be
used, but .log or .txt is recommended. The file will be created, if it does not already exist.
Starting with MapServer 6.0, a filename with relative path can be passed via the CONFIG MS_ERRORFILE
directive, in which case the filename is relative to the mapfile location. Note that setting MS_ERRORFILE via
an environment variable always requires an absolute path since there would be no mapfile to make the path
relative to.
stderr Use this to send MapServer’s debug messages to the Web server’s log file (i.e. “standard error”). If you are
using Apache, your debug messages will be placed in the Apache error_log file. If you are using Microsoft
IIS, your debug messages will be sent to stdout (i.e. the browser), so its use is discouraged. With IIS it is
recommended to direct output to a file instead.
stdout Use this to send MapServer’s debug messages to the standard output (i.e. the browser), combined with the rest
of MapServer’s output.
windowsdebug Use this to send MapServer’s debug messages to the Windows OutputDebugString API, allowing the
use of external programs like SysInternals debugview to display the debug output.
The recommended way to set the MS_ERRORFILE variable is in your mapfile, within the MAP object, such as:
MAP
...
CONFIG "MS_ERRORFILE" "/ms4w/tmp/ms_error.txt"
...
LAYER
...
END
END
You can also set the MS_ERRORFILE variable as an environment variable on your system. Apache users can set the
environment variable in Apache’s httpd.conf file, such as:
SetEnv MS_ERRORFILE "/ms4w/tmp/ms_error.txt"
Windows users can alternatively set the environment variable through the Windows System Properties; but make sure
to set a SYSTEM environment variable.
Note: If both the MS_ERRORFILE environment variable is set and a CONFIG MS_ERRORFILE is also set, then the
CONFIG directive takes precedence.
You can retrieve varying types of debug messages by setting the DEBUG parameter in the Mapfile. You can place the
DEBUG parameter in any LAYER in the mapfile, or instead, set it once in the MAP object so that it applies to each
layer. Use the value of the DEBUG parameter to set the type of information returned, as follows:
DEBUG Levels
Mapfile Example
The following example is the recommended method to set the DEBUG parameter:
MAP
...
CONFIG "MS_ERRORFILE" "/ms4w/tmp/ms_error.txt"
DEBUG 5
...
LAYER
...
END
END
Instead of setting the DEBUG Debug level in each of your mapfiles, you can also be set the level globally by using the
MS_DEBUGLEVEL environment variable.
When set, this value is used as the default debug level value for all map and layer objects as they are loaded by the
mapfile parser. This option also sets the debug level for any msDebug() call located outside of the context of a map or
layer object, for instance for debug statements relating to initialization before a map is loaded. If a DEBUG value is
also specified in the mapfile in some map or layer objects then the local value (in the mapfile) takes precedence over
the value of the environment variable.
Apache users can set the environment variable in Apache’s httpd.conf file, such as:
SetEnv MS_DEBUGLEVEL 5
Windows users can alternatively set the environment variable through the Windows System Properties; but make sure
to set a SYSTEM environment variable.
MapServer relies on the GDAL library to access most data layers, so you may wish to turn on GDAL debugging, to
hopefully get more information on how GDAL is accessing your data file. This could be very helpful for problems
with accessing raster files and PostGIS tables. You can trigger this GDAL output by setting the CPL_DEBUG variable
in your mapfile, within the MAP object, such as:
MAP
...
CONFIG "CPL_DEBUG" "ON"
...
LAYER
...
END
END
MapServer relies on the PROJ.4 library to handle data projections, so you may wish to turn on PROJ debugging,
to hopefully get more information back from the PROJ library. You can trigger this PROJ output by setting the
PROJ_DEBUG variable in your mapfile, within the MAP object, such as:
MAP
...
CONFIG "PROJ_DEBUG" "ON"
...
LAYER
...
END
END
Once you have set the MS_ERRORFILE and DEBUG level in your mapfile, you should now test your mapfile and read
your generated log file.
Using shp2img
The recommended way to test your mapfile is to use the MapServer commandline utility shp2img, to verify that your
mapfile creates a valid map image. shp2img should be included in your MapServer installation (MS4W users need to
execute setenv.bat before using the utility).
You can set the DEBUG level by passing the shp2img following parameters to your commandline call:
Note: If you have already set MS_ERRORFILE in your mapfile, you must comment this out in order to use these
shp2img options
Note: When using shp2img to debug, your layer’s STATUS should be set to ON or DEFAULT. If the layer’s STATUS
is set to OFF, you must additionally pass the layer name to shp2img by using the “-l layername” syntax
-all_debug Use this setting to set the debug level for the MAP object and all layers. this is the recommended switch
to use
shp2img -m spain.map -o test.png -all_debug 5
msLoadMap(): 0.002s
msDrawMap(): Layer 0 (spain provinces), 0.012s
msDrawRasterLayerLow(orthophoto): entering.
msDrawGDAL(): src=0,0,3540,2430, dst=188,48,1,1
source raster PL (-793.394,-1712.627) for dst PL (188,48).
msDrawGDAL(): red,green,blue,alpha bands = 1,2,3,0
msDrawMap(): Layer 1 (orthophoto), 0.150s
msDrawMap(): Layer 2 (urban areas), 0.004s
msDrawMap(): Layer 3 (species at risk), 0.008s
msDrawMap(): Layer 4 (populated places), 1.319s
msDrawMap(): Drawing Label Cache, 0.014s
msDrawMap() total time: 1.513s
msSaveImage() total time: 0.039s
msFreeMap(): freeing map at 0218C1A8.
freeLayer(): freeing layer at 0218F5E0.
freeLayer(): freeing layer at 030C33A0.
freeLayer(): freeing layer at 030C3BC8.
freeLayer(): freeing layer at 030C4948.
freeLayer(): freeing layer at 030C7678.
shp2img total time: 1.567s
-map_debug Use this setting to set the debug level for the MAP object only.
shp2img -m spain.map -o test.png -map_debug 5
-layer_debug Use this setting to set the debug level for one layer object only.
msDrawRasterLayerLow(orthophoto): entering.
msDrawGDAL(): src=0,0,3540,2430, dst=188,48,1,1
source raster PL (-793.394,-1712.627) for dst PL (188,48).
msDrawGDAL(): red,green,blue,alpha bands = 1,2,3,0
msDrawMap(): Layer 1 (orthophoto), 0.151s
freeLayer(): freeing layer at 02F23390.
msDrawRasterLayerLow(orthophoto): entering.
GDAL: GDALOpen(D:\ms4w\apps\spain\map/.\../data/ov172068_200904_c100u50x75c24n.jpg, this=0
4059840) succeeds as JPEG.
msDrawGDAL(): src=0,0,3540,2430, dst=188,48,1,1
source raster PL (-793.394,-1712.627) for dst PL (188,48).
msDrawGDAL(): red,green,blue,alpha bands = 1,2,3,0
GDAL: GDALDefaultOverviews::OverviewScan()
msDrawMap(): Layer 1 (orthophoto), 0.155s
freeLayer(): freeing layer at 03113390.
GDAL: GDALDeregister_GTiff() called.
Reading Errors Returned by shp2img If there is a problem with your mapfile, shp2img should output the line
number in your mapfile that is causing the trouble. The following tells us that there is a problem on line 85 of my
mapfile:
getSymbol(): Symbol definition error. Parsing error near (truetype2):(line 85)
If you are using mapfile INCLUDEs, it may be tricky to track down this line number, but most of the time the line
number is useful.
Another handy way to test your mapfile is to call the mapserv CGI executable at the commandline, such as the follow-
ing:
mapserv -nh "QUERY_STRING=map=/ms4w/apps/spain/map/spain.map&mode=map"
ON_MISSING_DATA
If you are using tile indexes to access your data, you should also be aware of the configuration settings added in
MapServer 5.4 that allow you to tell MapServer how to handle missing data in tile indexes. Please see the CONFIG
parameter’s ON_MISSING_DATA setting in the MAP object for more information.
Hint: You can check the attributes in the tileindex by executing “ogrinfo -al” on your data file
Once you have verified that there are no problems with you mapfile, next you should check your Web server log files,
for any related information that may help you narrow down your problem.
Apache
Unix users will usually find Apache’s error_log file in a path similar to:
/var/log/apache2/
Windows users will usually find Apache’s log files in a path similar to:
C:\Program Files\Apache Group\Apache2\logs
MapServer for Windows (MS4W) users will find Apache’s log files at:
\ms4w\Apache\logs
Microsoft IIS
6. At the bottom of the General Properties tab, you will see a box that contains the log file directory and the log file
name. The full log path is comprised of the log file directory plus the first part of the log file name, for example:
C:\WINDOWS\system32\LogFiles\W3SVC1\ex100507.log
You may also want to check the Windows Event Viewer logs, which is located at:
1. Go to Start -> Control Panel -> Administrative Tools
2. Computer Management
3. Event Viewer
Warning: As mentioned previously, in IIS the MapServer stderr debug output is returned to the client instead of
routed to the Web Server logs, so be sure to log the output to a file, using:
CGI Error - The specified CGI application misbehaved by not returning a complete
set of HTTP headers
This error is often caused by missing DLL files. You should try to execute “mapserv -v at the commandline, to make
sure that MapServer loads properly.
If you have verified that MapServer creates a valid map image through shp2img, you’ve checked your MapServer
log files, and there are no problems noted in your Web server logs, then you should focus your attention on possible
application configuration problems. “Application” here means how you are displaying your map images on the Web
page, such as with OpenLayers.
PHP MapScript
If you are using PHP MapScript in your application, here are some important notes for debugging:
1. Make sure your php.ini file is configured to show all errors, by setting:
display_errors = On
2. To enable debugging in PHP MapScript, if you are using MapServer 5.6.0 or more recent, make sure to define
ZEND_DEBUG in the PHP source.
If you are using MapServer < 5.6.0, then:
• open the file /mapscript/php3/php_mapscript.c
• change the following:
#define ZEND_DEBUG 0
to
#define ZEND_DEBUG 1
It is not strictly necessary to build MapServer with debugging enabled in order to use GDB on linux, but it does ensure
that more meaningful information is reported within GDB. To enable full symbolic information use the –enable-
debug configure switch. Note that use of this switch disables optimization and so it should not normally be used for
production builds where performance is important.
./configure --enable-debug <other switches>
make clean
make
To run either mapserv or shp2img, give the name of the executable as an argument to the “gdb” command. If it is not
in the path, you will need to provide the full path to the executable.
gdb shp2img
GNU gdb (GDB) 7.0-ubuntu
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /wrk/home/warmerda/mapserver/shp2img...done.
(gdb)
Once you are at the “(gdb)” prompt you can use the run command with the arguments you would normally have passed
to the mapserv or shp2img executable.
(gdb) run -m test.map -o out.png
Starting program: /wrk/home/warmerda/mapserver/shp2img -m test.map -o out.png
[Thread debugging using libthread_db enabled]
If the program is crashing, you will generally get a report like the above indicating the function the crash occurred
in, and some minimal information on why. It is often useful to request a traceback to see what functions led to the
function that crashed. For this use the “where” command.
(gdb) where
#0 0x00007ffff67594a2 in JP2KAKDataset::Identify (poOpenInfo=0x0)
at jp2kakdataset.cpp:962
#1 0x00007ffff67596d2 in JP2KAKDataset::Open (poOpenInfo=0x7fffffffb6f0)
at jp2kakdataset.cpp:1025
#2 0x00007ffff6913339 in GDALOpen (
pszFilename=0x83aa60 "/home/warmerda/data/jpeg2000/spaceimaging_16bit_rgb.jp
2", eAccess=GA_ReadOnly) at gdaldataset.cpp:2170
#3 0x00007ffff69136bf in GDALOpenShared (
pszFilename=0x83aa60 "/home/warmerda/data/jpeg2000/spaceimaging_16bit_rgb.jp
2", eAccess=GA_ReadOnly) at gdaldataset.cpp:2282
#4 0x0000000000563c2d in msDrawRasterLayerLow (map=0x81e450, layer=0x839140,
image=0x83af90, rb=0x0) at mapraster.c:566
#5 0x000000000048928f in msDrawRasterLayer (map=0x81e450, layer=0x839140,
image=0x83af90) at mapdraw.c:1390
#6 0x0000000000486a48 in msDrawLayer (map=0x81e450, layer=0x839140,
image=0x83af90) at mapdraw.c:806
#7 0x00000000004858fd in msDrawMap (map=0x81e450, querymap=0) at mapdraw.c:459
#8 0x0000000000446410 in main (argc=5, argv=0x7fffffffd918) at shp2img.c:300
(gdb)
It may also be helpful to examine variables used in the line where the crash occured. Use the print command for this.
In this case we see that the program crashed because poOpenInfo was NULL (zero). Including a traceback like the
above in bug report can help the developers narrow down a problem more quickly, especially if it is one that is difficult
for the developers to reproduce themselves.
1. Make sure that MapServer is compiled in debug mode (on unix this is enabled through ./configure –enable-
debug).
You can verify that your build was compiled in debug mode, by executing the following at the commandline
(look for “DEBUG=MSDEBUG”):
./mapserv -v
2. Set the MS_ERRORFILE variable is in your mapfile, within the MAP object, such as:
MAP
...
CONFIG "MS_ERRORFILE" "/ms4w/tmp/ms_error.txt"
...
LAYER
...
END
END
3. If you don’t use the MS_ERRORFILE variable, you can use the LOG parameter in your WEB object of the
mapfile, such as:
MAP
...
WEB
LOG "mapserver.log"
END
...
LAYER
...
END
END
4. Specify DEBUG ON in your MAP object, or in your LAYER objects, such as:
MAP
...
WEB
LOG "mapserver.log"
END
DEBUG ON
...
LAYER
...
END
END
5. Note that only errors will be written to the log file; all DEBUG output goes to stderr, in the case of Apache that
is Apache’s error_log file. If you are using Microsoft IIS, debug output is routed to stdout (i.e. the browser), so
be sure to remove DEBUG ON statements if using IIS on a production server.
.
10.2 FastCGI
Table of Contents
• FastCGI
– Introduction
– Obtaining the necessary software
– Configuration
– Common Problems
– FastCGI on Win32
10.2.1 Introduction
FastCGI is a protocol for keeping cgi-bin style web applications running as a daemon to take advantage of preserving
memory caches, and amortizing other high startup costs (like heavy database connections) over many requests.
1. There are three pieces to the MapServer FastCGI puzzle. First, you need the actual FastCGI library. This can
be downloaded from http://www.fastcgi.com/. This library does the usual configure, make, make install dance.
One added complication is that it installs by default in /usr/local, and you might give the configure command a
–prefix=/usr to put it in a location that is already visible to ldconfig.
2. Assuming you are running Apache, the next piece you need is mod_fcgi. Mod_fcgi depends on the version of
Apache you are running, so make sure to download the correct fork (Apache 1.3 vs. Apache 2).
3. The third and final piece is to compile MapServer with FastCGI support. This is pretty straightforward, and all
you need to do is tell configure where the FastCGI library is installed. If you changed the prefix variable as
described above, this would be:
With those pieces in place, the MapServer CGI (mapserv) should now be FastCGI-enabled. You can verify this by
testing it on with the command line:
[hobu@kenyon mapserver-4.4.2]# ./mapserv -v
MapServer version 4.4.2 OUTPUT=GIF OUTPUT=PNG OUTPUT=JPEG OUTPUT=WBMP
SUPPORTS=PROJ SUPPORTS=FREETYPE SUPPORTS=WMS_SERVER SUPPORTS=WMS_CLIENT
SUPPORTS=WFS_SERVER SUPPORTS=WFS_CLIENT SUPPORTS=FASTCGI INPUT=EPPL7
INPUT=SDE INPUT=ORACLESPATIAL INPUT=OGR INPUT=GDAL
INPUT=SHAPEFILE DEBUG=MSDEBUG
10.2.3 Configuration
4. Install a copy of the mapserv executable into the cgi-bin directory with the extension .fcgi (ie. mapserv.fcgi).
Use this executable when you want to utilize fastcgi support.
5. In your mapfile, set a PROCESSING directive to tell FastCGI to cache the connections and layer information
on all layers for which connection caching is desired - ie. all slow layers.
PROCESSING "CLOSE_CONNECTION=DEFER"
File permissions
Fedora Core 3 doesn’t allow FastCGI to write to the process logs (when you use RedHat’s Apache 2 rather than your
own). This is described here.
Also, FastCGI needs to write its socket information somewhere. This can be directed with the FastCgiIpcDir directive.
MS4W Users
MS4W (MapServer for Windows) >= version 2.2.2 contains MapServer compiled with FastCGI support. MS4W ver-
sion >= 2.2.8 also contains the required Apache module (mod_fcgid), and users must follow the README instructions
to setup FastCGI with their application.
Building fcgi-2.4.0
Binary IO Patch
It is critical that stdio be in binary mode when PNG and other binary images are written to it. To accomplish this for
stdio handled through the FastCGI library, I had to do the following hack to libfcgi/fcgi_stdio.c within the fcgi-2.4.0
distribution.
In FCGI_Accept() made he following change
if(isCGI) {
FCGI_stdin->stdio_stream = stdin;
FCGI_stdin->fcgx_stream = NULL;
FCGI_stdout->stdio_stream = stdout;
FCGI_stdout->fcgx_stream = NULL;
FCGI_stderr->stdio_stream = stderr;
FCGI_stderr->fcgx_stream = NULL;
} else {
I’m sure there is a better way of accomplishing this. If you know how, please let me know!
Building libfcgi
The makefile.nt should be fine. Just ensure you have run VCVARS32.BAT (as is needed for building MapServer) and
then issue the command:
nmake /f makefile.nt
Then the .lib and .dll will be in libfcgi/Debug?. Make sure you copy the DLL somewhere appropriate (such as your
cgi-bin directory).
Other Issues
1) FastCGI’s receive a very limited environment on win32, seemingly even more restricted than normal cgi’s started
by apache. Make sure that all DLLs required are either in the fastcgi directory or in windowssystem32. Any missing
DLLs will result in very cryptic errors in the error_log, including stuff about Overlapping read requests failing or
something like that.
2) Make sure you use a libfcgi.dll built against the same runtime library as your mapserv.exe (and possibly
libmap_fcgi.dll) or you will suffer a world of pain! Different runtime libraries have different “environ” vari-
ables (as well as their own stdio and heaps). You can check that everything is using MSVCRT.DLL (or all using
MSVCRTD.DLL) using the MS SDK Dependency Walker.
10.3 Mapfile
Table of Contents
• Mapfile
– Introduction
10.3.1 Introduction
The contents of a Map File are used by MapServer for configuration, data access, projection, and more. Because the
Map File is parsed every time a map image is requested, it is important to think about what you include in the file
in order to optimize performance. The optimal Map File is one that doesn’t include or reference anything that isn’t
needed.
1. Projections
There are two ways to define projections in a Map File. You can either use inline projection parameters or specify an
EPSG code for that projection. If you use the EPSG code method, Proj.4 looks up the projection parameters in the
Proj4 database using the EPSG code as an ID. This database lookup takes significantly more resources than when the
projection parameters are defined inline. This lookup takes place for each projection definition using EPSG codes in a
Map File.
Projection defined using inline projection parameters
PROJECTION
"proj=utm"
"ellps=GRS80"
"datum=NAD83"
"zone=15"
"units=m"
"north"
"no_defs"
END
Optimization Suggestions
• Use inline projection parameter definitions in place of EPSG codes.
• If you want to use EPSG codes, remove all unneeded projection definition records from the Proj.4 EPSG
database.
2. Layers
For every layer in a Map File that has a status of ON or DEFAULT, MapServer will load that layer and prepare it for
display, even if that layer never gets displayed.
Optimization Suggestions
• Build lean Map Files, only include layers that you plan to use.
• Turn off unnecessary layers; the more layers MapServer is displaying, the more time it takes. Have your opening
map view show only the minimum necessary to orient the user, and allow them to turn on additional layers as
needed. This is particularly true of remote WMS or very large rasters.
• Related to turning off layers, is turning them on but using MINSCALEDENOM and MAXSCALEDENOM to
determine at what zoomlevels the layer is available. If a map’s display is outside of the layer’s MINSCALE-
DENOM and MAXSCALEDENOM range, then MapServer can skip processing that layer. It also makes for a
really cool effect, that the national boundaries magically change to state boundaries.
• If you have a complex application, consider using multiple simple and specific Map Files in place of one large
‘do everything’ Map File.
• In a similar vein, each class also supports MINSCALEDENOM and MAXSCALEDENOM. If your dataset
has data that are relevant at different zoomlevels, then you may find this a very handy trick. For example,
give a MINSCALEDENOM of 1:1000000, county roads a MINSCALEDENOM of 1:100000, and streets a
MAXSCALEDENOM of 1:50000. You get the cool effect of new data magically appearing, but you don’t have
MapServer trying to draw the nation’s roads when the entire nation is in view!
• Classes are processed in order, and a feature is assigned to the first class that matches. So try placing the most
commonly-used classes at the top of the class list, so MapServer doesn’t have to try as many classes before
finding a match. For example, if you wanted to highlight the single state of Wyoming, you would probably do
this:
CLASS
EXPRESSION (’[NAME]’ eq ’WY’])
STYLE
COLOR 255 0 0
END
END
CLASS
STYLE
COLOR 128 128 128
END
END
But it would be a lot more efficient to do this, since 98% of cases will be matched on the first try:
CLASS
EXPRESSION (’[NAME]’ ne ’WY’])
STYLE
COLOR 128 128 128
END
END
CLASS
STYLE
COLOR 255 0 0
END
END
3. Symbols
When the Map File is loaded, each raster symbol listed in the symbols file is located on the filesystem and loaded.
Optimization Suggestions
• Only include raster symbols in your symbols file if you know that they will be used by your application.
4. Fonts
To load a font, MapServer opens up the fonts.list FONTSET file which contains an alias for the font and the path for
that font file. If you have a fonts.list file with a long list of fonts, it will take more time for MapServer to locate and
load the font that you need.
Optimization Suggestions
• Limit the entries in fonts.list to fonts that you actually use.
10.4 Raster
Author HostGIS
Revision $Revision: 8365 $
Date $Date: 2008-12-31 07:49:02 -0800 (Wed, 31 Dec 2008) $
Last Updated 2008/08/08
Table of Contents
• Raster
– Overviews
– Tileindexes and Internal Tiling
– Image formats
– Remote WMS
10.4.1 Overviews
TIFF supports the creation of “overviews” within the file, which is basically a downsampled version of the raster
data suitable for use at lower resolutions. Use the “gdaladdo” program to add overviews to a TIFF, and MapServer
(via GDAL) will automagically choose which downsampled layer to use. Note that overviews significantly increase
the disk space required by a TIFF, and in some cases the extra disk reading may offset the performance gained by
MapServer not having to resample the image. You’ll just have to try it for yourself and see how it works.
Tiling is mostly effective for cases where one commonly requests only a very small area of the image.
A tileindex is how one creates an on-the-fly mosaic from many rasters. This is described in the Tile Indexes. That
document describes common cases where a tileindex makes sense. In particular, if you have a very large raster and
most requests are for a very small spatial area within it, you may want t consider slicing it and tileindexing it.
As an alternative to slicing and mosaicing, TIFFs do support a concept of internal tiling. Like a tileindex, this is mostly
effective when the requests are for a small portion of the raster. Internal tiling is done by adding “-co TILED=YES”
to gdal_translate, e.g.:
gdal_translate -co TILED=YES original.tif tiled.tif
The TIFF image format is the fastest to “decipher”, but once you get beyond a certain point, the disk reading (since
TIFF is very large) may become slow enough to make it worthwhile to consider other image formats.
For TIFFs larger than 1 GB, ECW images tend to render faster than TIFFs, since decompressing the data (CPU and
RAM) is faster than reading the uncompressed data (disk). The downside is that ECW is not open-source, and the
licensing is often prohibitive.
JPEG2000 is a very slow image format, as is JPEG.
Remote WMS servers are often slow, especially the public ones such as TerraServer or NASA’s Landsat server. There’s
nothing you can do about that, except to reconsider when the remote WMS layer should be used.
For example, there may be a different WMS server (or a different set of imagery, or even vector outline maps) suitable
for drawing the countries or states to orient the user. You could then have the WMS layer come on at a certain scale,
or have the layer always available but turned off so the user can choose when to turn it on.
See Also:
Raster Data
Author HostGIS
Revision $Revision: 8365 $
Date $Date: 2008-12-31 07:49:02 -0800 (Wed, 31 Dec 2008) $
Last Updated 2007/08/03
Table of Contents
• Tile Indexes
– Introduction
– What is a tileindex and how do I make one?
– Using the tileindex in your mapfile
– Tileindexes may make your map faster
10.5.1 Introduction
A tileindex is a shapefile that ties together several datasets into a single layer. Therefore, you don’t need to create
separate layers for each piece of imagery or each county’s road data; make a tileindex and let MapServer piece the
mosaic together on the fly.
Making a tileindex is easy using ‘gdaltindex’ for GDAL data sources (rasters) and ‘ogrtindex’ for OGR data sources
(vectors). You just run them, specifying the index file to create and the list of data sources to add to the index.
For example, to make a mosaic of several TIFFs:
gdaltindex imagery.shp imagery/*.tif
Note: ogrtindex and gdaltindex add the specified files to the index. Sometimes you’ll have to delete the index file to
avoid creating duplicate entries.
There are two items of note here: TILEINDEX and TILEITEM. TILEINDEX is simply the path to the index file, and
TILEITEM specifies the field in the shapefile which contains the filenames referenced by the index. The TILEITEM
will usually be “LOCATION” unless you specified the -tileindex option when running gdaltindex or ogrtindex.
Two important notes about the pathnames:
• The path to TILEINDEX follows the same conventions as for any other data source, e.g. using the SHAPEPATH
or else being relative to the location of the mapfile.
• The filenames specified on the command line to gdaltindex or ogrtindex will be used with the same conventions
as well, following the SHAPEPATH or else being relative to the mapfile’s location. I find it very useful to
change into the SHAPEPATH directory and then run ogrtindex/gdaltindex from there; this ensures that I specify
the correct pathnames.
• MapServer will examine the tileindex to determine which datasets fall into the map’s view, and will open only
those datasets. This can result in a great savings for a large dataset, especially for use cases where most of the
time only a very small spatial region of the data is being used. (for example, citywide maps with nationwide
street imagery)
A tileindex will not help in the case where all/most of the data sources will usually be opened anyway (e.g. street data
by county, showing states or larger regions). In that case, it may even result in a decrease in performance, since it may
be slower to open 100 files than to open one giant file.
The ideal case for a tileindex is when the most typically requested map areas fall into very few tiles. For example,
if you’re showing state and larger regions, try fitting your data into state-sized blocks instead of county-sized blocks;
and if you’re showing cities and counties, go for county-sized blocks.
You’ll just have to experiment with it and see what works best for your use cases.
10.6 Vector
Author HostGIS
Revision $Revision: 8365 $
Date $Date: 2008-12-31 07:49:02 -0800 (Wed, 31 Dec 2008) $
Last Updated 2008/08/08
Table of Contents
• Vector
– Splitting your data
– Shapefiles
– PostGIS
– Databases in General (PostGIS, Oracle, MySQL)
If you find yourself making several layers, all of them using the same dataset but filtering to only use some of the
records, you could probably do it better. If the criteria are static, one approach is to pre-split the data.
The ogr2ogr utility can select on certain features from a datasource, and save them to a new data source. Thus, you
can split your dataset into several smaller ones that are already effectively filtered, and remove the FILTER statement.
10.6.2 Shapefiles
Use shptree to generate a spatial index on your shapefile. This is quick and easy (“shptree foo.shp”) and generates a
.qix file. MapServer will automagically detect an index and use it.
MapServer also comes with the sortshp utility. This reorganizes a shapefile, sorting it according to the values in one
of its columns. If you’re commonly filtering by criteria and it’s almost always by a specific column, this can make the
process slightly more efficient.
Although shapefiles are a very fast data format, PostGIS is pretty speedy as well, especially if you use indexes well
and have memory to throw at caching.
10.6.3 PostGIS
The single biggest boost to performance is indexing. Make sure that there’s a GIST index on the geometry column,
and each record should also have an indexed primary key. If you used shp2pgsql, then these statements should create
the necessary indexes:
ALTER TABLE table ADD PRIMARY KEY (gid);
CREATE INDEX table_the_geom ON table (the_geom) USING GIST;
PostgreSQL also supports reorganizing the data in a table, such that it’s physically sorted by the index. This allows
PostgreSQL to be much more efficient in reading the indexed data. Use the CLUSTER command, e.g.
CLUSTER the_geom ON table;
Then there are numerous optimizations one can perform on the database server itself, aside from the geospatial compo-
nent. The easiest is to increase max_buffers in the postgresql.conf file, which allows PostgreSQL to use more memory
for caching. More information can be found at the PostgreSQL website.
By default, MapServer opens and closes a new database connection for each database-driven layer in the mapfile. If
you have several layers reading from the same database, this doesn’t make a lot of sense. And with some databases
(Oracle) establishing connections takes enough time that it can become significant.
Try adding this line to your database layers:
PROCESSING "CLOSE_CONNECTION=DEFER"
This causes MapServer to not close the database connection for each layer until after it has finished processing the
mapfile and this may shave a few seconds off of map generation times.
Utilities
11.1 legend
11.1.1 Purpose
Creates a legend from a mapfile. Output is either PNG or GIF depending on what version of the GD library used.
11.1.2 Syntax