MapServer PDF
MapServer PDF
Release 6.0.3
Contents
1 2
About An Introduction to MapServer 2.1 MapServer Overview . . . . . . . . . 2.2 Anatomy of a MapServer Application 2.3 Installation and Requirements . . . . 2.4 Introduction to the Maple . . . . . . 2.5 Making the Site Your Own . . . . . . 2.6 Enhancing your site . . . . . . . . . 2.7 How do I get Help? . . . . . . . . . .
3 5 5 6 8 14 22 23 24 27 27 27 28 28 29 29 30 31 31 33 33 41 47 53 59 61
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
MapServer Tutorial 3.1 Tutorial Timeframe . . . . . . . . . . . . . . . 3.2 Tutorial Data . . . . . . . . . . . . . . . . . . 3.3 Before Using the Tutorial . . . . . . . . . . . 3.4 Windows, UNIX/Linux Issues . . . . . . . . . 3.5 Other Resources . . . . . . . . . . . . . . . . 3.6 Section 1: Static Maps and the MapFile . . . . 3.7 Section 2: CGI variables and the User Interface 3.8 Section 3: Query and more HTML Templates . 3.9 Section 4: Advanced User Interfaces . . . . . Installation 4.1 Compiling on Unix . . . . . . 4.2 Compiling on Win32 . . . . . 4.3 PHP MapScript Installation . 4.4 .NET MapScript Compilation 4.5 IIS Setup for MapServer . . . 4.6 Oracle Installation . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
Maple 67 5.1 Cartographical Symbol Construction with MapServer . . . . . . . . . . . . . . . . . . . . . . . . . 67 5.2 CLASS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 5.3 CLUSTER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
5.4 5.5 5.6 5.7 5.8 5.9 5.10 5.11 5.12 5.13 5.14 5.15 5.16 5.17 5.18 5.19 5.20 5.21 5.22 5.23 5.24 5.25 5.26 5.27 5.28 6
Display of International Characters in MapServer Expressions . . . . . . . . . . . . . . . . . . . . FEATURE . . . . . . . . . . . . . . . . . . . . FONTSET . . . . . . . . . . . . . . . . . . . . GRID . . . . . . . . . . . . . . . . . . . . . . . INCLUDE . . . . . . . . . . . . . . . . . . . . JOIN . . . . . . . . . . . . . . . . . . . . . . . LABEL . . . . . . . . . . . . . . . . . . . . . . LAYER . . . . . . . . . . . . . . . . . . . . . . LEGEND . . . . . . . . . . . . . . . . . . . . . MAP . . . . . . . . . . . . . . . . . . . . . . . OUTPUTFORMAT . . . . . . . . . . . . . . . PROJECTION . . . . . . . . . . . . . . . . . . QUERYMAP . . . . . . . . . . . . . . . . . . . REFERENCE . . . . . . . . . . . . . . . . . . SCALEBAR . . . . . . . . . . . . . . . . . . . STYLE . . . . . . . . . . . . . . . . . . . . . . SYMBOL . . . . . . . . . . . . . . . . . . . . Symbology Examples . . . . . . . . . . . . . . Templating . . . . . . . . . . . . . . . . . . . . Union Layer . . . . . . . . . . . . . . . . . . . Variable Substitution . . . . . . . . . . . . . . . WEB . . . . . . . . . . . . . . . . . . . . . . . XML Maple support . . . . . . . . . . . . . . Notes . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
121 125 135 135 137 138 139 144 148 156 157 161 164 165 166 166 167 171 173 176 186 191 191 193 194 195 195 196 233 269 271 274 277 279
MapScript 6.1 Introduction . . . . . . . . . . . . . 6.2 SWIG MapScript API Reference . . 6.3 PHP MapScript . . . . . . . . . . . . 6.4 Python MapScript Appendix . . . . . 6.5 Python MapScript Image Generation 6.6 Maple Manipulation . . . . . . . . 6.7 Querying . . . . . . . . . . . . . . . 6.8 MapScript Variables . . . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
Data Input 287 7.1 Vector Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 7.2 Raster Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 Output Generation 8.1 AGG Rendering Specics . . . . 8.2 AntiAliasing with MapServer . . 8.3 Dynamic Charting . . . . . . . . 8.4 Flash Output . . . . . . . . . . . 8.5 HTML Legends with MapServer 8.6 HTML Imagemaps . . . . . . . . 8.7 OGR Output . . . . . . . . . . . 8.8 PDF Output . . . . . . . . . . . . 8.9 SVG . . . . . . . . . . . . . . . 8.10 Tile Mode . . . . . . . . . . . . 8.11 Template-Driven Output . . . . . 8.12 Kml Output . . . . . . . . . . . . OGC Support and Conguration 371 371 373 377 381 387 395 398 402 407 413 418 423 431
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
9 ii
9.1 9.2 9.3 9.4 9.5 9.6 9.7 9.8 9.9 9.10 9.11 9.12 9.13 9.14
Mapserver OGC Specication support . . . . . . . . . . . . . . . WMS Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . WMS Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . WMS Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Map Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . WFS Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . WFS Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . WFS Filter Encoding . . . . . . . . . . . . . . . . . . . . . . . . SLD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . WCS Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . WCS Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . SOS Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . How to set up MapServer as a client to access a service over https MapScript Wrappers for WxS Services . . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
431 431 455 462 466 473 482 486 493 503 520 525 537 539 547 547 558 561 563 565 566 569 569 569 571 571 573 574 575 576 578 579 583 583 585 585 586 586 587 592 595 597 597 598 599 599
10 Optimization 10.1 Debugging MapServer 10.2 FastCGI . . . . . . . . 10.3 Maple . . . . . . . . 10.4 Raster . . . . . . . . . 10.5 Tile Indexes . . . . . 10.6 Vector . . . . . . . . . 11 Utilities 11.1 legend . . . . . 11.2 msencrypt . . . 11.3 scalebar . . . . . 11.4 shp2img . . . . 11.5 shptree . . . . . 11.6 shptreetst . . . . 11.7 shptreevis . . . . 11.8 sortshp . . . . . 11.9 sym2img . . . . 11.10 tile4ms . . . . . 11.11 Batch Scripting . 11.12 File Management 12 CGI 12.1 12.2 12.3 12.4 12.5 12.6
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
MapServer CGI Introduction . mapserv . . . . . . . . . . . . Map Context Files . . . . . . MapServer CGI Controls . . . Run-time Substitution . . . . A Simple CGI Wrapper Script
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
13 Community Activities 13.1 IRC . . . . . . . . . . . . . . 13.2 Mailing Lists . . . . . . . . . 13.3 MapServer Wiki Pages . . . . 13.4 MapServer Service Providers
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
14 Development 601 14.1 Sponsors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601 14.2 MapServer Release Plans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602 14.3 Announcements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605 iii
Bug Submission . . . . . . . . . . Subversion . . . . . . . . . . . . . Documentation Development Guide Testing . . . . . . . . . . . . . . . Request for Comments . . . . . . . Maple Editing . . . . . . . . . . . External Links . . . . . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
607 608 609 617 623 868 870 871 871 872 872 873 875 879 883 883 883 884 885 885 885 885 886 886 887 887 888 888 888 889 889 889 889 889 890 891 891 891 892 892 892 892 893 893 893 894 894 895 896
15 Download 15.1 Source . . . . . . 15.2 Documentation . . 15.3 Binaries . . . . . . 15.4 Demo Application 16 Environment Variables 17 Glossary
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
18 Errors 18.1 drawEPP(): EPPL7 support is not available . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.2 loadLayer(): Unknown identier. Maximum number of classes reached . . . . . . . . . . . . . . . . 18.3 loadMapInternal(): Given map extent is invalid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.4 msGetLabelSize(): Requested font not found . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.5 msLoadFontset(): Error opening fontset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.6 msLoadMap(): Failed to open map le . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.7 msProcessProjection(): no options found in init le . . . . . . . . . . . . . . . . . . . . . . . . . . 18.8 msProcessProjection(): No such le or directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.9 msProcessProjection(): Projection library error.major axis or radius = 0 not given . . . . . . . . . . . 18.10 msQueryByPoint: search returned no results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.11 msReturnPage(): Web application error. Malformed template name . . . . . . . . . . . . . . . . . . 18.12 msSaveImageGD(): Unable to access le . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.13 msWMSLoadGetMapParams(): WMS server error. Image Size out of range, WIDTH and HEIGHT must be between 1 and 2048 pixels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18.14 Unable to load dll (MapScript) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 FAQ 19.1 19.2 19.3 19.4 19.5 19.6 19.7 19.8 19.9 19.10 19.11 19.12 19.13 19.14 19.15 19.16 19.17 19.18 19.19 iv
Where is the MapServer log le? . . . . . . . . . . . . . . . . . . . . . What books are available about MapServer? . . . . . . . . . . . . . . . How do I compile MapServer for Windows? . . . . . . . . . . . . . . . What do MapServer version numbers mean? . . . . . . . . . . . . . . . Is MapServer Thread-safe? . . . . . . . . . . . . . . . . . . . . . . . . . What does STATUS mean in a LAYER? . . . . . . . . . . . . . . . . . . How can I make my maps run faster? . . . . . . . . . . . . . . . . . . . What does Polyline mean in MapServer? . . . . . . . . . . . . . . . . . What is MapScript? . . . . . . . . . . . . . . . . . . . . . . . . . . . . Does MapServer support reverse geocoding? . . . . . . . . . . . . . . . Does MapServer support geocoding? . . . . . . . . . . . . . . . . . . . How do I set line width in my maps? . . . . . . . . . . . . . . . . . . . Why do my JPEG input images look crappy via MapServer? . . . . . . . Which image format should I use? . . . . . . . . . . . . . . . . . . . . . Why doesnt PIL (Python Imaging Library) open my PNGs? . . . . . . . Why do my symbols look poor in JPEG output? . . . . . . . . . . . . . How do I add a copyright notice on the corner of my map? . . . . . . . . How do I have a polygon that has both a ll and an outline with a width? How can I create simple antialiased line features? . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
Which OGC Specications does MapServer support? . . . . . . . . . . . . . . . . . . . . . . Why does my requested WMS layer not align correctly? . . . . . . . . . . . . . . . . . . . . When I do a GetCapabilities, why does my browser want to download mapserv.exe/mapserv? Why do my WMS GetMap requests return exception using MapServer 5.0? . . . . . . . . . . Using MapServer 6.0, why dont my layers show up in GetCapabilities responses or are not anymore? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Where do I nd my EPSG code? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . How can I reproject my data using ogr2ogr? . . . . . . . . . . . . . . . . . . . . . . . . . . How can I help improve the documentation on this site? . . . . . . . . . . . . . . . . . . . . Whats with MapServers logo? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . found . . . . . . . . . . . . . . . . . . . .
897 897 898 898 899 899 899 900 900 901 903 905 907
vi
If you plan on upgrading to the MapServer 6.0 release, be sure to review the MapServer Migration Guide.
Table 1: Quick Links An Introduction to MapServer MapScript OGC Support and Conguration Development genindex Installation Data Input Optimization Glossary About Maple Output Generation Utilities Errors Community Activities
Contents
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
ESRI shaples, PostGIS, ESRI ArcSDE, Oracle Spatial, MySQL and many others via OGR Map projection support On-the-y map projection with 1000s of projections through the Proj.4 library
Chapter 1. About
CHAPTER 2
An Introduction to MapServer
Revision $Revision$ Date $Date$ Author Jeff McKenna Contact jmckenna at gatewaygeomatics.com Author David Fawcett Contact david.fawcett at moea.state.mn.us Author Howard Butler Contact hobu.inc at gmail.com Contents An Introduction to MapServer MapServer Overview Anatomy of a MapServer Application Installation and Requirements Introduction to the Maple Making the Site Your Own Enhancing your site How do I get Help?
high quality rendering fully customizable application output many ready-to-use Open Source application environments In its most basic form, MapServer is a CGI program that sits inactive on your Web server. When a request is sent to MapServer, it uses information passed in the request URL and the Maple to create an image of the requested map. The request may also return images for legends, scale bars, reference maps, and values passed as CGI variables. See Also: The Glossary contains an overview of many of the jargon terms in this document. MapServer can be extended and customized through MapScript or templating. It can be built to support many different vector and raster input data formats, and it can generate a multitude of output formats. Most pre-compiled MapServer distributions contain most all of its features. See Also: Compiling on Unix and Compiling on Win32 Note: MapScript provides a scripting interface for MapServer for the construction of Web and stand-alone applications. MapScript can be used independently of CGI MapServer, and it is a loadable module that adds MapServer capability to your favorite scripting language. MapScript currently exists in PHP, Perl, Python, Ruby, Tcl, Java, and .NET avors. This guide will not explicitly discuss MapScript, check out the MapScript Reference for more information.
Initialization File - uses a form with hidden variables to send an initial query to the web server and MapServer. This form could be placed on another page or be replaced by passing the initialization information 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 le that receives requests and returns images, data, etc. It sits in the cgi-bin or scripts directory of the web 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 Web/HTTP Server - serves up the HTML pages when hit by the users browser. You need a working Web (HTTP) server, such as Apache or Microsoft Internet Information Server, on the machine on which you are installing MapServer.
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 Webs subpackages, 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.
10
6. Run the apache-install.bat script to install the Apache Service. Note: You must run this script under the OSGeo4W Shell. This is usually available as a shortcut on your desktop
Note: An apache-uninstall.bat script is also available to remove the Apache service installation. 7. Start Apache from the OSGeo4W shell and navigate to http://127.0.0.1
apache-restart.bat
11
12
13
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 prociency 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.
Note: Comments in a maple are specied with a # character MapServer parses maples from top to bottom, therefore layers at the end of the maple 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)
14
Figure 2.2: Rendered Bluemarble Image The above example is built on the following directory structure: The maple could be placed anywhere, as long as it is accessible to the web server. Normally, one would try to avoid placing it at a location that makes it accessible on the web. Let us say it is placed in /home/msuser/maples/ The location of the font le is given relative to the map le, in this case: /home/msuser/etc/fonts.txt The location of the datasets (bluemarble.gif ) is given relative to the map le, in this case: /home/msuser/data/ The location of the symbol le is given relative to the map le, in this case: /home/msuser/etc/symbols.txt The les generated by Mapserver will be placed in the directory /ms4w/tmp/ms_tmp/. The web server must be able to place les in this directory. The web server must make this directory available as /ms_tmp (if the web server is on www.ms.org, the web address to the directory must be: httpd://www.ms.org/ms_tmp/.
EXTENT is the output extent in the units of the output map SIZE is the width and height of the map image in pixels IMAGECOLOR is the default image background color
15
Note: MapServer currently uses a pixel-center based extent model which is a bit different from what GDAL or WMS use.
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 # STYLE END # CLASS END # LAYER
16
CLASS NAME "Primary Roads" STYLE SYMBOL "circle" COLOR 178 114 1 SIZE 15 END # STYLE STYLE SYMBOL "circle" COLOR 254 161 0 SIZE 7 END # STYLE END # CLASS
2.4.4 SYMBOLs
can be dened directly in the maple, or in a separate le the separate le method must use the SYMBOLSET parameter in the MAP object:
MAP NAME "sample" EXTENT -180 -90 180 90 # Geographic SIZE 800 400 IMAGECOLOR 128 128 255 SYMBOLSET "../etc/symbols.txt" END # MAP
17
18
Figure 2.5: Rendered Bluemarble image with skier symbol See Also: Cartographical Symbol Construction with MapServer, Symbology Examples, and SYMBOL
2.4.5 LABEL
dened within a CLASS object the LABELITEM parameters in the LAYER object can be used to specify an attribute in the data to be used for labeling. The label is displayed by the FONT, declared in the FONTSET le (set in the MAP object). The 2.4. Introduction to the Maple 19
FONTSET le contains references to the available font names. ENCODING describes which encoding is used in the le (see Display of International Characters in MapServer). An example LABEL object that references one of the above fonts might look like:
LABEL FONT "sans-bold" TYPE truetype ENCODING "UTF-8" SIZE 10 POSITION LC PARTIALS FALSE COLOR 100 100 100 OUTLINECOLOR 242 236 230 END # LABEL
Figure 2.6: Rendered Bluemarble image with skier symbol and a label See Also: LABEL, FONTSET
20
EXPRESSION "africa"
2. Regular expressions
EXPRESSION /^9|^10/
3. Logical expressions
EXPRESSION ([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 maple can now be stored in a separate le and added to the main maple using the INCLUDE parameter. The lename to be included can have any extension, and it is always relative to the main .map le. Here are some potential uses: LAYERs can be stored in les and included to any number of applications STYLEs can also be stored and included in multiple applications The following is an example of using maple includes to include a layer denition in a separate le: If shadedrelief.lay contains:
LAYER NAME shadedrelief STATUS ON TYPE RASTER DATA GLOBALeb3colshade.jpg END # LAYER
The following is an example of a maple where all LAYER s are in separate .lay les, and all other objects (WEB, REFERENCE, SCALEBAR, etc.) are stored in a .ref le:
MAP 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"
21
You can also send a HTTP request directly to the MapServer CGI program without passing any conguration variables (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.
22
2.5.4 Projections
Because the earth is round and your monitor (or paper map) is at, distortions will occur when you display geographic data in a two-dimensional image. Projections allow you to represent geographic data on a at 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 Longitude), you do not need to include any projection info in your Map File. In building your rst MapServer application, this simplication is recommended. On-the-y 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.
23
2.6.4 Interfaces
See: OpenLayers http://openlayers.org
24
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.5 Gallery
See examples (currently shut down) of existing MapServer applications.
2.7.6 Tutorial
Perry Nacionales built a great Tutorial on how to build a MapServer application (Mapserver version 5).
2.7.8 Books
Web Mapping Illustrated, a 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. According to the publisher, it covers installation and conguration, basic MapServer topics and features, incorporation of dynamic data, advanced topics, MapScript, and the creation of an actual application.
25
26
CHAPTER 3
MapServer Tutorial
Author Pericles S. Nacionales Contact pnaciona at gmail.com Author Jeff McKenna Contact jmckenna at gatewaygeomatics.com Updated 2010-04-07 This tutorial was designed to give new users a quick (relatively speaking) introduction to the concepts behind MapServer. It is arranged into four sections with each section having one or more examples and increasing in complexity. Users can jump to any section at any time although it is recommended that absolute beginners work on the rst three sections sequentially. Section one focuses on basic MapServer conguration concepts such as layer and class ordering, using vector and raster data, projections and labeling. Section two provides examples on how to use HTML templates to create a simple interface for an interactive web mapping application. Section three introduces the use of HTML templates to provide a query interface. Finally, section four introduces some advanced user interface concepts.
27
Download the data (and all html les) for this tutorial at http://download.osgeo.org/mapserver/docs/mapservertutorial.zip.
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 le. However, if you plan to move your application to UNIX at some point, youll have the tedious task of switching all backslashes to slashes. While were on the subject of paths, keep in mind that paths in maples are typically relative to the systems root directory: the slash (/) in UNIX or some drive letter (C:) in Windows. This is true except when specically asked to enter a URL or when referencing a URL. When working with HTML template les, paths are relative to the web servers 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. 28 Chapter 3. MapServer Tutorial
3.4.2 Executable
Another issue is that UNIX executable les dont 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 /cgibin/mapserv.exe or /cgi-bin/mapserv50.exe.
29
3.7.2 Examples
So, lets build an interactive interface for our application... Users of a web mapping application should be able to pan and zoom on the map: Example 2.1 - Pan and Zoom Controls They also should be able to turn on and off layers on a map: Example 2.2 - Layer Control A map should always include a scalebar. Example 2.3 - Adding a Scalebar If users are to navigate through the map, a reference map should be provided: Example 2.4 - Adding a Reference Map The map should include a legend. Example 2.5- Adding a Legend
30
Begin tutorial
31
32
CHAPTER 4
Installation
4.1.1 Introduction
The University of Minnesotas 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.
33
34
Chapter 4. Installation
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. Minimum libgd versions MapServer aggressively takes advantage of new features and bug xes 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 x for antialiased lines. Congure 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 systems libgd, ensure that you have the development package also installed so MapServer can nd and use the appropriate headers. MacOSX A useful FAQ on for libgd on OSX is available at http://www.libgd.org/DOC_INSTALL_OSX 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 its own interface to FreeType, using it through GD instead. When you run your congure 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 its 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 congure script looks for the FreeType library separately as well, generating output looking somewhat like this:
35
checking where FreeType is installed... checking for FT_Init_FreeType in -lfreetype... yes using libfreetype -lfreetype from system libs.
Even though you have FreeType installed on your system and the congure script nds it, does NOT mean you will have TrueType font support. GD MUST be compiled against FreeType either way. 1px Anti-Aliasing and segfaults Versions of libgd earlier than 2.0.34 contain a one very signicant bug and will always cause a segfault if you attempt to do one pixel wide antialiasing. You can manually patch older gds, 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. Curved label support 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. Congure should autodetect if you have a sufcient libgd and TrueType support to be able to use this feature.
Support for this specication is automatically enabled when you include PROJ.4 support. (with-proj) You can check this yourself by looking for the following in your congure output:
checking whether we should include WMS support... OGC WMS compatibility enabled (-DUSE_WMS).
36
Chapter 4. Installation
If, for some reason you DONT want WMS support, you can force it off by passing without-wms to your congure 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 nal map. In order to enable this feature, you will need to pass the with-wmsclient option to the congure 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 congure 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 specically 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 specication is enabled by passing the congure script the with-wfs option. OGR and PROJ.4 support is required. You can check this yourself by looking for the following in your congure 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 specically 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 its data from a remote servers WFS output and renders it into a map, just like it would when reading data from a shapele. 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 congure 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 congure 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 specically request it. More information on using this feature is available in the WFS Client HOWTO available on the MapServer website.
37
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 specied:
--with-sde=/opt/sdeexe90 --with-sde-version=90
Oracle Spatial Oracles 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 congure script. You will very likely need an ORACLE_HOME environment variable set to have it congure 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 attempting 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 shouldnt have too much trouble nding binaries of the libraries that GD requires, and often, they will already be installed with your system. On unix, Ive had very little luck nding 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 rst. I often nd 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 congure/make/make install library.
38
Chapter 4. Installation
4. Compile libcurl. libcurl is a straight-forward congure/make/make install library. 5. Compile/install optional libraries. These might include SDE, PostGIS, Oracle Spatial, AGG, Ming, PDFlib, or MyGIS. Mix and match as you need them. 6. Unpack the MapServer tarball and cd into the mapserver directory:
[user@host user]$ tar -zxvf mapserver-X.Y.Z.tar.gz
7. Congure your environment using congure. I often place my congure command in its own le and changes its mode to be executable (+x) to save typing and have a record of how MapServer was congured.
./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 congured your build options and selected all the libraries you wish mapserver to use, youre 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 le 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.
39
4.1.8 Installation
MapServer binary The MapServer program itself consists of only one le, 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 conguration le), or have someone (such as your webmaster) help you with the conguration details. The main goal is to get the mapserv binary installed in a publicly accessible directory that is congured to run CGI programs and scripts.
The basic install
Under a default conguration, the CGI directory is /usr/local/apache/cgi-bin (RedHat users will use /home/httpd/cgi-bin). Placing the mapserv le 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, youre 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 servers CGI Directory. Ask your webmaster to install the le 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 le world executable is perfectly ne 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 conguration isnt 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 servers error log to nd out more, and may need to enlist the help of your webmaster/system administrator. Where to go once youve got it compiled The An Introduction to MapServer document provides excellent coverage of getting started with MapServer.
40
Chapter 4. Installation
4.2.1 Introduction
This document provides a simple set of compilation procedures for MapServer on Win32 platforms. If youve 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 sufcient 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 specic 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 x bugs or even to implement new features in MapServer. To make it easy for users and developers, Ive 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 Ive 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,
41
editing the make les, and invoking Microsofts 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.
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 youre ready to download the source codes.
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/oldgnu/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 download this library at http://www.ijg.org/les/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-y 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 les. This library is set as a default library in MapServer so theres 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 y 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-y projection support so we need to download GD, regex, and Proj.4 libraries. Go ahead and get those libraries.
43
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 le, 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. Heres 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 rst. D. Make sure the regex path is set correctly. In order for the delete command in the nmake /f makele.vc clean target to work properly it is necessary to use backslashes in the REGEX_DIR denition.
# # # # # # 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
44
Chapter 4. Installation
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 MapServers nmake.opt to replace the CURL_LIB variable with this line:
CURL_LIB = $(CURL_DIR)/lib/libcurl_imp.lib
Now issue the command: nmake /f Makele.vc and wait for it to nish compiling. If it compiles successfully, you should get mapserver.lib, libmap.dll, mapserv.exe, and other .EXE les. Thats 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.
6. Dene the following in the nmake.opt for MapServer: POSTGIS =-DUSE_POSTGIS POSTGIS_DIR =c:/projects/postgresql-8.0.1/src
45
7. nmake /f makele.vc 8. dont forget to copy libpq.dll (from C:projectspostgresql-8.0.1srcinterfaceslibpqrelease) into a location where MapServer can nd it.
This occurs if you have not properly dened 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 le we are most interested in is mapserv.exe. The other executable les 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.
46
Chapter 4. Installation
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. Id suggest making a subdirectory called bin under the directory projects and copy the executables to that subdirectory. You might nd these programs useful as you develop MapServer applications.
4.2.13 Acknowledgements
Thanks to Assefa Yewondwossen for providing the Makele.vc. I would not have been able to write this HOWTO without that le. 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.
47
4.3.1 Introduction
The PHP/MapScript module is a PHP dynamically loadable module that makes MapServers 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 dont have ready access to a pre-compiled installation and need to compile your own copy of MapServer with the PHP/MapScript module. Which version of PHP is supported? 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 How to Get More Information on the PHP/MapScript Module for MapServer For a list of all classes, properties, and methods available in the module see the PHP MapScript 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
Download PHP and PHP/MapScript The PHP source or the Win32 binaries can be obtained from the PHP web site. Once you have veried that PHP is installed and is running, you need to get the latest MapServer source and compile MapServer and the PHP module. Setting Up PHP on Your Server Unix Check if you have PHP already installed (several Linux distributions have it built in). If not, see the PHP manuals Installation on Unix systems section. Windows
48
Chapter 4. Installation
MS4W (MapServer For Windows) is a package that contains Apache, PHP, and PHP/MapScript ready to use in a simple ziple. Several Open Source applications are also available for use in MS4W. 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.nets 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 congured 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).
Build/Install the PHP/MapScript Module Building on a Linux Box NOTE: For UNIX users, see the README.CONFIGURE le in the MapServer source, or see the Compiling on Unix HowTo. The main MapServer congure script will automatically setup the main makele to compile php_mapscript.so if you pass the with-php=DIR argument to the congure script. Copy the php_mapscript.so library to your PHP extensions directory, and then use the dl() function to load the module at the beginning of your PHP scripts. See also the PHP function extension_loaded() to check whether an extension is already loaded. The le mapscript/php3/examples/phpinfo_mapscript.phtml will test that the php_mapscript module is properly installed and can be loaded. If you get an error from PHP complaining that it cannot load the library, then make sure that you recompiled and reinstalled PHP with support for dynamic libraries. On RedHat 5.x and 6.x, this means adding -rdynamic to the CLDFLAGS in the main PHP3 Makele after running ./congure Also make sure all directories in the path to the location of php_mapscript.so are at least r-x for the HTTPd user (usually nobody), otherwise dl() may complain that it cannot nd the le even if its there. Building on Windows For Windows users, it is recommended to look for a precompiled binary for your PHP version on the MapServer download page or on MapTools.org. If for some reason you really need to compile your own Windows binary then see the README.WIN32 le in the MapServer source (good luck!). Installing PHP/MapScript Simply copy the le 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 le containing the following code and try to access it through your web server:
<HTML> <BODY> <?php if (PHP_OS == "WINNT" || PHP_OS == "WIN32")
49
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. Example Steps of a Full Windows Installation Using MS4W (MapServer for Windows) 1. Download the latest MS4W base package. 2. Extract the les in the archive to the root of one of your drives (e.g. C:/ or D:/). 3. Double-click the le /ms4w/apache-install.bat to install and start the Apache Web server. 4. In a web browser goto http://127.0.0.1. You should see an MS4W opening page. You are now running PHP, PHP/MapScript, and Apache. 5. You can now optionally install other applications that are pre-congured for MS4W, which are located on the MS4W download page. Manual Installation Using Apache Server 1. Download the Apache Web Server and extract it to the root of a directory (eg. D:/Apache). 2. Download PHP4 and extract it to your Apache folder (eg. D:/Apache/PHP4). 3. Create a temp directory to store MapServer created GIFs. NOTE: This directory is specied in the IMAGEPATH parameter of the WEB Object in the Maple reference. For this example we will call the temp directory ms_tmp (eg. E:/tmp/ms_tmp). 4. Locate the le httpd.conf in the conf directory of Apache, and open it in a text viewer (eg. TextPad, Emacs, Notepad). In the Alias section of this le, add aliases to the ms_tmp folder and any other folder you require (for this example we will use the msapps folder):
Alias Alias /ms_tmp/ /msapps/ "path/to/ms_tmp/" "path/to/msapps/"
In the ScriptAlias section of this le, add an alias for the PHP4 folder.
ScriptAlias /cgi-php4/ "pathto/apache/php4/"
In the AddType section of this le, add a type for php4 les.
AddType application/x-httpd-php4 .php
In the Action section of this le, add an action for the php.exe le.
50
Chapter 4. Installation
Action application/x-httpd-php4
"/cgi-php4/php.exe"
5. Copy the le php4.ini-dist located in your Apache/php4 directory and paste it into your WindowsNT folder (eg. c:/winnt), and then rename this le to php.ini in your WindowsNT folder. 6. If you want specic extensions loaded by default, open the php.ini le in a text viewer and uncomment the appropriate extension. 7. Place the le php_mapscript.dll into your Apache/php4/extensions folder. Installation Using Microsofts 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 eld 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 Conguration 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 le 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 specied in the IMAGEPATH parameter of the WEB Object in the Maple. 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 directory). 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.
51
The MapServer Wiki also has PHP/MapScript build and installation notes and some php code snippets.
Q Where can I nd sample scripts? A Some examples are included in directory mapserver/mapscript/php3/examples/ in the MapServer source distribution. A good one to get started is test_draw_map.phtml: its a very simple script that just draws a map, legend and scalebar in an HTML page. A good intermediate example is the PHP MapScript By Example guide (note that this document was created for an earlier MapServer version but the code might be still useful). The next example is the GMap demo. You can download the whole source and data les from the MapTools.org download page. Questions About Installation Q How can I tell that the module is properly installed on my server? A Create a le called phpinfo.phtml with the following contents:
<?php ?> dl("php_mapscript.so"); phpinfo();
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 le and inserts its map, legend, and scalebar in an HTML page. Modify the page to access one of your own MapServer .map les, and if you get the expected result, then everything is probably working ne.
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 le extension. Assuming youre 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 MapServers congure as a system lib but at runtime I get an error: libproj.so.0: No such le 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. (Im still surprised that congure picked proj.4 as a system lib since its not in the systems lib path...probably something magic in autoconf that well have to look into) There are a couple of possible solutions: 52 Chapter 4. Installation
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/ldcong. This will permanently add /usr/local/lib to your systems runtime lib path. 3. Congure MapServer with the following options:
--with-proj=/usr/local --enable-runpath
and the /usr/local/lib directory will be hardcoded in the exe and .so les I (Daniel Morissette) personally prefer option #2 because it is permanent and applies to everything running on your system.
Q Does PHP/MapScript have to be setup as a CGI? If so, why? A Yes, please see the PHP/MapScript CGI page in the MapServer Wiki for details.
Q I have compiled PHP as a CGI and when PHP tries to load the php_mapscript.so, I get an undened symbol: _register_list_destructors error. Whats wrong? A Your PHP CGI executable is probably not linked to support loading shared libraries. The MapServer congure script must have given you a message about a ag to add to the PHP Makele to enable shared libs. Edit the main PHP Makele and add -rdynamic to the LDFLAGS at the top of the Makele, then relink your PHP executable. Note: The actual parameter to add to LDFLAGS may vary depending on the system youre running on. On Linux it is -rdynamic, and on *BSD it is -export-dynamic.
Q What are the best combinations of MapScript and PHP versions? A The best combinations are: MapScript 4.10 with PHP 5.2.1 and up MapScript 4.10 with PHP 4.4.6 and up
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-specic 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.
Win32 compilation targeting the MS.NET framework 1.1 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 makele.vc and set the SWIG variable to the location of your swig.exe Use:
nmake -f makefile.vc
to compile mapscript.dll and mapscript_csharp.dll. Win32 compilation targeting the MS.NET framework 2.0 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 makele.vc and set the SWIG variable to the location of your swig.exe. Use:
nmake -f makefile.vc
to compile mapscript.dll and mapscript_csharp.dll. Win32 compilation targeting the MONO framework Before the compilation you should download and install the recent mono Win32 setup package (eg. mono-1.1.13.2gtksharp-2.8.1-win32-1.exe) Edit makele.vc and set the CSC variable to the location of your mcs.exe. Alternatively you can dene:
MONO = YES
in your nmake.opt le. You should use the same compiler for compiling MapScript as the compiler has been used for the MapServer compilation. To compile MapScript open the Command Prompt supplied with your compiler and use:
nmake -f makefile.vc
54
Chapter 4. Installation
Alternative compilation methods on Windows 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. Testing the compilation 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. Linux compilation targeting the MONO framework Before the compilation you should download and install the recent mono Linux package. Some distributions have precompiled 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 congured and compiled. Beginning from MapServer 4.8.2 during conguration the mapscript/csharp/Makele will be created according to the conguration options. Edit this le and set the SWIG and CSC for the corresponding executable pathes if the les could not be accessed by default. To compile at a console step into the /mapscript/csharp directory use:
make
to compile libmapscript.so and mapscript_csharp.dll. For testing the compilation and the runtime environment you can use:
make test
for starting the sample applications compiled previously. OSX compilation targeting the MONO framework Beginning from 4.10.0 the csharp/Makele supports the OSX builds. Before making the build the recent MONO package should be installed on the system. 4.4. .NET MapScript Compilation 55
Before compiling MapScript, MapServer should be congured and compiled. Beginning from MapServer 4.8.2 during conguration the mapscript/csharp/Makele will be created according to the conguration options. Edit this le and set the SWIG and CSC for the corresponding executable pathes if the les could not be accessed by default. To compile at a console step into the /mapscript/csharp directory use:
make
to compile libmapscript.dylib and mapscript_csharp.dll. For testing the compilation and the runtime environment you can use:
make test
for starting the sample applications compiled previously. To run the applications mapscript_csharp.dll.cong is needed along with the mapscript_csharp.dll le. This le is created during the make process
4.4.2 Installation
The les required for your application should be manually installed. It is highly recommended to copy the les into the same folder as the executable resides.
56
Chapter 4. Installation
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 le 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. Manifests for the dll-s must be embedded as a resource According to the windows makele the MapScript compilation target (mapscript.dll) is linked with the /MD option. In this case the VS2005 linker will generate a manifest le containing the unmanaged assembly dependency. The sample contents of the manifest le are:
<?xml version=1.0 encoding=UTF-8 standalone=yes?> <assembly xmlns=urn:schemas-microsoft-com:asm.v1 manifestVersion=1.0> <dependency> <dependentAssembly> <assemblyIdentity type=win32 name=Microsoft.VC80.CRT version=8.0.50608.0 processorArchitecture=x86 publicKeyToken=1fc8b3b9a1e18e3b /> </dependentAssembly> </dependency> </assembly>
Like previously mentioned if you are creating a windows application the common language runtime will search for a manifest le for the application. The name of the manifest le 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. Issue with regex and Visual Studio 2005 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 C# MapScript library name mapping with MONO 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 le name is platform dependent. On Windows the library name is simply appended with the .dll extension (mapscript.dll). On the Unix systems the library le name normally starts with the lib prex and appended with the .so extension (libmapscript.so).
57
Mapping of the library name may be manually controlled using a dll.cong le. This simply maps the library le the DllImport is looking for to its unix equivalent. The le normally contains the following information (mapscript_csharp.dll.cong):
<configuration> <dllmap dll="mapscript" target="libmapscript.so" /> </configuration>
The le should be placed along with the corresponding mapscript_csharp.dll le, 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 Localization issues with MONO/Linux 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 maple contains oat 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
58
Chapter 4. Installation
4.5.2 Php.ini le
session.save_path (absolute path to your tmp directory) extension_dir (relative path to your php/extensions directory) cgi.force_redirect = 0</li> enable the pg_sql extension (php_pgsql.dll) (for Postgresql)
59
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 Security 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 executables. 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.
60
Chapter 4. Installation
gmap Good for testing purposes. Remember to change your maples as discussed in Maples 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.
4.6.1 Preface
This document explains the whole conguration 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! 4.6. Oracle Installation 61
This manual was written, because I spent several days googling around to get my UMN having access to an oracle database. Im 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 didnt 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
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, youre ne using User/Password@MY_ORACLE in your maple to connect to the oracle database. But rst we have to do some more stuff.
62
Chapter 4. Installation
$ echo export ORACLE_HOME=/path/to/oracle/home >> /etc/profile # **(e.g. ORACLE_HOME=/app/oracle/ora10g) $ echo export ORACLE_BASE=path/to/oracle >> /etc/profile # **(e.g. ORACLE_HOME=/app/oracle) $ echo export ORACLE_SID=MY_ORACLE >> /etc/profile $ echo export LD_LIBRARY_PATH=path/to/oracle/home/lib >> /etc/profile # **(e.g. ORACLE_HOME=/app/oracle/ora10g/lib)
The command comes silent, so there is no system output if you didnt mistype anything! Setting the Apache Environment Sometimes it is confusing WHERE to set WHAT in the splitted apache2.conf-les. In the folder /etc/apache2/sites_available you nd your sites-le. If you did not do sth. Special e.g. installing virtual hosts, the le is named default. In this le, the apache cgi-directory is dened. Our le 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 le, 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 le. Then restart apache:
63
$ /etc/init.d/apache2 force-reload
Create maple Before we start creating our maple 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 DATA GEOM FROM MY_LAYER USING SRID 82032 [...] Where: GEOM is the name of the geometry column MY_LAYER the name of the table 82032 is equivalent to the EPSG code 31468 (German projection system) Testing & Error handling So you are ne now. Load the maple 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, lets check, if the maple is all right. Therefore we use the MapServer utility program shp2img. Lets assume you are in the directory, where you compiled MapServer and run shp2img:
$ cd /var/src/mapserver_version/ $ shp2img -m /path/to/mapfile/mapfile.map -i png -o /path/to/output/output.png
If not, this possibly points you towards any error in your maple 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 maple syntax and/or the environment settings for Oracle. For Debian/Ubuntu its worth also checking the le /etc/environment and test-wise to add the system variables comparable to System Variables
64
Chapter 4. Installation
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 conguration. Please note, that the apache.cong le differs in several linux-distributions. For this paper we talk about Ubuntu, which should be the same as Debian.
65
66
Chapter 4. Installation
CHAPTER 5
Maple
Author Steve Lime Contact steve.lime at dnr.state.mn.us Author Jeff McKenna Contact jmckenna at gatewaygeomatics.com Author Jean-Franois Doyon Contact jdoyon at ccrs.nrcan.gc.ca The Maple is the heart of MapServer. It denes the relationships between objects, points MapServer to where data are located and denes how things are to be drawn. The Maple consists of a MAP object, which has to start with the word MAP. There are some important concepts that you must understand before you can reliably use maples to congure MapServer. First is the concept of a LAYER. A layer is the combination of data plus styling. Data, in the form of attributes plus geometry, are given styling using CLASS and STYLE directives. See Also: An Introduction to MapServer for An Introduction to the Maple
67
Table of Contents Cartographical Symbol Construction with MapServer Abstract Introduction * Multiple Rendering and Overlay * Symbol Scaling * Mapserver and symbol specication 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 denitions for the gure 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 ll * Polygon lls with symbols of TYPE pixmap * Polygon lls with symbols of TYPE vector * Polygon outlines Examples (Mapserver 4) * Basic Symbols * Complex Symbols Tricks * Changing the center of a point symbol Maple changes related to symbols Current Problems / Open Issues * GAP - PATTERN incompatibility The End
5.1.1 Abstract
This Document refers to the syntax of map and symbol les for MapServer 6. The rst 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.
68
Chapter 5. Maple
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 variables 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 gure shows the theoretical structure of cartographical symbols, which is also used in MapServer:
Multiple Rendering and Overlay 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.
69
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 lling the polygon. When the polygon ll is rendered on top of the lines, the inner part of the underlying outline is covered by the ll 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 ll. 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 of handling the display size of symbols and cartographical elements in a map at different scales. The size of cartographical elements is either set in screen pixels or in real world units. If the size is set in real world units (for example meters), the symbol will shrink and grow according to the scale at which the map is displayed. If the size is set in screen pixels, symbols look the same at all scales. The default behaviour of MapServer is to implement the screen pixels size type for displaying cartographical elements. Real world units, as described above, can be achieved using either the SIZEUNITS or the SYMBOLSCALEDENOM parameter of the LAYER. When SIZEUNITS is set (and is not pixels), symbol sizes are specied in real world units (for instance meters). For available units, see the SIZEUNIT documentation. When SYMBOLSCALEDENOM is set, the given symbols size is used for the map scale 1:SYMBOLSCALEDENOM, for other scales, the symbols are scaled proportionally. STYLE MAXSIZE and MINSIZE limits the scaling of symbols. Mapserver and symbol specication In a MapServer application, SYMBOL parameters are organised in the map le as follows: Each LAYER has a TYPE parameter that denes the type of geometry (point, line or polygon). The symbols are rendered at points, along lines or over areas accordingly. Basic symbols are dened in SYMBOL elements, using the parameters TYPE, POINTS, IMAGE, FILLED, and more (SYMBOL elements can be collected in separate symbol les for reuse). Colour, lightness, size and outline are dened inside the STYLE sections of a CLASS section using the parameters COLOR, SIZE, WIDTH and OUTLINECOLOR. Patterns for styling lines and polygons are dened 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 conguration 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):
70
Chapter 5. Maple
Table 5.1: Commented LAYER and SYMBOL sections. LAYER section of the map le # Start of layer definition LAYER # Name of the layer NAME "mytest" TYPE POINT # Point geometries STATUS DEFAULT # Always draw # Use the dataset test.shp DATA t e s t # Start of a Class definition CLASS # Start of the first Style STYLE # Symbol to be used (reference) SYMBOL "square" # Size of the symbol in pixels SIZE 16 # Colour (RGB) - red COLOR 255 0 0 # Outline colour (RGB) - black OUTLINECOLOR 0 0 0 END # end of STYLE # Start of the second Style STYLE # Symbol to be used (reference) SYMBOL "circle" # Size of the symbol in pixels SIZE 10 # Colour (RGB) - blue COLOR 0 0 255 END # end of STYLE END # end of CLASS END # end of LAYER SYMBOL (from a separate symbol le or in-line in the map le) # Start of symbol definition SYMBOL # Symbol name (referenced in STYLEs) NAME "square" TYPE vector # Type of symbol # Start of the symbol geometry POINTS 0 0 0 1 1 1 1 0 0 0 END # end of POINTS # The symbol should be filled FILLED true END # end of SYMBOL # Start of symbol definition SYMBOL # Symbol name (referenced in STYLEs) NAME "circle" TYPE ellipse # Type of symbol # Start of the symbol geometry POINTS 1 1 END # end of POINTS # The symbol should be filled FILLED true END # end of SYMBOL
71
Output formats MapServer support raster output formats (e.g. PNG, JPEG and GIF) and vector output formats (e.g. PDF, SVG). The raster formats (except for GIF) use anti-aliasing. See OUTPUTFORMAT (and MAP IMAGETYPE) for more. Symbol units The units used for specifying dimensions is dened in the SIZEUNITS parameter of the LAYER. The available units are listed there. The default unit is pixels. The MAP elements RESOLUTION and DEFRESOLUTION parameters will determine the resolution of the resulting map and hence the size in pixels of the symbols on the map. DEFRESOLUTION is by default 72 dpi (dots per inch). If RESOLUTION is set to 144 (and DEFRESOLUTION is 72), all dimensions specied in the map le will be multiplied by 144/72 = 2. This can be used to produce higher resolution images. Dimensions can be specied using decimals. Scaling of Symbols The SYMBOLSCALEDENOM parameter in the LAYER section species the scale at which the symbol or text label is displayed in exactly the dimensions dened 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 SYMBOLSCALEDENOM parameter. The MAXSIZE and MINSIZE parameters inside the STYLE element limit the scaling of symbols to the maximum and minimum size specied here (but does not affect the size calculations). When symbols are scaled as the scale changes, the elements (dened in STYLEs) of a composite cartographical symbol may change their positions relative to each other. This is due to rounding effects when creating the image. The effect is most noticable at small scales (large scale denominators), when the symbols get small. Due to the same effects, symbols can also slightly change their shape when they get small. It is not possibile to dene the display intervals with MINSCALEDENOM and MAXSCALEDENOM in the STYLEsection, 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. All three parameters heavily interact and have to be coordinated to produce a good map.
72
Chapter 5. Maple
Figure 5.3: Basic point symbol TYPEs, showing effects of size, offset, angle and outlinecolor TYPE vector is used to dene advanced vector symbols. The shape of the symbol is dened in the POINTS parameter. A vector symbol can consist of several elements. The coordinates -99 -99 are used to separate the elements. To create a polygon vector symbol, the SYMBOL FILLED parameter must be set to true. If the end point is not equal to the start point of a polygon geometry, it will be closed automatically. The maximum number of points is 100, but this can be increased by changing the parameter MS_MAXVECTORPOINTS in the le mapsymbols.h before compilation. 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. Do not go below a useful minimum size. This 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. Note: The bounding box of a vector symbol has (0,0) as its upper left corner. This can be used to precisely control symbol placement.
Symbols of TYPE truetype You can use symbols from truetype fonts. The symbol settings are dened 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 le - often fonts.list). The FONTSET parameter of the MAP element must be set for fonts to work.
73
For gif output (GD renderer), you can dene that you want to apply antialiasing to the characters by using the parameter ANTIALIAS. It is recommended to do this especially with more complex symbols and whenever they dont t well into the raster matrix or show a visible pixel structure. Colours for truetype symbols can be specied in LAYER CLASS STYLE (as with symbols of the TYPE vector and ellipse). You can specify both ll colour and outline colour. To nd 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 = . (aint that a pain!!) You can also place truetype characters and strings on the map using LABEL. Then you can control the placing of the text by using the POSITION parameter [ul|uc|ur|cl|cc|cr|ll|lc|lr], that species the position relative to the geometric origin of the geometry. Symbols of TYPE pixmap Symbols of the TYPE pixmap are simply small raster images. The le name of the raster image is specied 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 modied in the SYMBOL element subsequently. You can specify a colour with the TRANSPARENT parameter which will not be displayed - i.e. it will be transparent. As a result, underlying objects and colours are visible. The SIZE parameter denes the height of pixmap symbols when rendered. The pixel structure will show when the SIZE grows too large. If you are using symbol scaling (LAYER SYMBOLSCALEDENOM is set or LAYER SIZEUNITS is not pixels) and want to prevent this from happening, you should set the STYLE MAXSIZE parameter. Symbol denitions for the gure that demonstrates point symbols This code was used to produce the symbols in the point symbol gure. First, the symbol denitions:
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
74
Chapter 5. Maple
SYMBOL NAME "P" TYPE truetype FONT "arial" CHARACTER "P" END # SYMBOL SYMBOL NAME "v-line" TYPE vector FILLED false POINTS 0 0 5 10 10 0 END # POINTS END # SYMBOL SYMBOL NAME "v-poly" TYPE vector FILLED true POINTS 0 0 3.5 8 7 0 5.2 0 3.5 4 1.8 0 0 0 END # POINTS END # SYMBOL
Then, the LAYERs and STYLEs used for producing the polygon V symbols in the point symbol gure:
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 LAYER # Vector v - polygon, size STATUS DEFAULT TYPE POINT
75
FEATURE POINTS 20 30 END # Points END # Feature CLASS STYLE SYMBOL "v-poly" COLOR 0 0 0 SIZE 30 END # STYLE STYLE SYMBOL "circlef" COLOR 255 0 0 SIZE 4 END # STYLE END # CLASS END # LAYER LAYER # Vector v - polygon, size, angle STATUS DEFAULT TYPE POINT FEATURE POINTS 30 30 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 LAYER # Vector v - polygon, size, offset STATUS DEFAULT TYPE POINT FEATURE POINTS 40 30 END # Points END # Feature CLASS STYLE SYMBOL "v-poly" COLOR 0 0 0 SIZE 30 OFFSET 0 15 END # STYLE STYLE
76
Chapter 5. Maple
SYMBOL "circlef" COLOR 255 0 0 SIZE 4 END # STYLE END # CLASS END # LAYER LAYER # Vector v - polygon, size, angle, offset STATUS DEFAULT TYPE POINT FEATURE POINTS 50 30 END # Points END # Feature CLASS STYLE SYMBOL "v-poly" COLOR 0 0 0 SIZE 30 ANGLE 60 OFFSET 0 15 END # STYLE STYLE SYMBOL "circlef" COLOR 255 0 0 SIZE 4 END # STYLE END # CLASS END # LAYER LAYER # Vector v - polygon, size outline STATUS DEFAULT TYPE POINT FEATURE POINTS 60 30 END # Points END # Feature CLASS STYLE SYMBOL "v-poly" COLOR 0 0 0 SIZE 30 OUTLINECOLOR 0 255 0 END # STYLE STYLE SYMBOL "circlef" COLOR 255 0 0 SIZE 4 END # STYLE END # CLASS END # LAYER LAYER # Vector v - polygon, size, outline, width STATUS DEFAULT TYPE POINT FEATURE
77
POINTS 70 30 END # Points END # Feature CLASS STYLE SYMBOL "v-poly" COLOR 0 0 0 SIZE 30 OUTLINECOLOR 0 255 0 WIDTH 4 END # STYLE STYLE SYMBOL "circlef" COLOR 255 0 0 SIZE 4 END # STYLE END # CLASS END # LAYER LAYER # Vector v - polygon, size, outline, no color STATUS DEFAULT TYPE POINT FEATURE POINTS 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 gure 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.
78
Chapter 5. Maple
79
80
Chapter 5. Maple
81
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 ######## Left column ############### LAYER # Simple line STATUS DEFAULT TYPE LINE FEATURE POINTS 5 5 25 10 45 10 35 5 END # Points END # Feature CLASS STYLE COLOR 0 0 0 WIDTH 6.5 END # STYLE END # CLASS END # LAYER LAYER # Dashed line STATUS DEFAULT TYPE LINE FEATURE POINTS 5 15 25 20 45 20 35 15 END # Points END # Feature CLASS
82
Chapter 5. Maple
STYLE COLOR 0 0 0 WIDTH 5.0 PATTERN 40 10 END END # STYLE END # CLASS END # LAYER LAYER # Dashed line, varying STATUS DEFAULT TYPE LINE FEATURE POINTS 5 25 25 30 45 30 35 25 END # Points END # Feature CLASS STYLE COLOR 0 0 0 WIDTH 5.0 LINECAP round #[butt|round|square|triangle] LINEJOIN miter #[round|miter|bevel] LINEJOINMAXSIZE 3 PATTERN 40 17 0 17 0 17 0 17 END END # STYLE END # CLASS END # LAYER LAYER # Line dash overlay STATUS DEFAULT TYPE LINE FEATURE POINTS 5 35 25 40 45 40 35 35 END # Points END # Feature CLASS STYLE COLOR 102 102 102 WIDTH 4.0 END # STYLE STYLE COLOR 255 255 255 WIDTH 2.0 LINECAP BUTT PATTERN 8 12 END END # STYLE END # CLASS END # LAYER LAYER # Line overlay - 2 STATUS DEFAULT
83
TYPE LINE FEATURE POINTS 5 45 25 50 45 50 35 45 END # Points END # Feature CLASS STYLE COLOR 0 0 0 WIDTH 16.0 END # STYLE STYLE COLOR 209 66 0 WIDTH 10.0 END # STYLE END # CLASS END # LAYER LAYER # Line overlay - 3 STATUS DEFAULT TYPE LINE FEATURE POINTS 5 55 25 60 45 60 35 55 END # Points END # Feature CLASS STYLE COLOR 0 0 0 WIDTH 17.0 END # STYLE STYLE COLOR 209 66 0 WIDTH 11.0 END # STYLE STYLE COLOR 0 0 0 WIDTH 1.0 END # STYLE END # CLASS END # LAYER ######## right column ############ LAYER # Line - ellipse overlay STATUS DEFAULT TYPE LINE FEATURE POINTS 50 5 70 10 90 10
84
Chapter 5. Maple
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 LAYER # Line - symbol overlay STATUS DEFAULT TYPE LINE FEATURE POINTS 50 15 70 20 90 20 80 15 END # Points END # Feature CLASS STYLE COLOR 0 0 0 WIDTH 2.8 END # STYLE STYLE COLOR 0 0 0 SYMBOL "vertline" SIZE 20.0 ANGLE 30 GAP -50 END # STYLE END # CLASS END # LAYER LAYER # Line - font overlay STATUS DEFAULT TYPE LINE FEATURE POINTS 50 25 70 30 90 30 80 25
85
END # Points END # Feature CLASS STYLE COLOR 0 0 0 WIDTH 6 END # STYLE STYLE COLOR 102 0 0 SYMBOL "P" SIZE 20 GAP -30 END # STYLE END # CLASS END # LAYER LAYER # Line - pixmap overlay STATUS DEFAULT TYPE LINE FEATURE POINTS 50 35 70 40 90 40 80 35 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 END # STYLE END # CLASS END # LAYER LAYER # Line - pixmap overlay STATUS DEFAULT TYPE LINE FEATURE POINTS 50 45 70 50 90 50 80 45 END # Points END # Feature CLASS STYLE COLOR 0 0 0 WIDTH 6 END # STYLE STYLE
86
Chapter 5. Maple
COLOR 102 0 0 SYMBOL "o-flag-trans" SIZE 20 GAP -30 OFFSET -10 -99 END # STYLE END # CLASS END # LAYER
LINECAP
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 the 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 ll the resulting area. none will render each segment using linecap butt. The gure below illustrates the different linejoins.
Specify the maximum length of m (see the gure below). The value is a multiplication factor (default 3). The max length of the miter join is calculated as follows (d is the line width, specied with the WIDTH parameter of the STYLE):
m_max = d * LINEJOINMAXSIZE
If m > m_max, then the connection length will be set to m_max. Use of the OFFSET parameter In STYLE, an OFFSET parameter can be set to shift symbols in the X and Y direction. The displacement is not inuenced 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 dened in style number 2 in the map le example below red line in the map image). A positive X value shifts to the right. A positive Y value shifts downwards.
87
Figure 5.7: Miter linejoin 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 denes 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.
Figure 5.8: Use of the OFFSET parameter with lines - map image
88
Chapter 5. Maple
Use of the OFFSET parameter with lines - Map le excerpt LAYER # STATUS DEFAULT TYPE LINE FEATURE POINTS 20 20 280 160 280 20 160 20 160 60 END # Points END # Feature CLASS STYLE # no offset COLOR 0 0 0 # black WIDTH 1 END # STYLE STYLE # simple offset left and down COLOR 255 0 0 # red WIDTH 2 OFFSET -8 12 END # STYLE STYLE # left offset rel. to line direction COLOR 0 0 255 # blue WIDTH 5 OFFSET -16 -99 END # STYLE STYLE # right offset rel. to line direction COLOR 0 255 0 # green WIDTH 5 OFFSET 16 -99 END # STYLE END # CLASS END # LAYER
Asymmetrical line styling with point symbols Line number 2 and 5 from the bottom in the right column of the Construction of Line Symbols gure are examples 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 the bottom is produced using an asymmetrical point symbol - this is the best method for placing symbols on lines. Line number 5 from the bottom is produced using STYLE OFFSET. As can be seen, the symbols are here rendered on the offset line, meaning that at sharp bends, some symbols will be placed far away from the line.
89
The symbols are by default used as tiles, and rendered (without spacing) one after the other in the x and y direction, lling the whole polygon. If the SIZE parameter is used in the STYLE, the symbols will be scaled to the specied 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 ll Simple line hatches (e.g. horizontal, vertical and diagonal) can be created by lling the polygon with a hatch symbol.
Figure 5.9: Hatch examples The SIZE parameter in the STYLE that uses a SYMBOL of type hatch species the distance from center to center between the lines (the default is 1). The WIDTH parameter species the width of the lines in the hatch pattern (default is 1). The ANGLE parameter species the direction of the lines (default is 0 - horizontal lines). The gure demonstrates the use of SIZE (bottom left), WIDTH (bottom right), ANGLE (top left) and overlay (top right) of hatches. The code below shows excerpts of the map le that was used to produce the gure. First, the SYMBOL denition:
SYMBOL NAME "hatchsymbol" TYPE hatch END
90
Chapter 5. Maple
Table 5.2: Hatches CLASS denitions LAYER # hatch ... CLASS STYLE SYMBOL "hatchsymbol" COLOR 0 0 0 SIZE 10 END # STYLE END # CLASS END # LAYER LAYER # hatch with angle ... CLASS STYLE SYMBOL "hatchsymbol" COLOR 0 0 0 SIZE 10 ANGLE 45 END # STYLE END # CLASS END # LAYER LAYER # hatch with wide lines ... CLASS STYLE SYMBOL "hatchsymbol" COLOR 0 0 0 SIZE 10 WIDTH 5 END # STYLE END # CLASS END # LAYER LAYER # cross hatch ... CLASS STYLE SYMBOL "hatchsymbol" COLOR 255 153 0 SIZE 10 WIDTH 4 END # STYLE STYLE SYMBOL "hatchsymbol" COLOR 0 0 255 SIZE 20 ANGLE 90 END # STYLE END # CLASS END # LAYER 5.1. Cartographical Symbol Construction with MapServer 91
Polygon lls with symbols of TYPE pixmap Polygons can be lled with pixmaps. Note: If the STYLE SIZE parameter is different from the image height of the pixmap, there can be rendering artefacts around the pixmaps (visible as a grid with the background colour). Pixmap symbols can be rotated using the ANGLE parameter, but for polygon lls, this produces strange effects, and is not recommended. To create complex area symbols, e.g. with dened distances between single characters or hatches with broad lines, pixmap ll is probably the best option. Depending on the desired pattern you have to generate the raster image with high precision using a graphical editor. The gure below is an example of how to obtain a regular allocation of symbols with dened spacing.
Figure 5.10: Raster image for a regular symbol ll You can use other shapes than circles. B denes 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 the same x and y distances to the imageborder is enough. The following gure 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, nished with Photoshop and exported to PNG with special attention to the colour palette.
92
Chapter 5. Maple
Table 5.3: Construction of a horizontally arranged area symbol CLASS section CLASS STYLE COLOR 255 255 0 END STYLE SYMBOL "in_the_star" END STYLE OUTLINECOLOR 0 0 0 WIDTH 1 END END SYMBOL denition SYMBOL NAME "in_the_star" TYPE PIXMAP IMAGE "stern.png" TRANSPARENT 8 END
93
Table 5.4: Construction of a diagonally arranged area symbol CLASS section CLASS STYLE SYMBOL "in_point1" END STYLE OUTLINECOLOR 0 0 0 WIDTH 1 END END SYMBOL denition SYMBOL NAME "in_point1" TYPE PIXMAP IMAGE "flaeche1_1.png" TRANSPARENT 13 END
Figure 5.13: Polygon ll - diagonal pattern Table 5.5: Construction of a hatch CLASS section CLASS STYLE COLOR 255 255 0 END STYLE SYMBOL "in_hatch" END STYLE OUTLINECOLOR 0 0 0 WIDTH 1 END END SYMBOL denition SYMBOL NAME "in_hatch" TYPE PIXMAP IMAGE "schraffur.png" TRANSPARENT 2 END
Polygon lls with symbols of TYPE vector Polygons can be lled with symbols of TYPE vector. As for the other symbol lls, the pattern will be generated by using the specied symbol for the tiles. The bounding box of the symbol is used when tiling. 94 Chapter 5. Maple
The upper left corner of the bounding box of a symbols of TYPE vector is always (0, 0). The lower right corner of the bounding box is determined by the maximum x and y values of the symbol denition (POINTS parameter). Creating vector symbols for polygon lls is done in much the same way as for pixmap symbols. Precision is necessary to get nice symmetrical symbols. Both polygon (FILLED true) and line (FILLED false) 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. Note: For vector line symbols (FILL off), if a width greater than 1 is specied, the lines will grow to extend outside the original bounding box of the symbol. The parts that are outside of the bounding box will be cut away. STYLE ANGLE can be used for polygon lls, but will only rotate each individual symbol, not the pattern as a whole. It is therefore quite demanding to generate rotated patterns. Below you will nd some examples of vector symbols used for polygon lls. The polygon ll is accompanied by the vector symbol used for the ll. The centre of the vector symbol is indicated with a red dot.
Excerpts from the map le for the polygon ll vector examples above
95
LAYER # chess board STATUS DEFAULT TYPE POLYGON FEATURE POINTS 5 5 5 25 45 25 45 5 5 5 END # Points END # Feature CLASS STYLE SYMBOL "chess" COLOR 0 0 0 SIZE 35 END # STYLE END # CLASS END # LAYER LAYER # x - line STATUS DEFAULT TYPE POLYGON FEATURE POINTS 5 30 5 50 45 50 45 30 5 30 END # Points END # Feature CLASS STYLE SYMBOL "x-line" COLOR 0 0 0 WIDTH 5 SIZE 35 END # STYLE END # CLASS END # LAYER LAYER # v polygon STATUS DEFAULT TYPE POLYGON FEATURE POINTS 5 55 5 75 45 75 45 55 5 55 END # Points END # Feature CLASS STYLE SYMBOL "v-poly"
96
Chapter 5. Maple
COLOR 0 0 0 SIZE 35 END # STYLE END # CLASS END # LAYER LAYER # Circles STATUS DEFAULT TYPE POLYGON FEATURE POINTS 5 80 5 100 45 100 45 80 5 80 END # Points END # Feature CLASS STYLE SYMBOL "circlef" COLOR 0 0 0 SIZE 20 GAP 18 END # STYLE END # CLASS END # LAYER LAYER # x polygon STATUS DEFAULT TYPE POLYGON FEATURE POINTS 55 5 55 25 95 25 95 5 55 5 END # Points END # Feature CLASS STYLE COLOR 0 0 0 SYMBOL "x-poly-fill" SIZE 35 END # STYLE END # CLASS END # LAYER LAYER # indistinct marsh STATUS DEFAULT TYPE POLYGON FEATURE POINTS 55 30 55 50 95 50 95 30
97
55 30 END # Points END # Feature CLASS STYLE COLOR 0 0 255 SYMBOL "ind_marsh_poly" SIZE 25 END # STYLE END # CLASS END # LAYER LAYER # diagonal circles STATUS DEFAULT TYPE POLYGON FEATURE POINTS 55 55 55 75 95 75 95 55 55 55 END # Points END # Feature CLASS STYLE COLOR 255 230 51 SYMBOL "diag_dots" SIZE 30 END # STYLE END # CLASS END # LAYER
LAYER # diagonal holes in yellow STATUS DEFAULT TYPE POLYGON FEATURE POINTS 55 80 55 100 95 100 95 80 55 80 END # Points END # Feature CLASS STYLE SYMBOL "diag_holes" SIZE 30 COLOR 250 220 102 END # STYLE END # CLASS END # LAYER LAYER # v line + circle STATUS DEFAULT TYPE POLYGON
98
Chapter 5. Maple
FEATURE POINTS 100 5 100 25 140 25 140 5 100 5 END # Points END # Feature CLASS STYLE COLOR 255 0 0 SYMBOL "circlef" SIZE 30 GAP 45 END # STYLE STYLE COLOR 0 0 0 SYMBOL "v-line" LINEJOIN miter LINECAP butt SIZE 35 WIDTH 10 GAP 45 END # STYLE END # CLASS END # LAYER LAYER # indistinct marsh + diagonal holes in yellow STATUS DEFAULT TYPE POLYGON FEATURE POINTS 100 30 100 50 140 50 140 30 100 30 END # Points END # Feature CLASS STYLE COLOR 0 0 255 SYMBOL "ind_marsh_poly" SIZE 25 END # STYLE STYLE SYMBOL "diag_holes" SIZE 30 COLOR 250 220 0 OPACITY 75 END # STYLE END # CLASS END # LAYER LAYER # x line + circle STATUS DEFAULT TYPE POLYGON
99
FEATURE POINTS 100 55 100 75 140 75 140 55 100 55 END # Points END # Feature CLASS STYLE COLOR 0 0 255 SYMBOL "circle" WIDTH 5 SIZE 20 GAP 30 END # STYLE STYLE COLOR 0 204 0 SYMBOL "x-line" SIZE 10 WIDTH 3 GAP 30 END # STYLE END # CLASS END # LAYER
100
Chapter 5. Maple
TYPE vector FILLED false FILLED true POINTS 0 0 3.5 8 7 0 5.2 0 3.5 4 1.8 0 0 0 END END SYMBOL NAME "x-line" TYPE vector POINTS 0 0 1 1 -99 -99 0 1 1 0 END END SYMBOL NAME "chess" TYPE vector FILLED true POINTS 0 0 10 0 10 10 0 10 0 0 -99 -99 10 10 20 10 20 20 10 20 10 10 END END SYMBOL NAME "x-poly-fill" TYPE vector FILLED true POINTS 0 1.131 0 0 1.131 0 4.566 3.434 8 0 9.131 0 9.131 1.131 5.697 4.566
101
9.131 8 9.131 9.131 8 9.131 4.566 5.697 1.131 9.131 0 9.131 0 8 3.434 4.566 0 1.131 END # POINTS END # SYMBOL SYMBOL NAME "ind_marsh_poly" TYPE vector FILLED true POINTS # Half line 0 2 4.5 2 4.5 3 0 3 0 2 -99 -99 # Half line 7 2 11.5 2 11.5 3 7 3 7 2 -99 -99 # Hole line 1.25 5 10.25 5 10.25 6 1.25 6 1.25 5 END END SYMBOL NAME "diag_dots" TYPE vector FILLED true POINTS # Central circle: 0.7450 0.4500 0.7365 0.5147 0.7115 0.5750 0.6718 0.6268 0.6200 0.6665 0.5597 0.6915 0.4950 0.7000 0.4303 0.6915 0.3700 0.6665 0.3182 0.6268 0.2785 0.5750 0.2535 0.5147
102
Chapter 5. Maple
0.2450 0.2535 0.2785 0.3182 0.3700 0.4303 0.4950 0.5597 0.6200 0.6718 0.7115 0.7365 0.7450 -99 -99 0.25 0.2415 0.2165 0.1768 0.1250 0.0647 0.0 0.0 0.25 -99 -99 1 0.25 0.9252 0.8649 0.8132 0.7734 0.7485 0.74 1 0.0 1 0.25 -99 -99 0.74 0.7485 0.7734 0.8132 0.8649 0.9252 1 0.74 1 1 0.74 -99 -99 0.0 0.0647 0.1250 0.1768 0.2165 0.2415 0.25 0.0 0.0 END END
0.4500 0.3853 0.3250 0.2732 0.2335 0.2085 0.2000 0.2085 0.2335 0.2732 0.3250 0.3853 0.4500 0.0 0.0647 0.1250 0.1768 0.2165 0.2415 0.25 0.0 0.0
103
TYPE vector FILLED true POINTS 0.0 0.0 # Left half circle 0.0 0.24 0.0647 0.2485 0.1250 0.2734 0.1768 0.3132 0.2165 0.3649 0.2415 0.4252 0.25 0.5 0.2415 0.5647 0.2165 0.6250 0.1768 0.6768 0.1250 0.7165 0.0647 0.7415 0.0 0.75 0.0 1.0 # Bottom half circle 0.24 1 0.2485 0.9252 0.2734 0.8649 0.3132 0.8132 0.3649 0.7734 0.4252 0.7485 0.5 0.74 0.5647 0.7485 0.6250 0.7734 0.6768 0.8132 0.7165 0.8649 0.7415 0.9252 0.75 1 1.0 1.0 # Right half circle 1 0.75 0.9252 0.7415 0.8649 0.7165 0.8132 0.6768 0.7734 0.6250 0.7485 0.5647 0.74 0.5 0.7485 0.4252 0.7734 0.3649 0.8132 0.3132 0.8649 0.2734 0.9252 0.2485 1 0.24 1.0 0.0 # Top half circle 0.75 0.0 0.7415 0.0647 0.7165 0.1250 0.6768 0.1768 0.6250 0.2165
104
Chapter 5. Maple
0.5647 0.5 0.4252 0.3649 0.3132 0.2734 0.2485 0.24 0.0 END END
Polygon outlines Polygon outlines can be created by using OUTLINECOLOR in the STYLE. WIDTH species the width of the outline.
STYLE OUTLINECOLOR 0 255 0 WIDTH 3 END # STYLE
Dashed polygon outlines can be achieved by using OUTLINECOLOR, WIDTH and PATTERN (together with LINECAP, LINEJOIN and LINEJOINMAXSIZE). For more information on the use of PATTERN, see Use of the PATTERN and GAP parameters.
STYLE OUTLINECOLOR 0 255 0 WIDTH 3 PATTERN 10 5 END # PATTERN LINECAP BUTT END # STYLE
For some symbol types, it is even possible to style polygon outlines using OUTLINECOLOR, SYMBOL and GAP.
STYLE OUTLINECOLOR 0 255 0 SYMBOL circle SIZE 5 GAP 15 END # STYLE
105
Basic Symbols
106
Chapter 5. Maple
107
Complex Symbols
108
Chapter 5. Maple
109
5.1.8 Tricks
Changing the center of a point symbol Mapserver does all transformations (offset, rotation) with respect to the symbol center point. The center point is calculated from the symbols 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 species 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 nd three tables that contain the SYMBOLs and the STYLE mechanisms that were used to generate the shifted symbols in the illustration.
110
Chapter 5. Maple
111
Table 5.6: Symbol tricks - shift - arrows SYMBOLs SYMBOL NAME "arrow-offset-end" TYPE vector FILLED true POINTS -5 0.4 -2 0.4 -2 0 0 0.8 -2 1.6 -2 1.2 -5 1.2 -5 0.4 END # POINTS END # SYMBOL SYMBOL NAME "arrow-offset-start" TYPE vector FILLED true POINTS 5 0.4 8 0.4 8 0 10 0.8 8 1.6 8 1.2 5 1.2 5 0.4 END # POINTS END # SYMBOL LAYER STYLEs LAYER # Line STATUS DEFAULT TYPE LINE FEATURE POINTS 20 65 40 70 60 70 70 65 END # Points END # Feature CLASS STYLE COLOR 0 0 0 WIDTH 15 LINECAP butt END # STYLE STYLE GEOMTRANSFORM "start" COLOR 0 255 0 SYMBOL "arrow-offset-start" SIZE 15.0 ANGLE AUTO END # STYLE STYLE GEOMTRANSFORM "start" COLOR 255 0 0 SYMBOL "circlef" SIZE 3 END # STYLE STYLE GEOMTRANSFORM "end" COLOR 0 255 0 SYMBOL "arrow-offset-end" SIZE 15.0 ANGLE AUTO END # STYLE STYLE GEOMTRANSFORM "end" COLOR 255 0 0 SYMBOL "circlef" SIZE 3 END # STYLE END # CLASS END # LAYER
112
Chapter 5. Maple
Table 5.7: Symbol tricks - shift - asymmetrical tags SYMBOLs SYMBOL NAME "fence-tag" TYPE vector POINTS 0 5 0 10 END # POINTS END # SYMBOL SYMBOL NAME "vert-line" TYPE vector POINTS 0 0 0 10 END # POINTS END # SYMBOL LAYER STYLEs LAYER # Line - symbol overlay STATUS DEFAULT TYPE LINE FEATURE POINTS 20 50 40 55 60 55 70 50 END # Points END # Feature CLASS STYLE COLOR 0 0 0 WIDTH 4 END # STYLE STYLE COLOR 0 0 0 SYMBOL "fence-tag" SIZE 40.0 WIDTH 3 ANGLE 30 GAP -50 END # STYLE STYLE COLOR 255 0 0 SYMBOL "circlef" SIZE 1 GAP -50 END # STYLE END # CLASS END # LAYER
113
Table 5.8: Symbol tricks. 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
114
Chapter 5. Maple
put together a cartographical symbols library for the prot 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
BACKGROUNDCOLOR [r] [g] [b] Color to use for non-transparent symbols. COLOR [r] [g] [b] Color to use for drawing features. DEBUG [on|off] Enables debugging of the class object. Verbose output is generated and sent to the standard error output (STDERR) or the MapServer logle 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 dene which class a feature belongs to: String comparisons, regular expressions, logical expressions, and string functions (see Expressions). 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 necessary although strings must be quoted if they contain special characters. (As a matter of good habit, it is recommended that you quote all strings). The attribute to use for comparison is dened in the LAYER CLASSITEM parameter. Regular expression are limited using slashes (/regex/). The attribute to use for comparison is dened in the LAYER CLASSITEM parameter. Logical expressions allow the building of fairly complex tests based on one or more attributes and therefore are only available with shapeles. Logical expressions are delimited by parentheses (expression). Attribute names are delimited by square brackets [ATTRIBUTE]. Attribute names are case sensitive and must match the items in the shapele. For example:
EXPRESSION ([POPULATION] > 50000 AND [LANGUAGE] eq FRENCH)
The following logical operators are supported: =, >, <, <=, >=, =, or, and, lt, gt, ge, le, eq, ne, in, ~, ~*. As one might expect, this level of complexity is slower to process. One string function exists: length(). It computes the length of a string:
EXPRESSION (length([NAME_E]) < 8)
String comparisons and regular expressions work from the classitem dened 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"
5.2. CLASS
115
... END CLASS NAME "name2" GROUP "group2" ... END CLASS NAME "name3" GROUP "group1" ... END ... END # layer
KEYIMAGE [lename] Full lename 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). LABEL Signals the start of a LABEL object. MAXSCALEDENOM [double] Minimum scale at which this CLASS 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 instead. The deprecated MAXSCALE is the minimum scale at which this class 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. MAXSIZE [integer] Maximum size in pixels to draw a symbol. Default is 50. See LAYER SYMBOLSCALEDENOM. MINSCALEDENOM [double] Maximum scale at which this CLASS 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 instead. The deprecated MINSCALE is the maximum scale at which this CLASS 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. MINSIZE [integer] Minimum size in pixels to draw a symbol. Default is 0. See LAYER SYMBOLSCALEDENOM. NAME [string] Name to use in legends for this class. If not set class wont show up in legend. OUTLINECOLOR [r] [g] [b] Color to use for outlining polygons and certain marker symbols. Line symbols do not support outline colors. SIZE [integer] Height, in pixels, of the symbol/pattern to be used. Only useful with scalable symbols. For vector (and ellipse) SYMBOL TYPEs the default size is based on the range of Y values in the POINTS dening the symbol. For symbols of type pixmap, the default is the vertical size of the image. Default size is 1 for TTF symbols. STATUS [on|off] Sets the current display status of the class. Default turns the class on.
116
Chapter 5. Maple
STYLE Signals the start of a STYLE object. A class can contain multiple styles. Multiple styles can be used create complex symbols (by overlay/stacking). See Cartographical Symbol Construction with MapServer for more information on advanced symbol construction. SYMBOL [integer|string|lename] 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 le, starting at 1, the 5th symbol in the le is therefore symbol number 5. You can also give your symbols names using the NAME parameter in the symbol denition le, and use those to refer to them. Default is 0, which results in a single pixel, single width line, or solid polygon ll, depending on layer type. You can also specify a gif or png lename. The path is relative to the location of the maple. See Cartographical Symbol Construction with MapServer for more information on advanced symbol construction. TEMPLATE [lename] Template le or URL to use in presenting query results to the user. See Templating for more info. TEXT [string|expression] Text to label features in this class with. This overrides values obtained from the LAYER LABELITEM. The string can contain references to feature attributes. This allows you to concatenate multiple attributes into a single label. You can for example concatenate the attributes FIRSTNAME and LASTNAME like this:
TEXT [FIRSTNAME] [LASTNAME]
More advanced Expressions can be used to specify the labels. Since version 6.0, there are functions available for formatting numbers:
TEXT ("Area is: " + tostring([area],"%.2f"))
VALIDATION Signals the start of a VALIDATION block. As of MapServer 5.4.0, VALIDATION blocks are the preferred mechanism for specifying validation patterns for CGI param runtime substitutions. See Run-time Substitution. Although the recommended way of making stacked symbols to achieve interesting effects is to use STYLEs, you can also stack 2 symbols without using STYLEs. You dene the second symbol, which effectively sits on top of the rst symbol (as dened above). The following parameters allow you to dene the second symbol, and they are equivalent to their non-overlay counterparts: OVERLAYBACKGROUNDCOLOR OVERLAYCOLOR OVERLAYOUTLINECOLOR OVERLAYSIZE OVERLAYMINSIZE OVERLAYMAXSIZE OVERLAYSYMBOL
5.3 CLUSTER
5.3. CLUSTER
117
Table of Contents CLUSTER Description Supported Layer Types Maple Parameters Maple Snippet Feature attributes PHP MapScript Usage Example: Clustering Railway Stations
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.
118
Chapter 5. Maple
FILTER (expression) # a logical expression to specify the grouping condition END LABELITEM "Cluster:FeatureCount" CLASS ... LABEL ... END END ... END
Maple Layer
#################### # Lightrail Stations #################### SYMBOL NAME "lightrail"
5.3. CLUSTER
119
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 ########################### CLUSTER MAXDISTANCE 50 REGION "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
120
Chapter 5. Maple
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
121
Table of Contents Display of International Characters in MapServer Credit Related Links Requirements How to Enable in Your Maple * 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 Informationtechnology 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).
5.4.3 Requirements
MapServer >= 4.4.0 MapServer compiled with the libiconv library
122
Chapter 5. Maple
> mapserv -v MapServer version 5.6.5 OUTPUT=GIF OUTPUT=PNG OUTPUT=JPEG OUTPUT=WBMP OUTPUT=PDF OUTPUT=SWF OUTPUT=SVG 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 SUPPORTS=FASTCGI SUPPORTS=THREADS SUPPORTS=GEOS SUPPORTS=RGBA_PNG SUPPORTS=TILECACHE INPUT=JPEG INPUT=POSTGIS INPUT=OGR INPUT=GDAL INPUT=SHAPEFILE
Step 2: Verify That Your Files Encoding is Supported by ICONV 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 specic system. Step 3: Add ENCODING Parameter to your LABEL Object Now you can simply add the ENCODING parameter to your maple LAYER object, such as:
MAP ... LAYER ... CLASS ... LABEL ... ENCODING "SHIFT_JIS" END END END END
One of the benets 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 Shapele 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 Maple 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
123
SIZE 10 POSITION CL PARTIALS FALSE BUFFER 0 ENCODING S H I F T _ 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
Step 4: Test with the shp2img utility see shp2img commandline utility
124
Chapter 5. Maple
// get the class objects label object $clabel= $class->label; // get encoding parameter $encode_str = $clabel->encoding; print "Encoding = ".$encode_str."\n"; // set encoding parameter $clabel->set("encoding","UTF-8");
5.4.6 Notes
Note: During initial implementation, this functionality was tested using the different Japanese encoding systems: Shift-JIS, EUC-JP, UTF-8, as well as Thais TIS-620 encoding system. Examples of encodings for the Latin alphabet supported by libiconv are: ISO-8859-1 (Latin alphabet No. 1 - also known as LATIN-1 - western European languages), ISO-8859-2 (Latin alphabet No. 2 - also known as LATIN-2 eastern European languages), CP1252 (Microsoft Windows Latin alphabet encoding - English and some other Western languages).
5.5 Expressions
Author Dirk Tilger Contact dirk at MIRIUP.DE Author Umberto Nicoletti Contact umberto.nicoletti at gmail.com Revision $Revision$ Date $Date$ Last Updated 2011/06/30
5.5. Expressions
125
Contents Expressions Introduction * String quotation * Quotes escaping in strings * Using attributes * Character encoding Expression Types * String comparison (equality) * Regular expression comparison MapServer expressions * Logical expressions * String expressions that return a logical value * Arithmetic expressions that return a logical value * Spatial expressions that return a logical value (GEOS) * String operations that return a string * Functions that return a string * String functions that return a number * Arithmetic operations and functions that return a number * Spatial functions that return a number (GEOS) * Spatial functions that return a shape (GEOS) * Temporal expressions
5.5.1 Introduction
As of version 6.0, expressions are used in four places: In LAYER FILTER to specify the features of the dataset that are to be included in the layer. In CLASS EXPRESSION to specify to which features of the dataset the CLASS applies to. In CLASS TEXT to specify text for labeling features. In STYLE GEOMTRANSFORM. String quotation Stings can be quoted using single or double quotes:
This is a string "And this is also a string"
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:
"National \"hero\" statue"
126
Chapter 5. Maple
Starting with Mapserver 6.0 you dont need to escape single quotes within double qouted strings and you dont need to escape double quotes within single quoted strings. In 6.0 you can also write the string as follows:
National "hero" statue ...
Using attributes Attribute values can be referenced in the Map le and used in expressions. Attribute references are case sensitive and can be used in the following types of expressions: In LAYER FILTER In CLASS EXPRESSION In CLASS TEXT Referencing an attribute is done by enclosing the attribute name in square brackets, like this: [ATTRIBUTENAME]. Then, every occurrence of [ATTRIBUTENAME] will be replaced by the actual value of the attribute ATTRIBUTENAME. Example: The data set of our layer has the attribute BUILDING_NAME. We want the value of this attribute to appear inside a string. This can be accomplished as follows (single or double qoutes):
The [BUILDING_NAME] building
For the building which has its BUILDING_NAME attribute set to Historical Museum, the resulting string is:
The Historical Museum building
For Raster Data layers special attributes have been dened that can be used for classication, for example: [PIXEL] ... will become the pixel value as number [RED], [GREEN], [BLUE] ... will become the color value for the red, green and blue component in the pixel value, respectively. Character encoding With Mapserver there is no way to specify the character encoding of the maple or the layer data sources, so Mapserver cant do the character encoding translation. If the character encoding of the data source is not the same as the character encoding of the map le, they could be converted to a common encoding.
String comparison (equality) String comparison means, as the name suggests, that attribute values are checked if they are equal to some value. String comparisons are the simplest form of MapServer expressions and the fastest option. To use a string comparison for ltering 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 in the LAYER object and EXPRESSION in the CLASS object. Example for a simple string comparison lter
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 classication 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 reasons explained later, the values for both CLASSITEM and FILTERITEM should start with neither a / nor a ( character. Regular expression comparison Regular expressions are a standard text pattern matching mechanism from the Unix world. The functionality of regular 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 dened by the POSIX standard. The documentation of the particular regular expression library is usually in the regex manual page (man regex) on Unix systems. 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 for string comparison, when using a regular expressions, FILTERITEM (LAYER FILTER) or CLASSITEM (CLASS EXPRESSION) has to be dened if the items are not included in the LAYER FILTER or CLASS EXPRESSION. 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 meanings 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. Mapserver supports two regex operators:
128
Chapter 5. Maple
~ case insensitive regular expression ~* case sensitive regular expression The following LAYER conguration 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: For FILTER, the regular expression is case-sensitive, thus records having Hotel in them would not have matched. Example: Match records that have a value from 2000 to 2010 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]*$/
Example: Match all the features where the name attribute ends with by, BY, By or bY (case insensitive matching):
EXPRESSION ([name] ~* by$)
Example: Match all the features where the rdname attribute starts with Main.
LAYER ... CLASSITEM rdname CLASS EXPRESSION /^Main.*$/
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 les of some of the components, however.
5.5. Expressions
129
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. ( ( Expression1 ) AND ( Expression2 ) ) ( ( Expression1 ) && ( Expression2 ) ) returns true when both of the logical expressions (Expression1 and Expression2) are true. ( ( Expression1 ) OR ( Expression2 ) ) ( ( Expression1 ) || ( Expression2 ) ) returns true when at least one of the logical expressions (Expression1 or Expression2) is true. NOT ( Expression1 ) ! ( Expression1 ) returns true when Expression1 is false. String expressions that return a logical value Syntactically, a sting is something encapsulated in single or double quotes. ( String1 eq String2 ) ( String1 == String2 ) - deprecated since 6.0 ( String1 = String2 ) returns true when the strings are equal. Case sensitive. ( String1 =* String2 ) returns true when the strings are equal. Case insensitive. ( String1 != String2 ) ( String1 ne String2 ) returns true when the strings are not equal. ( String1 < String2 ) ( String1 lt String2 ) returns true when String1 is lexicographically smaller than String2 ( String1 > String2 ) ( String1 gt String2 ) returns true when String1 is lexicographically larger than String2. ( String1 <= String2 ) ( String1 le String2 ) returns true when String1 is lexicographically smaller than or equal to String2 ( String1 >= String2 ) ( String1 ge String2 ) returns true when String1 is lexicographically larger than or equal to String2.
130
Chapter 5. Maple
( String1 IN token1,token2,...,tokenN ) returns true when String1 is equal to one of the given tokens. Note: The separator for the tokens is the comma. That means that there can not be unnecessary white space in the list and that tokens that have commas in them cannot be compared. ( String1 ~ regexp ) returns true when String1 matches the regular expression regexp. This operation is identical to the regular expression matching described earlier. ( String1 ~* regexp ) returns true when String1 matches the regular expression regexp (case insensitive). This operation is identical to the regular expression matching described earlier. Arithmetic expressions that return a logical value The basic element for arithmetic operations is the number. Arithmetic operations that return numbers will be covered in the next section. ( n1 eq n2 ) ( n1 == n2 ) - deprecated since 6.0 ( n1 = n2 ) returns true when the numbers are equal. ( n1 != n2 ) ( n1 ne n2 ) returns true when the numbers are not equal. ( n1 < n2 ) ( n1 lt n2 ) returns true when n1 is smaller than n2. ( n1 > n2 ) ( n1 gt n2 ) returns true when n1 is larger than n2. ( n1 <= n2 ) ( n1 le n2 ) returns true when n1 is smaller than or equal to n2. ( n1 >= n2 ) ( n1 ge n2 ) returns true when n1 is larger than or equal to n2. ( n1 IN number1,number2,...,numberN ) returns true when n1 is equal to one of the given numbers.
5.5. Expressions
131
Spatial expressions that return a logical value (GEOS) ( shape1 eq shape2 ) returns true if shape1 and shape2 are equal ( shape1 intersects shape2 ) returns true if shape1 and shape2 intersect New in version 6.0. ( shape1 disjoint shape2 ) returns true if shape1 and shape2 are disjoint New in version 6.0. ( shape1 touches shape2 ) returns true if shape1 and shape2 touch New in version 6.0. ( shape1 overlaps shape2 ) returns true if shape1 and shape2 overlap New in version 6.0. ( shape1 crosses shape2 ) returns true if shape1 and shape2 cross New in version 6.0. ( shape1 within shape2 ) returns true if shape1 is within shape2 New in version 6.0. ( shape1 contains shape2 ) returns true if shape1 contains shape2 New in version 6.0. ( shape1 dwithin shape2 ) returns true if the distance between shape1 and shape2 is equal to 0 New in version 6.0. ( shape1 beyond shape2 ) returns true if the distance between shape1 and shape2 is greater than 0 New in version 6.0. String operations that return a string String1 + String2 returns String1String2, that is, the two strings concatenated to each other. Functions that return a string tostring ( n1, Format1 ) uses Format1 to format the number n1 (C style formatting - sprintf). New in version 6.0. commify ( String1 ) adds thousands separators (commas) to a long number to make it more readable New in version 6.0. String functions that return a number length ( String1 ) returns the number of characters of String1
132
Chapter 5. Maple
Arithmetic operations and functions that return a number round ( n1 , n2 ) returns n1 rounded to a multiple of n2: n2 * round(n1/n2) New in version 6.0. n1 + n2 returns the sum of n1 and n2 n1 - n2 returns n2 subtracted from n1 n1 * n2 returns n1 multiplicated with n2 n1 / n2> returns n1 divided by n2 -n1 returns n1 negated n1 ^ n2 returns n1 to the power of n2 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 )
Spatial functions that return a number (GEOS) area ( shape1 ) returns the area of shape1 New in version 6.0. Spatial functions that return a shape (GEOS) fromtext ( String1 ) returns the shape corresponding to String1 (WKT - well known text)
fromText(POINT(500000 5000000))
New in version 6.0. buffer (shape1 , n1 ) returns the shape that results when shape1 is buffered with bufferdistance n1 New in version 6.0.
5.5. Expressions
133
difference ( shape1 , shape2 ) returns the shape that results when the common area of shape1 and shape2 is subtracted from shape1 New in version 6.0. Temporal expressions MapServer uses an internal time type to do comparison. To convert a string into this time type it will check the list below from the top and down to check if the specied time matches, and if so, it will do the conversion. The following are integer values: YYYY - year, MM - month, DD - date, hh - hours, mm - minutes, ss - seconds. The following are character elements of the format: - (dash) - date separator, : (colon) - time separator, T - marks the start of the time component (ISO 8601), space - marks the end of the date and start of the time component, Z - zulu time (0 UTC offset). YYYY-MM-DDThh:mm:ssZ YYYY-MM-DDThh:mm:ss YYYY-MM-DD hh:mm:ss YYYY-MM-DDThh:mm YYYY-MM-DD hh:mm YYYY-MM-DDThh YYYY-MM-DD hh YYYY-MM-DD YYYY-MM YYYY Thh:mm:ssZ Thh:mm:ss For temporal values obtained this way, the following operations are supported: ( t1 eq t2 ) ( t1 == t2 ) - deprecated since 6.0 ( t1 = t2 ) returns true when the times are equal. ( t1 != t2 ) ( t1 ne t2 ) returns true when the times are not equal. ( t1 < t2 ) ( t1 lt t2 ) returns true when t1 is earlier than t2 ( t1 > t2 ) ( t1 gt t2 ) returns true when t1 is later than t2.
134
Chapter 5. Maple
( t1 <= t2 ) ( t1 le t2 ) returns true when t1 is earlier than or equal to t2 ( t1 >= t2 ) ( t1 ge t2 ) returns true when t1 is later than or equal to t2.
5.6 FEATURE
POINTS A set of xy pairs terminated with an END, for example:
POINTS 1 1 50 50 1 50 1 1 END
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 specied 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 dened as their own layers in the maple. If another CONNECTIONTYPE is specied in the same layer, MapServer will always use the inline features to draw the layer and ignore the other CONNECTIONTYPEs.
5.7 FONTSET
Author Kari Guerts Author Jeff McKenna Contact jmckenna at gatewaygeomatics.com Revision $Revision$ Date $Date$ Last Updated 2008/10/08
5.6. FEATURE
135
Contents FONTSET Format of the fontset le FONTSET is a MAP parameter. The syntax is:
FONTSET [filename]
Where lename gives the location of the fontset le of the system. The location of the system fontset le could for instance be /usr/share/fonts/truetype/font.list (Debian). The location can be specied using a relative or absolute path.
136
Chapter 5. Maple
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 youre 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 grids 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 grids 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 # LABELFORMAT %7.0f m # nice if a projected SRS used # MININTERVAL 20000 # MAXSUBDIVIDE 2 END END # Layer
5.8. GRID
137
5.9 INCLUDE
When this directive is encountered parsing switches to the included le immediately. As a result the included le can be comprised of any valid maple 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 maple. The C pre-processor can also be used (albeit with a different syntax) and is far more powerful.
5.9.1 Notes
Supported in versions 4.10 and higher. The name of the le to be included MUST be quoted (single or double quotes). Includes may be nested, up to 5 deep. File location can be given as a full path to the le, or (in MapServer >= 4.10.1) as a path relative to the maple. Debugging can be problematic because: 1. the le an error occurs in does not get output to the user 2. the line number counter is not reset for each le. Here is one possible error that is thrown when the include le cannot be found:
msyylex(): Unable to access file. Error opening included file "parks_include.map"
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
138
Chapter 5. Maple
CLASS NAME Church COLOR 0 0 0 SYMBOL square SIZE 7 STYLE SYMBOL "square" SIZE 5 COLOR 255 255 255 END STYLE SYMBOL "square" SIZE 3 COLOR 0 0 255 END END END
5.10 JOIN
5.10.1 Description
Joins are dened 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.
CONNECTIONTYPE [csv|mysql|postgresql] Type of connection (not required for DBF joins). For PostgreSQL use postgresql, for CSV use csv, for MySQL use mysql. FOOTER [lename] Template to use after a layers 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 [lename] Template to use before a layers set of results have been sent. In other words, this header HTML will be displayed before the contents of the TEMPLATE HTML.
5.10. JOIN
139
NAME [string] Unique name for this join. Required. TABLE [lename|tablename] For le-based joins this is the name of XBase or comma delimited le (relative to the location of the maple) to join TO. For PostgreSQL support this is the name of the PostgreSQL table to join TO. TEMPLATE [lename] 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 specied 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.
Ogrinfo
>ogrinfo lookup.dbf lookup -summary INFO: Open of lookup.dbf using driver ESRI Shapefile successful. Layer name: lookup Geometry: None Feature Count: 12 Layer SRS WKT: (unknown) IDENT: Integer (2.0) VAL: Integer (2.0)
140
Chapter 5. Maple
>ogrinfo prov.shp prov -summary INFO: Open of prov.shp using driver ESRI Shapefile successful. Layer name: prov Geometry: Polygon Feature Count: 12 Extent: (-2340603.750000, -719746.062500) - (3009430.500000, 3836605.250000) Layer SRS WKT: (unknown) NAME: String (30.0) ID: Integer (2.0)
Template
<tr bgcolor="#EFEFEF"> <td align="left">[NAME]</td> <td align="left">[test_VAL]</td> </tr>
5.10. JOIN
141
Ogrinfo
>ogrinfo -ro PG:"host=127.0.0.1 port=5432 user=postgres password=postgre dbname=join" lookup -summary INFO: Open of PG:host=127.0.0.1 port=5432 user=postgres password=postgres dbname=join using driver PostgreSQL successful. Layer name: lookup Geometry: Unknown (any) Feature Count: 12 Layer SRS WKT: (unknown) ident: Integer (0.0) val: Integer (0.0)
Template
<tr bgcolor="#EFEFEF"> <td align="left">[NAME]</td> <td align="left">[test_val]</td> </tr>
142
Chapter 5. Maple
Note: The CSV driver currently doesnt read column names from the rst row. It just uses indexes (1, 2, ... n) to reference the columns. Its ok to leave column names as the rst row since they likely wont match anything but they arent used. Typically youd see something like TO 1 in the JOIN block. Then in the template youd use [name_1], [name_2], etc...
Ogrinfo
>ogrinfo lookup.csv lookup -summary INFO: Open of lookup.csv using driver CSV successful. Layer name: lookup Geometry: None Feature Count: 12 Layer SRS WKT: (unknown) IDENT: String (0.0) VAL: String (0.0)
Template (prov.html) Ideally this the template should look like this:
<!-- MapServer Template --> <tr bgcolor="#EFEFEF"> <td align="left">[NAME]</td> <td align="left">[test_VAL]</td> </tr>
But since attribute names are not supported for CSV les (see note above), the following will have to be used:
<!-- MapServer Template --> <tr bgcolor="#EFEFEF"> <td align="left">[NAME]</td> <td align="left">[test_2]</td> </tr>
5.10. JOIN
143
5.11 LABEL
ALIGN [left|center|right] Species text alignment for multiline labels (see WRAP) Note that the alignment algorithm is far from precise, so dont expect fabulous results (especially for right alignment) if youre not using a xed width font. New in version 5.4. 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 specics). [Attribute] was introduced in version 5.0, to specify the item name in the attribute table to use for angle values. The hard brackets [] are required. For example, if your shapeles DBF has a eld 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]
144
Chapter 5. Maple
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. Note: Removed in 6.0. Use a LABEL STYLE object with GEOMTRANSFORM labelpoly and COLOR. BACKGROUNDSHADOWCOLOR [r] [g] [b] Color to draw a background rectangle (i.e. billboard) shadow. Off by default. Note: Removed in 6.0. Use a LABEL STYLE object with GEOMTRANSFORM labelpoly, COLOR and OFFSET. BACKGROUNDSHADOWSIZE [x][y] How far should the background rectangle be offset? Default is 1. Note: Removed in 6.0. Use a LABEL STYLE object with GEOMTRANSFORM labelpoly, COLOR and OFFSET. BUFFER [integer] Padding, in pixels, around labels. Useful for maintaining spacing around text to enhance readability. 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 shapeles DBF has a eld named MYCOLOR 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 dened in the FONTSET) to use for labeling.
5.11. LABEL
145
[Attribute] was introduced in version 5.6 to specfy the font alias. FORCE [true|false] Forces labels for a particular class on, regardless of collisions. Available only for cached labels. Default is false. If FORCE is true and PARTIALS is false, FORCE takes precedence, and partial labels are drawn. MAXLENGTH [integer] This keyword interacts with the WRAP keyword so that line breaks only occur after the dened number of characters. Table 5.9: Interaction with WRAP keyword wrap = char no wrap maxlength = 0 always wrap at the WRAP character no processing maxlength > 0 newline at the rst WRAP character after MAXLENGTH characters skip label if it contains more than MAXLENGTH characters maxlength < 0 hard wrap (always break at exactly MAXLENGTH characters) hard wrap (always break at exactly MAXLENGTH characters)
The associated RFC document for this feature is MS RFC 40: Support Label Text Transformations. New in version 5.4. MAXOVERLAPANGLE [double] Angle threshold to use in ltering out ANGLE FOLLOW labels in which characters overlap (oating point value in degrees). This ltering will be enabled by default starting with MapServer 6.0. The default MAXOVERLAPANGLE value will be 22.5 degrees, which also matches the default in GeoServer. Users will be free to tune the value up or down depending on the type of data they are dealing with and their tolerance to bad overlap in labels. As per RFC 60, if MAXOVERLAPANGLE is set to 0, then we fall back on pre-6.0 behavior which was to use maxoverlapangle = 0.4*MS_PI (40% of 180 degrees = 72degree). The associated RFC document for this feature is MS RFC 60: Labeling enhancement: ability to skip ANGLE FOLLOW labels with too much character overlap. MAXSIZE [double] Maximum font size to use when scaling text (pixels). Default is 256. Starting from version 5.4, the value can also be a fractional value (and not only integer). See LAYER SYMBOLSCALEDENOM. MINDISTANCE [integer] Minimum distance between duplicate labels. Given in pixels. MINFEATURESIZE [integer|auto] Minimum size a feature must be to be labeled. Given in pixels. For line data the overall length of the displayed line is used, for polygons features the smallest dimension of the bounding box is used. Auto keyword tells MapServer to only label features that are larger than their corresponding label. Available for cached labels only. MINSIZE [double] Minimum font size to use when scaling text (pixels). Default is 4. Starting from version 5.4, the value can also be a fractional value (and not only integer). See LAYER SYMBOLSCALEDENOM. OFFSET [x][y] Offset values for labels, relative to the lower left hand corner of the label and the label point. Given in pixels. In the case of rotated text specify the values as if all labels are horizontal and any rotation will be compensated for. See LAYER SYMBOLSCALEDENOM. OUTLINECOLOR [r] [g] [b] | [attribute] Color to draw a one pixel outline around the characters in the text. [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 shapeles DBF has a eld named MYOUTCOLOR that holds color values for each record, your LABEL object might contain:
LABEL COLOR 150 150 150 OUTLINECOLOR [ M Y O U T COLOR] FONT "sans"
146
Chapter 5. Maple
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. If FORCE is true and PARTIALS is false, FORCE takes precedence, and partial labels are drawn. 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 nds a position that doesnt collide with labels that have already been drawn. If all positions cause a conict, then the label is not drawn (Unless the labels FORCE a parameter is set to true). Auto placement is only available with cached labels. PRIORITY [integer]|[item_name]|[attribute] The priority parameter 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 rst. Specifying an out of range PRIORITY value inside a map le 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. New in version 5.0. REPEATDISTANCE [integer] 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. New in version 5.6. SHADOWCOLOR [r] [g] [b] Color of drop shadow. A 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 SHADOWCOLOR. [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 a number to give the size in pixels of your TrueType font based label, or any of the other 5 listed keywords for bitmap fonts. When scaling is in effect (SYMBOLSCALEDENOM is specied for the LAYER), SIZE gives the size of the font to be used at the map scale 1:SYMBOLSCALEDENOM.
5.11. LABEL
147
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 values. The hard brackets [] are required. For example, if your shapeles DBF has a eld 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 specic mechanisms of the STYLE object are the GEOMTRANSFORM options: GEOMTRANSFORM [labelpnt|labelpoly] Creates a geometry that can be used for styling the label. labelpnt draws a marker on the geographic position the label is attached to. This corresponds to the center of the label text only if the label is in position CC. 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. Example - draw a red background rectangle for the labels (i.e. billboard) with a shadow in gray:
STYLE GEOMTRANSFORM labelpoly COLOR 153 153 153 OFFSET 3 2 END # STYLE STYLE GEOMTRANSFORM labelpoly COLOR 255 0 0 END # STYLE
New in version 6.0. TYPE [bitmap|truetype] Type of font to use. Generally bitmap fonts are faster to draw then TrueType fonts. However, TrueType fonts are scalable and available in a variety of faces. Be sure to set the FONT parameter if you select TrueType. Note: 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
CLASS Signals the start of a CLASS object.
148
Chapter 5. Maple
Inside a layer, only a single class will be used for the rendering of a feature. Each feature is tested against each class in the order in which they are dened in the maple. The rst class that matches the its min/max scale constraints and its EXPRESSION check for the current feature will be used for rendering. CLASSGROUP [string] Specify the classs group that would be considered at rendering time. The CLASS objects GROUP parameter must be used in combination with CLASSGROUP. CLASSITEM [attribute] Item name in attribute table to use for class lookups. CLUSTER Signals the start of a CLUSTER object. The CLUSTER conguration option provides to combine multiple features from the layer into single (aggregated) features based on their relative positions. Supported only for POINT layers. See Also: MS RFC 69: Support for clustering of features in point layers CONNECTION [string] Database connection string to retrieve remote data. An SDE connection string consists of a hostname, instance name, database name, username and password separated by commas. 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 specic connection information for various data sources. CONNECTIONTYPE [local|ogr|oraclespatial|plugin|postgis|sde|union|wfs|wms] Type of connection. Default is local. See additional documentation for any other type. See Also: See Vector Data for specic 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 [lename]|[sde parameters][postgis table/column][oracle table/column] Full lename of the spatial data to process. No le extension is necessary for shapeles. Can be specied 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 MapServers FILTER whenever possible instead. You can also see the SQL submitted by forcing an error, for instance by submitting a DATA parameter you know wont work, using for example a bad column name. See Also: See Vector Data for specic connection information for various data sources.
5.12. LAYER
149
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 errorle 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 maple, 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 maple parameter can be used to control the level of debugging 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 shapeles 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 maples 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 debugging maples. 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 specied 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 logle if one is set using the LOG parameter in the WEB object. Apache users will see timing details for drawing in Apaches error_log le. Requires MapServer to be built with the DEBUG=MSDEBUG option (with-debug congure option). DUMP [true|false] Switch to allow MapServer to return data in GML format. Useful when used with WMS GetFeatureInfo operations. false by default. Deprecated since version 6.0: LAYER METADATA is used instead. See Also: WMS Server 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.
150
Chapter 5. Maple
FILTER [string] This parameter allows for data specic attribute ltering that is done at the same time spatial ltering is done, but before any CLASS expressions are evaluated. For OGR and shapeles 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 shapeles only. FOOTER [lename] Template to use after a layers 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 les, allowing to do things like turning on and off a group of layers at once. If a group name is present in the LAYERS parameter of a CGI request, all the layers of the group are returned (the STATUS of the LAYERs have no effect). HEADER [lename] Template to use before a layers 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 objects 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] Species 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 LABELMAXSCALEDENOM 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 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 LABELMINSCALE parameter. See Also: Map Scale LABELMINSCALE [double] - deprecated Since MapServer 5.0 the proper parameter to use is LABELMINSCALEDENOM 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]"
5.12. LAYER
151
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 layers 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 objects 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] Species 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 maps geographic units, at which this LAYER is drawn. If MAXSCALEDENOM is also specied 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 instead. 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 dene things such as layer title. It can also allow more exibility 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 maps geographic units, at which this LAYER is drawn. If MINSCALEDENOM is also specied 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 instead. 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. 152 Chapter 5. Maple
NAME [string] Short name for this layer. This name is the link between the maple 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. It is recommended that the name not contain spaces, special characters, or begin with a number (which could cause problems through interfaces such as OGC services). 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 [lename] Additional library to load by MapServer, for this layer. This is commonly used to load specic 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 connection throughout a single map draw process. Additionally, if you have FastCGI enabled, the connection handle will stay open indenitely, or according to the options specied in the FastCGI conguration. Oracle Spatial, ArcSDE, OGR and PostGIS/PostgreSQL currently support this approach.
PROCESSING "CLOSE_CONNECTION=DEFER"
Label Directive - The LABEL_NO_CLIP processing option can be used to skip clipping of shapes when determining associated label anchor points. This avoids changes in label position as extents change between map draws. It also avoids duplicate labels where features appear in multiple adjacent tiles when creating tiled maps.
PROCESSING "LABEL_NO_CLIP=True"
OGR Styles Directive - This directive can be used for obtaining label styles through MapScript. For more information see the MapServers 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.
5.12. LAYER
153
PROJECTION Signals the start of a PROJECTION object. REQUIRES [expression] Sets context for displaying this layer (see LABELREQUIRES). SIZEUNITS [feet|inches|kilometers|meters|miles|nauticalmiles|pixels] Sets the unit of CLASS object SIZE values (default is pixels). Useful for simulating buffering. Nauticalmiles was added in MapServer 5.6. STATUS [on|off|default] Sets the current status of the layer. Often modied by MapServer itself. Default turns the layer on permanently. Note: In CGI mode, layers with STATUS DEFAULT cannot be turned off using normal mechanisms. It is recommended to set layers to STATUS DEFAULT while debugging a problem, but set them back to ON/OFF in normal use.
Note: For WMS, layers in the server maple with STATUS DEFAULT are always sent to the client.
Note: The STATUS of the individual layers of a GROUP has no effect when the group name is present in the LAYERS parameter of a CGI request - all the layers of the group will be returned. STYLEITEM [<attribute>|auto] Item to use for feature specic styling. The style information may be represented by a separate attribute (style string) attached to the feature. MapServer supports the following style string representations: MapServer STYLE denition - The style string can be represented as a MapServer STYLE block according to the following example:
STYLE BACKGROUNDCOLOR 128 0 0 COLOR 0 0 208 END
MapServer CLASS denition - 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 Specication 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:
ogr2ogr -sql "select *, OGR_STYLE from srclayer" "dstlayer" "srclayer"
The value: AUTO can be used for automatic styling. Automatic styling can be provided by the driver. Currently, only the OGR driver supports automatic styling. When used for a Union Layer, the styles from the source layers will be used. SYMBOLSCALEDENOM [double] 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. Implemented in MapServer 5.0, to replace the deprecated SYMBOLSCALE parameter. See Also:
154
Chapter 5. Maple
Map Scale SYMBOLSCALE [double] - deprecated Since MapServer 5.0 the proper parameter to use is SYMBOLSCALEDENOM 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 [le|url] Used as a global alternative to CLASS TEMPLATE. See Templating for more info. TILEINDEX [lename|layername] Name of the tileindex le 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 le is used as the tileindex for shapele or raster layers, the tileindex should be a shapele. For CONNECTIONTYPE OGR layers, any OGR supported datasource can be a tileindex. Normally the location should contain the path to the tile le 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 le, but any supported feature source can be used (ie. postgres, oracle). Note: All les in the tileindex should have the same coordinate system, and for vector les 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 TOLERANCEUNITS. 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 shapeles 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 dene 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 copyright statement to another portion of the image in a way that is independent of image size.
5.12. LAYER
155
TYPE [annotation|chart|circle|line|point|polygon|raster|query] Species how the data should be drawn. Need not be the same as the shapele type. For example, a polygon shapele may be drawn as a point layer, but a point shapele 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 rst using a centroid, and if that doesnt 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 respectively use or omit the COLOR keyword when classifying. If you use it, its a polygon with a ll color, otherwise its a polyline with only an OUTLINECOLOR. A circle must be dened by a a minimum bounding rectangle. That is, two points that dene 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 [dd|feet|inches|kilometers|meters|miles|nauticalmiles|percentages|pixels] Units of the layer. percentages (in this case a value between 0 and 1) was added in MapServer 4.10 and is mostly geared for inline features. nauticalmiles was added in MapServer 5.6. VALIDATION Signals the start of a VALIDATION block. As of MapServer 5.4.0, VALIDATION blocks are the preferred mechanism for specifying validation patterns for CGI param runtime substitutions. See Run-time Substitution.
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 le. 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. KEYSIZE [x][y] Size of symbol key boxes in pixels. Default is 20 by 10.
156
Chapter 5. Maple
KEYSPACING [x][y] Spacing between symbol key boxes ([y]) and labels ([x]) in pixels. Default is 5 by 5. 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. 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 [lename] HTML legend template le. See Also: HTML Legends with MapServer TRANSPARENT [on|off] Should the background color for the legend be transparent. This ag is now deprecated in favor of declaring transparency within OUTPUTFORMAT declarations. Default is off. Deprecated since version 4.6.
5.14 MAP
Note: The map object is started with the word MAP, and ended with the word END. 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 specied 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 objects ANGLE or the LAYER objects LABELANGLEITEM parameters as well, these parameters are relative to the maps orientation (i.e. they are computed after the MAP objects ANGLE). For example, if you have specied an ANGLE for the map of 45, and then have a layer LABELANGLEITEM 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 CPLSetCongOption(). Details on GDAL/OGR options are found in their associated driver documentation pages (GDAL/OGR). The following options are available specically for MapServer: CGI_CONTEXT_URL [value] This 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 [lename] This CONFIG parameter can be used to specify an encryption key that is used with MapServers msencypt utility. MS_ERRORFILE [lename] This CONFIG parameter can be used to write MapServer errors to a le (as of MapServer 5.0). With MapServer 5.x, a full path (absolute reference) is required, including the lename. Starting with MapServer 6.0, a lename with relative path can be passed via this CONFIG directive, in which case the lename is relative to the maple location. Note that setting MS_ERRORFILE via an environment variable always requires an absolute path since there would be no maple to make the path relative to. For more on this see the DEBUG parameter below. 5.14. MAP 157
MS_NONSQUARE [yes|no] This CONFIG parameter can be used to allow non-square pixels (meaning that the pixels represent non-square regions). For MS_NONSQUARE yes to work, the MAP, and each LAYER will have to have a PROJECTION object. Note: Has no effect for WMS. ON_MISSING_DATA [FAIL|LOG|IGNORE] This 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 le in a tile index. This is the default.
CONFIG "ON_MISSING_DATA" "FAIL"
LOG This will cause MapServer to log the error message for a missing le 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.
CONFIG "ON_MISSING_DATA" "LOG"
IGNORE This will cause MapServer to not report or log any errors for missing les, and map creation will occur normally.
CONFIG "ON_MISSING_DATA" "IGNORE"
PROJ_LIB [path] This CONFIG parameter can be used to dene the location of your EPSG les for the Proj.4 library. Setting the [key] to PROJ_LIB and the [value] to the location of your EPSG les 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
CONFIG "PROJ_LIB" "/usr/local/share/proj/"
2. Windows
CONFIG "PROJ_LIB" "C:/somedir/proj/nad/"
DATAPATTERN [regular expression] This denes a regular expression to be applied to requests to change DATA parameters via URL requests (i.e. map_layername_data=...). If a pattern doesnt exist then web users cant monkey with support les 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 errorle 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 maple, 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:
158
Chapter 5. Maple
Once the environment variable is set, the DEBUG maple parameter can be used to control the level of debugging 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 shapeles 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 maples 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 debugging maples. 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 specied 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 logle if one is set using the LOG parameter in the WEB object. Apache users will see timing details for drawing in Apaches error_log le. Requires MapServer to be built with the DEBUG=MSDEBUG option (with-debug congure option). DEFRESOLUTION [int] Sets the reference resolution (pixels per inch) used for symbology. Default is 72. Used to automatically scale the symbology when RESOLUTION is changed, so the map maintains the same look at each resolution. The scale factor is RESOLUTION / DEFRESOLUTION. New in version 5.6. 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 specied. FONTSET [lename] Filename of fontset le to use. Can be a path relative to the maple, or a full path. IMAGECOLOR [r] [g] [b] Color to initialize the map with (i.e. background color). When transparency is enabled (TRANSPARENT ON in OUTPUTFORMAT) for the typical case of 8-bit pseudocolored map generation, this color will be marked as transparent in the output le 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 [jpeg|pdf|png|svg|...|userdened] Output format (raster or vector) to generate. The name used here must match the NAME of a user dened or internally available OUTPUTFORMAT. For a complete list of available IMAGEFORMATs, see the OUTPUTFORMAT section. INTERLACE [on|off] Deprecated Use FORMATOPTION INTERLACE=ON in the OUTPUTFORMAT declaration to specify if the output images should be interlaced. Deprecated since version 4.6. LAYER Signals the start of a LAYER object. 5.14. MAP 159
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). Default is 2048. NAME [name] Prex attached to map, scalebar and legend GIF lenames created using this maple. 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. 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 [lename] Path to the directory holding the shapeles 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 [lename] Filename of the symbolset to use. Can be a path relative to the maple, or a full path. Note: The SYMBOLSET le must start with the word SYMBOLSET and end with the word END. SYMBOL Signals the start of a SYMBOL object. TEMPLATEPATTERN [regular expression] This denes a regular expression to be applied to requests to change the TEMPLATE parameters via URL requests (i.e. map_layername_template=...). If a pattern doesnt exist then web users cant monkey with support les 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] Deprecated since version 4.6. Use TRANSPARENT ON in the OUTPUTFORMAT declaration to specify if the output images should be transparent. UNITS [dd|feet|inches|kilometers|meters|miles|nauticalmiles] 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.
160
Chapter 5. Maple
5.15 OUTPUTFORMAT
A map le may have zero, one or more OUTPUTFORMAT object declarations, dening 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 le, 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" FORMATOPTION "GAMMA=0.75" END OUTPUTFORMAT NAME "gif" DRIVER GD/GIF MIMETYPE "image/gif" IMAGEMODE PC256 EXTENSION "gif" END OUTPUTFORMAT NAME "png8" DRIVER AGG/ P N G 8 MIMETYPE "image/png; mode=8bit" IMAGEMODE RGB EXTENSION "png" FORMATOPTION "QUANTIZE_FORCE=on" FORMATOPTION "QUANTIZE_COLORS=256" FORMATOPTION "GAMMA=0.75" END OUTPUTFORMAT NAME "jpeg" DRIVER AGG/JPEG MIMETYPE "image/jpeg" IMAGEMODE RGB EXTENSION "jpg" FORMATOPTION "GAMMA=0.75" END OUTPUTFORMAT NAME "svg" DRIVER C A I R O / S V G MIMETYPE "image/svg+xml" IMAGEMODE RGB EXTENSION "svg" END OUTPUTFORMAT NAME "pdf" DRIVER C A I R O /PDF MIMETYPE "application/x-pdf" IMAGEMODE RGB EXTENSION "pdf" END OUTPUTFORMAT NAME "GTiff"
5.15. OUTPUTFORMAT
161
DRIVER G D A L /GTiff MIMETYPE "image/tiff" IMAGEMODE RGB EXTENSION "tif" END OUTPUTFORMAT NAME "kml" DRIVER K M L MIMETYPE "application/vnd.google-earth.kml.xml" IMAGEMODE RGB EXTENSION "kml" END OUTPUTFORMAT NAME "kmz" DRIVER K M Z 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
DRIVER [name] The name of the driver to use to generate this output format. Some driver names include the denition 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 efcient). TEMPLATE should be used for template based output. (mandatory) EXTENSION [type] Provide the extension to use when creating les of this type. (optional) FORMATOPTION [option] Provides a driver or format specic 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. GDAL/GTiff: Supports the TILED=YES, BLOCKXSIZE=n, BLOCKYSIZE=n, INTERLEAVE=[PIXEL/BAND] and COMPRESS=[NONE,PACKBITS,JPEG,LZW,DEFLATE] format specic options. GDAL/*: All FORMATOPTIONs are passed onto the GDAL create function. Options supported by GDAL are described in the detailed documentation for each GDAL format GDAL/*: NULLVALUE=n is used in raw image modes (IMAGEMODE BYTE/INT16/FLOAT) to preinitialize the raster and an attempt is made to record this in the resulting le as the nodata value. This is automatically set in WCS mode if rangeset_nullvalue is set. OGR/*: See OGR Output document for details of OGR format options.
162
Chapter 5. Maple
AGG/*: GAMMA=n is used to specify the gamma correction to apply to polygon rendering. Allowed values are ]0.0,1.0] , default is 0.75. This value is used to prevent artifacts from appearing on the border of contiguous polygons. Set to 1.0 to disable gamma correction. AGG/PNG: COMPRESSION=n is used to determine the ZLIB compression applied to the png creation. n is expected to be an integer value from 0 to 9, with 0 meaning no compression (not recommended), 1 meaning fastest compression, and 9 meaning best compression. The compression levels come at a cost (be it in terms of cpu processing or le size, chose the setting that suits you most). The default is COMPRESSION=6. AGG/PNG supports quantizing from 24/32 bits to 8bits, in order to reduce the nal image size (and therefore save bandwidth) (see also http://trac.osgeo.org/mapserver/ticket/2436#comment:4 for strategies when applying these options): QUANTIZE_FORCE=on used to reduce an RGB or RGBA image into an 8bit (or less) paletted images. The colors used in the palette are selected to best t the actual colors in the RGB or RGBA image. QUANTIZE_COLORS=256 used to specify the number of colors to be used when applying quantization. Maximum value is 256. Specifying anything between 17 and 255 is probably a waste of quality as each pixel is still encoded with a full byte. Specifying a value under 16 will produce tiny images, but severly degraded. PALETTE=/path/to/palette.txt is used to dene the absolute path where palette colors can be found. This le must contain 256 entries of r,g,b triplets for RGB imagemodes, or r,g,b,a quadruplets for RGBA imagemodes. The expected format is one triplet (or quadruplet) per line, each value separated by commas, and each triplet/quadruplet on a single line. If you want to use transparency with a palette, it is important to have these two colors in the palette le: 0,0,0,0 and 255,255,255,255. Note: 0,0,0,0 is important if you have fully transparent areas. 255,255,255,255 is opaque white. The important colors to have in your palette really depend on your actual map, although 0,0,0,0 , 0,0,0,255 , and 255,255,255,255 are very likely to show up most of the time. PALETTE_FORCE=on is used to reduce image depth with a predened palette. To allow additional colours for anti-aliasing other than those in the predened palette, use with QUANTIZE_COLORS. 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 oating 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)
5.15. OUTPUTFORMAT
163
NAME [name] The name to use in the IMAGETYPE keyword of the map le 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) TRANSPARENT [ON/OFF] Indicates whether transparency should be enabled for this format. Note that transparency 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 le 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.
5.16 PROJECTION
There are thousands of geographical reference systems. In order to combine datasets with different geographical reference systems into a map, the datasets will have to be transformed (projected) to the chosen geographical reference system of the map. If you want to know more about geographical reference systems and map projections, you could take some Geomatics courses (Geographical Information Systems, Cartography, Geodesy, ...). To set up projections you must dene one projection object for the output image (in the MAP object) and one projection object 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 specied within the object directly or referred to in an EPSG le. An EPSG le is a lookup le containing projection parameters, and is part of the PROJ.4 library. The following two examples both dene 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 le that contains a 26915 code with the full projection parameters. epsg in this instance is case-sensitive because it is referring to a le name. If your le system is case-sensitive, this must be lower case, or MapServer (Proj.4 actually) will complain about not being able to nd this le.
Note: See http://spatialreference.org/ref/epsg/26915 for more information on this coordinate system. The next two examples both display how to possibly dene unprojected lat/long (geographic):
164
Chapter 5. Maple
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 dened 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.17. QUERYMAP
165
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 ll. Default is red. EXTENT [minx][miny][maxx][maxy] The spatial extent of the base reference image. IMAGE [lename] Full lename of the base reference image. Must be a GIF image. MARKER [integer|string] Denes a symbol (from the symbol le) to use when the box becomes too small (see MINBOXSIZE and MAXBOXSIZE below). Uses a crosshair by default. MARKERSIZE [integer] Denes 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 dened 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 its 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 le. Future versions will make the image size available. ALIGN [left|center|right] Denes 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. Deprecated 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 scalebar 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.
166
Chapter 5. Maple
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 dene 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 ag 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 conjunction with the maps 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 nal intent is to have named styles (Not yet supported) that will be re-usable through the maple. This is the way of dening 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 species 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 species 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 species the rotation of the decoration symbol relative to the direction of the line. An angle of 0 means that the symbols x-axis is oriented along the direction of the line. For non-negativ (or absent) GAP values it species the rotation of the decoration symbol around its center. An angle of 0 means that the symbol is not rotated. For polygons, it species the angle of the lines in a HATCH symbol (0 - horizontal lines), or it species the rotation of the symbol used to generate the pattern in a polygon ll (it does not specify the rotation of the ll 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 GEOMTRANSFORM keyword. Note: Rotation using ANGLE is not supported for SYMBOLs of TYPE ellipse with the GD renderer (gif).
5.20. STYLE
167
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 species the distance between SYMBOLs (center to center) for decorated lines and polygon lls in layer SIZEUNITS. For polygon lls, GAP species 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 specied for the LAYER), GAP species the distance in layer SIZEUNITS at the map scale 1:SYMBOLSCALEDENOM. For lines, the rst 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 specied 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 specied. 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 current feature geometry. end: produces the last point of the current feature geometry. When used with ANGLE AUTO, it can for instance be used to render arrowheads on line segments. labelpnt: used for LABEL styles. Draws a marker on the geographic position the label is attached to. This corresponds to the center of the label text only if the label is in position CC. labelpoly: used for LABEL styles. Produces a polygon that covers the label plus a 1 pixel padding.
168
Chapter 5. Maple
start: produces the rst point of the current feature geometry. When used with ANGLE AUTO, it can for instance be used to render arrow tails on line segments. vertices: produces all the intermediate vertices (points) of the current feature 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 Construction 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 coefcient which multiplies a current symbol size. Default is 3. See Cartographical Symbol Construction with MapServer for explanation and examples. New in version 6.0: moved from SYMBOL MAXSIZE [double] Maximum size in pixels to draw a symbol. Default is 500. Starting from version 5.4, the value can also be a decimal value (and not only integer). See LAYER SYMBOLSCALEDENOM. MAXWIDTH [double] Maximum width in pixels 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). See LAYER SYMBOLSCALEDENOM. MINSIZE [double] Minimum size in pixels to draw a symbol. Default is 0. Starting from version 5.4, the value can also be a decimal value (and not only integer). See LAYER SYMBOLSCALEDENOM. MINWIDTH [double] Minimum width in pixels 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). See LAYER SYMBOLSCALEDENOM. OFFSET [x][y] Geometry offset values in layer SIZEUNITS. When scaling of symbols is in effect (SYMBOLSCALEDENOM is specied 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 rendering. 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 Specics 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 polygons and truetype). Has no effect for lines. The width of the outline can be specied using WIDTH. If no WIDTH is specied, an outline of one pixel will be drawn. If there is a SYMBOL dened for the STYLE, the OUTLINECOLOR will be used to create an outline for that SYMBOL (only ellipse, truetype and polygon vector symbols will get an outline). If there is no SYMBOL dened for the STYLE, the polygon will get an outline. 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:
5.20. STYLE
169
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 denes 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 specied for the LAYER), the numbers specify the lengths of the dashes and gaps in layer SIZEUNITS at the map scale 1:SYMBOLSCALEDENOM. 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
New in version 6.0: moved from SYMBOL SIZE [double|attribute] Height, in layer SIZEUNITS, of the symbol/pattern to be used. Default value depends on the SYMBOL TYPE. For pixmap: the hight (in pixels) of the pixmap; for ellipse and vector: the maximum y value of the SYMBOL POINTS parameter, for hatch: 1.0, for truetype: 1.0. When scaling of symbols is in effect (SYMBOLSCALEDENOM is specied for the LAYER), SIZE gives the height, in layer SIZEUNITS, of the symbol/pattern to be used at the map scale 1:SYMBOLSCALEDENOM. For symbols of TYPE hatch, the SIZE is the center to center distance between the lines. For its use with hatched lines, see Example#8 in the symbology examples. [attribute] was introduced in version 5.0, to specify the attribute to use for size values. The hard brackets [] are required. For example, if your data set has an attribute named MYHIGHT that holds size values for each feature, your STYLE object for hatched lines might contain:
STYLE SYMBOL hatch-test COLOR 255 0 0 ANGLE 45 SIZE [ M Y H I G H T ] 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|lename|url|attribute] The symbol to use for rendering the features. Integer is the index of the symbol in the symbol set, starting at 1 (the 5th symbol is symbol number 5). String is the name of the symbol (as dened using the SYMBOL NAME parameter). Filename species the path to a le containing a symbol. For example a PNG le. Specify the path relative to the directory containing the maple. URL species the address of a le containing a pixmap symbol. For example a PNG le. A URL must start with http:
170
Chapter 5. Maple
SYMBOL "http://myserver.org/path/to/file.png"
New in version 6.0. [attribute] allows individual rendering of features by using an attribute in the dataset that species the symbol name (as dened in the SYMBOL NAME parameter). The hard brackets [] are required. New in version 5.6. If SYMBOL is not specied, the behaviour depends on the type of feature. For points, nothing will be rendered. For lines, SYMBOL is only relevant if you want to style the lines using symbols, so the absence of SYMBOL means that you will get lines as specied using the relevant line rendering parameters (COLOR, WIDTH, PATTERN, LINECAP, ...). For polygons, the interior of the polygons will be rendered using a solid ll of the color specied in the COLOR parameter. See Also: SYMBOL 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 specied 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 species the width of the symbol outlines. This applies to SYMBOL TYPE vector (polygons), ellipse and truetype. For lines, WIDTH species the width of the line. For polygons, if used with OUTLINECOLOR, WIDTH species the thickness of the polygon outline. For a symbol of SYMBOL TYPE hatch, WIDTH species 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.4 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 denitions can be included within the main map le or, more commonly, in a separate le. Symbol denitions in a separate le are designated using the SYMBOLSET keyword, as part of the MAP object. This recommended setup is ideal for re-using symbol denitions 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. lled polygons) symbol 0 is a solid ll, and for lines, symbol 0 is a single pixel wide line. Symbol denitions contain no color information, colors are set within STYLE objects. For MapServer versions < 5 there is a maximum of 64 symbols per le. This can be changed by editing mapsymbol.h and changing the value of MS_MAXSYMBOLS at the top of the le. As of MapServer 5.0 there is no symbol limit. More information can be found in the Construction of Cartographic Symbols document.
5.21. SYMBOL
171
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. Youll need to gure out the mapping from the keyboard character to font character. FILLED [true|false] If true, the symbol will be lled with a user dened color (using STYLE COLOR). Default is false. If true, symbols of TYPE ellipse and vector will be treated as polygons (ll color specied using STYLE COLOR and outline specied using STYLE OUTLINECOLOR and WIDTH). If false, symbols of TYPE ellipse and vector will be treated as lines (the lines can be given a color using STYLE COLOR and a width using STYLE WIDTH). FONT [string] Name of TrueType font to use as dened 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. Deprecated since version 6.0. POINTS [x y] [x y] ... END Signies the start of a sequence of points that make up a symbol of TYPE vector or that dene the x and y radius of a symbol of TYPE ellipse. The end of this section is signied with the keyword END. The x and y values can be given using decimal numbers. The maximum x and y values dene the bounding box of the symbol. The size (actually height) of a symbol is dened 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 specied that denes the x and y radius of the ellipse. Circles are created when x and y are equal. Note: If a STYLE using this symbol doesnt 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 symbols background is the same as the parent image (i.e. color 0). This is user congurable. Note: The default (AGG) renderer does not support the TRANSPARENT parameter. It is supported by the GD renderer (GIF).
172
Chapter 5. Maple
TYPE [ellipse|hatch|pixmap|simple|truetype|vector] ellipse: radius values in the x and y directions dene 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 ll). truetype: TrueType font to use as dened in the MAP FONTSET. vector: a vector drawing is used to dene the shape of the symbol. Note: TYPE cartoline is no longer used. Dashed lines are specied using PATTERN, LINECAP, LINEJOIN and LINEJOINMAXSIZE in STYLE. Examples in Construction of Cartographic Symbols.
173
174
Chapter 5. Maple
Layer denition:
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.
175
Layer denition:
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
Author Frank Koormann Contact frank.koormann at intevation.de Author Jeff McKenna Contact jmckenna at gatewaygeomatics.com Revision $Revision$ Date $Date$
176
Chapter 5. Maple
5.23.1 Introduction
Templates are used: to dene the look of a MapServer CGI application interface and to present the results of a query. They guide the presentation of results, either a query or a map, to the user. Templates are almost always HTML les although they can also be a URL (e.g.. http://www.somewhere.com/[ATTRIBUTE]/info.html). URL templates can only be used with simple QUERY or ITEMQUERY results so many substitutions dened below are not available for them. Simple pan/zoom interfaces use a single template le while complicated queries often require many templates. Templates often use JavaScript to enhance the basic interface. Notes Templates must contain the magic string mapserver template in the rst 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 specic parameters as well as user dened 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 modied 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 le. ArcView and ArcInfo generally produce dbase les 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 les 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.
5.23. Templating
177
In HTML les, the attribute values can be inside quotes(). Writing attribute values inside quotes allows you to set special characters in value that you couldnt use normaly (ie: ],=, and space). To write a single quote in a attribute value, just use two quotes (). General [date] Outputs the date (as per the web servers clock). The default format is the same as is used by Apaches Common Log format, which looks like:
01/Dec/2010:17:34:58 -0800
Available arguments: format= A format string as supported by the standard C strftime() function. As an example, the default format is dened as:
[date format="%d/%b/%Y:%H:%M:%S %z"]
tz= timezone to use for the date returned. Default is local. Valid values are: gmt Output date will be Greenwich time local Output the time in the web servers local time zone. Additionally or alternatively, the %z and %Z strftime format strings allow the timezone offset or name to be output. [version] The MapServer version number. [id] Unique session id. The id can be passed in via a form but is more commonly generated by the software. In that case the id is a concatenation of UNIX time (or NT equivalent) and the process id. Unless youre getting more requests in a second than the system has process ids the id can be considered unique. ;-> [host] Hostname of the web server. [port] Port the web server is listening to. [post or get variable name], [post or get variable name_esc] The contents of any variables passed to the MapServer, whether they were used or not, can be echoed this way. One use might be to have the user set a map title or north arrow style in an interactive map composer. The system doesnt care about the values, but they might be real important in creating the nal output, e.g. if you specied a CGI parameter like myvalue=.... you can access this in the template le with [myvalue]. Also available as escaped version. [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 maple. 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 dened in the Maple). [ref] Path (relative to document root) of the new reference image.
178
Chapter 5. Maple
[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 dened in the Maple 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. [queryle] Path to the query le (if savequery was set as a CGI Parameter). [map] Path to the map le (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 applications. 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 [mapx], [mapy] X and Y coordinate of mouse click. [mapext], [mapext_esc] Full mapextent (separated by spaces). Also available as escaped version. (mapext_esc is deprecated in MapServer 5.2. You should use the escape= argument instead) The default template [mapext] 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 specic value. Specied in map coordinates. For example, [mapext] might return:
123456 123456 567890 567890
5.23. Templating
179
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 tting 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 specic value. Specied in map coordinates. For example, [rawext] might return:
123456 123456 567890 567890
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 extent. The following substitutions are only available if the MapServer was compiled with PROJ support and a PROJECTION is dened in the Maple. [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 enabled. 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:
180
Chapter 5. Maple
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 specic value. Specied in map coordinates. For example, [mapext_latlon] might return:
123456 123456 567890 567890
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 specic value. Specied in map coordinates. For example, [refext] might return:
123456 123456 567890 567890
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).
5.23. Templating
181
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 dened in the Maple 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 Maple. 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 le 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 specic value. Specied in map coordinates. For example, [shpext] might return:
123456 123456 567890 567890
format= Format of the coordinates. Default is $minx $miny $maxx $maxy. For example, to add commas to the coordinates you would use:
182
Chapter 5. Maple
[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): buffer=, Buffer size, currently the only unit available is pixels. Default is 0. centroid= Should only the centroid of the shape be used? true or false (case insensitive). Default is false. cs= Coordinate separator. Default is ,. irh=, irf=, orh=, orf= Characters to be put before (irh) and after (irf ) inner rings, and before (orh) and after (orf ) outer rings of polygons with holes. Defaults are . Note: Within each polygon, the outer ring is always output rst, followed by the inner rings. If neither irh nor orh are set, rings are output as parts using ph/pf /ps. ph=, pf=, ps= Characters to put before (ph) and after (pf ) and separators between (ps) feature parts (e.g. rings of multigeometries). Defaults are ph=, pf= and ps= . precision= The number of decimal places to output for coordinates. Default is 0. proj= The output projection denition for the coordinates, a special value of image will convert to image coordinates. Default is none. scale=, scale_x=, scale_y= Scaling factor for coordinates: Both axes (scale), x axis (scale_x) and y axis (scale_y). Defaults are 1.0. sh=, sf= Characters to put before (sh) and after (sf ) a feature. Defaults are . xh=, xf= Characters to put before (xh) and after (xf ) the x coordinates. Defaults are xh= and xf=,). yh= yf= Characters to put before (yh) and after (yf ) the y coordinates. Defaults are . As a simple example:
[shpxy xh="(" yf=")"] will result in: (x1 y1),(x2 y2),(x3 y3)
And a more complicated example of outputting KML for multipolygons which may potentially have holes (note that the parameters must all be on one line):
5.23. Templating
183
<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="<outerBoundaryIs><LinearRing><coordinates>" orf="</coordinates></LinearRing></outerBoundaryIs>" irh="<innerBoundaryIs><LinearRing><coordinates>" irf="</coordinates></LinearRing></innerBoundaryIs>" proj=epsg:4326 precision=10] </MultiGeometry>
[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 doesnt match the pattern (if dened). 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 le. ArcView, for example, uses all caps for shapele eld 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 specied in the Maple has to be given, second the tables elds 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. 184 Chapter 5. Maple
[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 le and footer specied in the Maple. [metadata_meta data key], [metadata_meta data key_esc] Queried data_projection] Also available as escaped version. For query modes that allow for multiple result sets, the following string substitutions are available. For FEATURESELECT 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 processing 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. layer meta data access (e.g [meta-
<!-- MapServer Template --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/transitional.dtd"> <html> <head> <title>MapServer Template Sample</title> </head> <body> MapServer Template Sample<br> <!-- The central form the application is based on. --> <form method="GET" action="[program]"> <!-- CGI MapServer applications are server stateless in principle, all information must be "stored" in the client. This includes some basic settings as below. The example is based on the pan and zoom test suite: http://maps.dnr.state.mn.us/mapserver_demos/tests36/ <input type="hidden" name="map" value="[map]"> <input type="hidden" name="imgext" value="[mapext]"> <input type="hidden" name="imgxy" value="149.5 199.5"> <input type="hidden" name="program" value="[program]"> <input type="hidden" name="htmlroot" value="[htmlroot]"> <input type="hidden" name="map_web" value="[map_web]"> <!-- A table for minimal page formatting. -->
-->
5.23. Templating
185
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
<table border=0 cellpadding=5> <tr> <!-- First column: Map and scale bar --> <td align=center> <!-- The map --> <input type="image" name="img" src="[img]" style="border:0;width:300;height:400"> <br> <!-- The scale bar--> <img src="[scalebar]" alt="Scale Bar"> </td> <!-- Second column: Zoom direction, Legend and Reference --> <td valign=top> <!-- Zoom direction --> <b>Map Controls</b><br> Set your zoom option:<br> <select name="zoom" size="1"> <option value="2" [ z o o m _ 2 _ s e l e c t ] > Zoom in 2 times <option value="1" [ z o o m _ 1 _ s e l e c t ] > Recenter Map
<option value="-2" [ z o o m _ - 2 _ s e l e c t ] > Zoom out 2 times </select> <br> <!-- Legend --> <b>Legend</b><br> <img src="[legend]" alt="Legend"><br><br><br><br> <!-- Reference map --> <input type="image" name="ref" src="[ref]" style="border:0;width:150;height:150"> </td> </tr> </table> </form> </body> </html>
186
Chapter 5. Maple
Table of Contents Union Layer Description Requirements Maple Conguration Feature attributes Classes and Styles Projections Examples * Maple 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 maple 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 doesnt use any external libraries to support it.
187
LAYER NAME "layer2" TYPE POINT STATUS OFF CONNECTIONTYPE S H A P E CONNECTION ... ... END LAYER NAME "layer3" TYPE POINT STATUS OFF CONNECTIONTYPE S H A P E CONNECTION ... ... END
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
Maple 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).
188
Chapter 5. Maple
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
189
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
190
Chapter 5. Maple
Example 2. Handling temporary les You have a user based discovery application that generates shapeles and stores them in a users home directory on the server. The username comes from a cookie, the lename comes from a request parameter.
DATA "/home/%username%/tempshp/%filename%"
This feature is only available in the CGI version of MapServer through a maple pre-processor. If you are using MapScript, you will have to code the substitution logic into your application yourself (By writing your own preprocessor).
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 dened 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 dened FOOTER [lename] Template to use AFTER anything else is sent. Multiresult query modes only. HEADER [lename] Template to use BEFORE everything else has been sent. Multiresult query modes only. IMAGEPATH [path] Path to the temporary directory fro writing temporary les 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:
191
LEGENDFORMAT "image/svg+xml"
LOG [lename] Since MapServer 5.0 the recommeded parameters to use for debugging are the MAP objects CONFIG 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. See Also: Map scale MAXSCALE [double] - deprecated Since MapServer 5.0 the proper parameter to use is MAXSCALEDENOM instead. 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. Deprecated since version 5.0. MAXTEMPLATE [le|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 dene things such as layer title. It can also allow more exibility 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 instead. 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 [lename|url]
192
Chapter 5. Maple
Template le or URL to use in presenting the results to the user in an interactive mode (i.e. map generates map and so on ... ). URL is not a remote le, rather a template. For example:
TEMPLATE http://someurl/somescript.cgi?mapext=[mapext]
TEMPPATH Path for storing temporary les. If not set, the standard system temporary le path will be used (e.g. tmp for unix). TEMPPATH can also be set using the environment variable MS_TEMPPATH. TEMPPATH is used in many contexts (see rfc66). Make sure that that Mapserver has sufcient rights to read and write les at the specied location. New in version 6.0. VALIDATION Signals the start of a VALIDATION block. As of MapServer 5.4.0, VALIDATION blocks are the preferred mechanism for specifying validation patterns for CGI param runtime substitutions. See Run-time Substitution.
5.27.2 Usage:
In order to enable this feature, set the MS_XMLMAPFILE_XSLT environment variable to point to the location of the XSLT to use for the XML->text maple conversion. e.g. in Apache:
SetEnv MS_XMLMAPFILE_XSLT /path/to/mapfile.xsl PassEnv MS_XMLMAPFILE_XSLT
With this enabled, passing an .xml lename to the CGI map parameter will automatically trigger the conversion. Note: This is a rst step to XML maple loading support. Obviously, there is a cost to parse and translate the XML maple, but this allows easier use of XML maples.
193
5.28 Notes
The Maple is NOT case-sensitive. The Mapfile is read from top to bottom by MapServer; this means that LAYERs near the top of your Maple will be drawn before those near the bottom. Therefore users commonly place background imagery and other background layer types near the top of their maple, and lines and points near the bottom of their maple. Strings containing non-alphanumeric characters or a MapServer keyword MUST be quoted. It is recommended to put ALL strings in double-quotes. For MapServer versions < 5, there was a default maximum of 200 layers per maple (there is no layer limit with MapServer >= 5). This can be changed by editing the map.h le to change the value of MS_MAXLAYERS to the desired number and recompiling. Here are other important default limits when using a MapServer version < 5: MAXCLASSES 250 (set in map.h) MAXSTYLES 5 (set in map.h) MAXSYMBOLS 64 (set in mapsymbol.h) MapServer versions >= 5 have no limits for classes, styles, symbols, or layers. File paths may be given as absolute paths, or as paths relative to the location of the maple. In addition, data les may be specied relative to the SHAPEPATH. The maple has a hierarchical structure, with the MAP object being the root. All other objects fall under this one. Comments are designated with a #. Attributes are named using the following syntax: [ATTRIBUTENAME]. Note: that the name of the attribute included between the square brackets IS CASE SENSITIVE. Generally ESRI generated shape data sets have their attributes (.dbf column names) all in upper-case for instance, and for PostGIS, ALWAYS use lower-case. MapServer Regular Expressions are used through the operating systems C Library. For information on how to use and write Regular Expressions on your system, you should read the documentation provided with your C Library. On Linux, this is GLibC, and you can read man 7 regex ... This man page is also available on most UNIXs. Since these RegExs are POSIX compliant, they should be the same on Windows as well, so windows users can try searching the web for man 7 regex since man pages are available all over the web.
194
Chapter 5. Maple
CHAPTER 6
MapScript
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 specic documentation located at Maple
6.1.1 Appendices
Language-specic extensions are described in the following appendices Python Appendix
6.1.3 fooObj
A paragraph or two about class fooObj. fooObj Attributes attribute [type [access]] Concise description of the attribute.
195
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 method(type mandatory_parameter [, type optional_parameter=default]) [type] Description of the method including elaboration on the method arguments, the methods actions, and returned values. Optional parameters and their default values are enclosed in brackets. Class method names are camel case with a leading lower case character like getExpressionString.
196
Chapter 6. MapScript
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 * shapeleObj * 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 specic documentation in DocBook format for the MDP. Appendices Language-specic extensions are described in the following appendices Python MapScript Appendix
197
Documentation Elements Classes will be documented in alphabetical order in the manner outlined below. Attributes and methods will be formatted as denition lists with the attribute or method as item, the type or return type as classier, and a concise description. To make the document as agnostic as possible, we refer to the following types: int, oat, 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 attributes value is read-only. fooObj A paragraph or two about class fooObj.
fooObj Attributes
attribute [type [access]] Concise description of the attribute. 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
method(type mandatory_parameter [, type optional_parameter=default]) [type] Description of the method including elaboration on the method arguments, the methods actions, and returned values. Optional parameters and their default values are enclosed in brackets. Class method names are camel case with a leading lower case character like getExpressionString. Additional Documentation Theres no point in duplicating the MapServer Maple Reference, which remains the primary reference for mapscript class attributes.
198
Chapter 6. MapScript
msIO_installStdinFromBuffer() [void] Installs a mapserver IO handler directing future stdin reading (ie. post request 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.
The other important associations for classObj are with styleObj, labelObj, and hashTableObj.
+-------+ 1 0..* +-------+ | Class | ---------> | Style | +-------+ +-------+ +-------+ 1 0..1 +-------+ | Class | ---------> | Label | +-------+ +-------+ +-------+ 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
debug [int] MS_TRUE or MS_FALSE keyimage [string] TODO Not sure what this attribute is for label [labelObj immutable] Denition of class labeling layer [layerObj immutable] Reference to the parent layer maxscaledenom [oat] The minimum scale at which class is drawn metadata [hashTableObj immutable] class metadata hash table. minscaledenom [oat] The maximum scale at which class is drawn
199
name [string] Unique within a layer numstyles [int] Number of styles for class. In the future, probably the 4.4 release, this attribute will be made immutable. status [int] MS_ON or MS_OFF. Draw features of this class or do not. template [string] Template for queries title [string] Text used for legend labeling type [int] The layer type of its parent layer
classObj Methods
new classObj( [ layerObj parent_layer=NULL ] ) [classObj] Create a new child classObj instance at the tail (highest 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 legend 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 appropriate to the expression type. getFirstMetaDataKey() [string] Returns the rst key in the metadata hash table. With getNextMetaDataKey(), provides an opaque iterator over keys. Note: getFirstMetaDataKey(), getMetaData(), and getNextMetaDataKey() are deprecated and will be removed in a future version. Replaced by direct metadata access, see hashTableObj. getMetaData( string key ) [string] Return the value of the classObj metadata at key. Note: getFirstMetaDataKey(), getMetaData(), and getNextMetaDataKey() are deprecated and will be removed in a future version. Replaced by direct metadata access, see hashTableObj. 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 rst 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.
200
Chapter 6. MapScript
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 rst 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
blue [int] Blue component of color in range [0-255] green [int] Green component of color in range [0-255] red [int] Red component of color in range [0-255] pen [int] Dont mess with this unless you know what you are doing! Note: Because of the issue with pen, setting colors by individual components is unreliable. Best practice is to use setRGB(), setHex(), or assign to a new instance of colorObj().
colorObj Methods
new colorObj( [ int red=0, int green=0, int blue=0, int pens=-4 ] ) [colorObj] Create a new instance. The color arguments are optional. setRGB( int red, int green, int blue ) [int] Set all three RGB components. MS_FAILURE. Returns MS_SUCCESS or
setHex( string hexcolor ) [int] Set the color to values specied 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.
201
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
code [int] MapServer error code such as MS_IMGERR (1). message [string] Context-dependent error message. routine [string] MapServer function in which the error was set.
errorObj Methods
next [errorObj] Returns the next error in the stack or NULL if the end has been reached. fontSetObj A fontSetObj is always a fontset attribute of a mapObj.
fontSetObj Attributes
lename [string immutable] Path to the fontset le on disk. fonts [hashTableObj immutable] Mapping of fonts. numfonts [int immutable] Number of fonts in set.
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
clear( ) [void] Empties the table of all items. get( string key [, string default=NULL ] ) [string] Returns the value of the item by its key, or default if the key does not exist.
202
Chapter 6. MapScript
nextKey( [string key=NULL] ) [string] Returns the name of the next key or NULL if there is no valid next key. If the input key is NULL, returns the rst key. remove( string key ) [int] Removes the hash item by its key. Returns MS_SUCCESS or MS_FAILURE. set( string key, string value ) [int] Sets a hash item. Returns MS_SUCCESS or MS_FAILURE. imageObj An image object is a wrapper for GD and GDAL images.
imageObj Attributes
format [outputFormatObj immutable] Image format. height [int immutable] Image height in pixels. imagepath [string immutable] If image is drawn by mapObj.draw(), this is the mapObjs web.imagepath. imageurl [string immutable] If image is drawn by mapObj.draw(), this is the mapObjs web.imageurl. renderer [int] MS_RENDER_WITH_GD, MS_RENDER_WITH_SWF, MS_RENDER_WITH_RAWDATA, MS_RENDER_WITH_PDF, or MS_RENDER_WITH_IMAGEMAP. Dont mess with this! size [int immutable] To access this attribute use the getSize method. Note: the getSize method is inefcient as it does a call to getBytes and then computes the size of the byte array. The bytearray is then immediately discarded. In most cases it is more efcient to call getBytes directly. width [int immutable] Image width in pixels.
imageObj Methods
new imageObj( int width, int height [, outputFormatObj format=NULL [, string lename=NULL ] ] ) [imageObj] Create new instance of imageObj. If lename is specied, an imageObj is created from the le and any specied width, height, and format parameters will be overridden by values of the image in lename. Otherwise, if format is specied an imageObj is created using that format. See the format attribute above for details. If lename is not specied, then width and height should be specied. 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 inefcient 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 efcient to call getBytes directly. save( string lename [, mapObj parent_map=NULL ] ) [int] Save image to lename. The optional parent_map parameter must be specied if saving GeoTIFF images. write( [ FILE le=NULL ] ) [int] Write image data to an open le 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. 6.2. SWIG MapScript API Reference 203
Note: The free() method of imageObj has been deprecated. In MapServer revisions 4+ all instances of imageObj will be properly disposed of by the interpreters garabage collector. If the application cant wait for garabage collection, then the instance can simply be deleted or undefd.
intarray An intarray is a utility class generated by SWIG useful for manipulating map layer drawing 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 specied length. labelCacheMemberObj An individual feature label. The labelCacheMemberObj class is associated with labelCacheObj.
+------------------+ 0..* 1 +------------+ | LabelCacheMember | <--------- | LabelCache | +------------------+ +------------+
labelCacheMemberObj Attributes
classindex [int immutable] Index of the class of the labeled feature. featuresize [oat immutable] TODO label [labelObj immutable] Copied from the class of the labeled feature. layerindex [int immutable] The index of the layer of the labeled feature. numstyles [int immutable] Number of styles as for the class of the labeled feature. point [pointObj immutable] Label point. poly [shapeObj immutable] Label bounding box. shapeindex [int immutable] Index within shapele of the labeled feature. status [int immutable] Has the label been drawn or not? styles [styleObj immutable] TODO this should be protected from SWIG. text [string immutable] Label text. tileindex [int immutable] Tileindex of the layer of the labeled feature.
204
Chapter 6. MapScript
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 maps 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
cachesize [int immutable] TODO markercachesize [int immutable] TODO numlabels [int immutable] Number of label members. nummarkers [int immutable] Number of marker members.
labelCacheObj Methods
freeCache( ) [void] Free the labelcache. labelObj A labelObj is associated with a classObj, a scalebarObj, or a legendObj.
+-------+ 0..1 1 +----------+ | Label | <--------- | Class | +-------+ | -------- | | Scalebar | | -------- | | Legend | +----------+
labelObj Attributes
angle [oat] TODO antialias [int] MS_TRUE or MS_FALSE autoangle [int] MS_TRUE or MS_FALSE
205
autofollow [int] MS_TRUE or MS_FALSE. Tells mapserver to compute a curved label for appropriate linear features (see MS RFC 11: Support for Curved Labels for specics). autominfeaturesize: int MS_TRUE or MS_FALSE backgroundcolor [colorObj] Color of background rectangle or billboard. Deprecated since version 6.0: Use styleObj and geomtransform. backgroundshadowcolor [colorObj] Color of background rectangle or billboard shadow. Deprecated since version 6.0: Use styleObj and geomtransform. backgroundshadowsizex [int] Horizontal offset of drop shadow in pixels. Deprecated since version 6.0: Use styleObj and geomtransform. backgroundshadowsizey [int] Vertical offset of drop shadow in pixels. Deprecated since version 6.0: Use styleObj and geomtransform. buffer [int] Maybe this shouldve been named padding since thats what it is: padding in pixels around a label. color [colorObj] Foreground color. 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 at: http://www.foss4g.org/FOSS4G/MAPSERVER/mpsnf-i18n-en.html. font [string] Name of TrueType font. force [int] MS_TRUE or MS_FALSE. 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. numstyles [int] Number of label styles 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 ow 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
getBinding( int binding ) [string] Get the attribute binding for a specied label property. Returns NULL if there is no binding for this property.
206
Chapter 6. MapScript
getStyle( int index ) [styleObj] Return a reference to the styleObj at index in the styles array. 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. removeBinding( int binding ) [int] Remove the attribute binding for a specled label property. setBinding ( int binding, string item ) [int] Set the attribute binding for a specied label property. Binding constants look like this: MS_LABEL_BINDING_[attribute name].
setBinding(MS_LABEL_BINDING_COLOR, "FIELD_NAME_COLOR");
Update
label
from
string
snippet.
Returns
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 le 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 connection type setConnectionType() should be used in order to initialize the layer vtable properly. data [string] Layer data denition, values depend upon connectiontype. debug [int] Enable debugging of layer. MS_ON or MS_OFF (default).
207
dump [int] Switch to allow mapserver to return data in GML format. MS_TRUE or MS_FALSE. Default is MS_FALSE. Deprecated since version 6.0: metadata is used instead. extent [rectObj] optional limiting extent for layer features. lteritem [string] Attribute dening lter. footer [string] TODO group [string] Name of a group of layers. header [string] TODO index [int immutable] Index of layer within parent maps layers array. labelangleitem [string] Attribute dening label angle. labelcache [int] MS_ON or MS_OFF. Default is MS_ON. labelitem [string] Attribute dening feature label text. labelmaxscaledenom [oat] Minimum scale at which layer will be labeled. labelminscaledenom [oat] Maximum scale at which layer will be labeled. labelrequires [string] Logical expression. labelsizeitem [string] Attribute dening label size. map [mapObj immutable] Reference to parent map. maxfeatures [int] Maximum number of layer features that will be drawn. For shapele data this means the rst N features where N = maxfeatures. maxscaledenom [oat] Minimum scale at which layer will be drawn. metadata [hashTableObj immutable] Layer metadata. minscaledenom [oat] Maximum scale at which layer will be drawn. name [string] Unique identier 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. opacity [int] Layer opacity percentage in range [0, 100]. The special value of MS_GD_ALPHA (1000) indicates that the alpha transparency of pixmap symbols should be honored, and should be used only for layers that use RGBA pixmap symbols. postlabelcache [int] MS_TRUE or MS_FALSE. Default is MS_FALSE. requires [string] Logical expression. sizeunits [int] Units of class size values. MS_INCHES, MS_FEET, MS_MILES, MS_NAUTICALMILES, MS_METERS, MS_KILOMETERS, MS_DD or MS_PIXELS status [int] MS_ON, MS_OFF, or MS_DEFAULT. styleitem [string] Attribute dening styles. symbolscaledenom [oat] Scale at which symbols are default size.
208
Chapter 6. MapScript
template [string] Template le. Note that for historical reasons, the query attribute must be non-NULL for a layer to be queryable. tileindex [string] Layer index le for tiling support. tileitem [string] Attribute dening tile paths. tolerance [oat] Search buffer for point and line queries. toleranceunits [int] MS_INCHES, MS_FEET, MS_KILOMETERS, MS_DD or MS_PIXELS MS_MILES, MS_NAUTICALMILES, MS_METERS,
transform [int] Whether or not layer data is to be transformed to image units. MS_TRUE or MS_FALSE. Default is MS_TRUE. Case of MS_FALSE is for data that are in image coordinates such as annotation points. type [int] See MS_LAYER_TYPE in mapserver.h. units [int] Units of the layer. See MS_UNITS in mapserver.h.
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 maple? 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 le. Processing directives supported are specic 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 layers 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. 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 layers 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 layers 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. Note: demote() is removed in MapServer 4.4 draw( mapObj map, imageObj image ) [int] Renders this layer into the target image, adding labels to the cache if required. Returns MS_SUCCESS or MS_FAILURE. TODO: Does the map need to be the map on which the layer is dened? I suspect so. drawQuery( mapObj map, imageObj image ) : Draw query map for a single layer into the target image. Returns MS_SUCCESS or MS_FAILURE. executeWFSGetFeature( layer ) [string] Executes a GetFeature request on a WFS layer and returns the name of the temporary GML le created. Returns an empty string on error.
209
generateSLD() [void] Returns an SLD XML string based on all the classes found in the layer (the layer must have STATUS on). getClass( int i ) [classObj] Fetch the requested class object. Returns NULL if the class index is out of the legal range. The numclasses eld contains the number of classes available, and the rst class is index 0. getExtent() [rectObj] Fetches the extents of the data in the layer. This normally requires a full read pass through the features of the layer and does not work for raster layers. getFeature( int shapeindex [, int tileindex=-1 ] ) [shapeObj] Return the layer feature at shapeindex and tileindex. getFilterString() [string] Returns the current lter expression. getFirstMetaDataKey() [string] Returns the rst key in the metadata hash table. With getNextMetaDataKey(), provides an opaque iterator over keys. Note: getFirstMetaDataKey(), getMetaData(), and getNextMetaDataKey() are deprecated and will be removed in a future version. Replaced by direct metadata access, see hashTableObj. getItem( int i ) [string] Returns the requested item. Items are attribute elds, and this method returns the item name (eld name). The numitems eld contains the number of items available, and the rst item is index zero. getMetaData( string key ) [string] Return the value at key from 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. 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 rst 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. getNumFeatures() [int] Returns the number of inline features in a layer. TODO: is this really only online features or will it return the number of non-inline features on a regular layer? getNumResults() [int] Returns the number of entries in the query result cache for this layer. Note: getNumResults() and getResult() are deprecated in MapServer 4.4. Users should instead use the new querying API described in querying-HOWTO.txt. layerObj::getResults() is the entry point for the new API. getProcessing( int index) [string] Return the raster processing directive at index. getProjection( ) [string] Returns the PROJ.4 denition of the layers projection. getResult( int i ) [resultCacheMemberObj] Fetches the requested query result cache entry, or NULL if the index is outside the range of available results. This method would normally only be used after issuing a query operation. Note: getNumResults() and getResult() are deprecated in MapServer 4.4. Users should instead use the new querying API described in querying-HOWTO.txt. layerObj::getResults() is the entry point for the new API. getResults() [resultCacheObj] Returns a reference to layers result cache. Should be NULL prior to any query, or after a failed query or query with no results. getResultsBounds() [rectObj] Returns the bounds of the features in the result cache.
210
Chapter 6. MapScript
getShape( shapeObj shape, int tileindex, int shapeindex ) [int] Get a shape from layer data. Note: getShape() is deprecated. Users should adopt getFeature() for new applications. getWMSFeatureInfoURL( mapObj map, int click_x, int click_y, int feature_count, string info_format ) [string] Return a WMS GetFeatureInfo URL (works only for WMS layers) clickX, clickY is the location of to query in pixel coordinates with (0,0) at the top left of the image. featureCount is the number of results to return. infoFormat is the format the format in which the result should be requested. Depends on remote servers 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, minscaledenom, and maxscaledenom within the context of the parent map. moveClassDown( int class ) [int] The class specied 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 specied by the class index will be moved up into the array of layers. Returns 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 intersect current map extents. qitem is the item (attribute) on which the query is performed, and qstring is the expression 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 layers 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 another layer. At present the results MUST be based on a polygon layer. Returns MS_SUCCESS if shapes were
211
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 layers result cache. By default clobbers existing cache. Returns MS_SUCCESS or MS_FAILURE. queryByPoint( mapObj map, pointObj point, int mode, oat buffer ) [int] Query layer at point location specied 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 le (in pixels) but you can use a constant buffer (specied 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 specied 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. 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 eld 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 recreates the vtable according to the new connection type. This method should be used instead of setting the connectiontype parameter directly. In case when the layer.connectiontype = MS_PLUGIN the library_str parameter should also be specied so as to select the library to load by mapserver. For the other connection types this parameter is not used. setExtent( oat minx, oat miny, oat maxx, oat maxy ) [int] Sets the extent of a layer. Returns MS_SUCCESS or MS_FAILURE. setFilter( string lter ) [int] Sets a lter expression similarly to the FILTER expression in a map le. 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. Processing directives supported are specic to the layer type and underlying renderer. setProjection( string proj4 ) [int] Set the layer projection using a PROJ.4 format projection denition (ie. +proj=utm +zone=11 +datum=WGS84 or init=EPSG:26911). Returns MS_SUCCESS or MS_FAILURE.
212
Chapter 6. MapScript
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 function basically prepares things so that candidate features can be accessed by query or drawing functions (eg using nextShape function). Returns MS_SUCCESS, MS_FAILURE or MS_DONE. MS_DONE is returned if the layer extent does not overlap rect. resultsGetShape(int shapeindex [, int tileindex = -1]) [shapeObj] Retrieve shapeObj from a layers resultset by index. Tileindex is optional and is used only for tiled shapeles, 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 is associated with mapObj
+--------+ 0..1 1 +-----+ | Legend | <--------> | Map | +--------+ +-----+
legendObj Attributes
height [int] Legend height. imagecolor [colorObj] Legend background color. keysizex [int] Width in pixels of legend keys. keysizey [int] Pixels. keyspacingx [int] Horizontal padding around keys in pixels. keyspacingy [int] Vertical padding. label [labelObj immutable] legend label. map [mapObj immutable] Reference to parent mapObj. outlinecolor [colorObj] key outline color. position [int] MS_UL, MS_UC, MS_UR, MS_LL, MS_LC, or MS_LR. postlabelcache [int] MS_TRUE or MS_FALSE. status [int] MS_ON, MS_OFF, or MS_EMBED. template [string] Path to template le. width [int] Label width.
legendObj Methods
None
213
lineObj Attributes
new lineObj( ) [lineObj] Create a new instance. 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. Returns 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 A mapObj is primarily associated with instances of layerObj.
+-----+ 0..1 0..* +-------+ | Map | <--------> | Layer | +-----+ +-------+
outputFormatObj.
+-----+ 1 1..* +--------------+ | Map | ---------> | OutputFormat | +-----+ +------------- +
mapObj Attributes
cellsize [oat] Pixel size in map units. congoptions [hashObj immutable] A hash table of conguration options from CONFIG keywords in the .map. Direct access to cong options is discouraged. Use the setCongOption() and getCongOption() methods instead.
214
Chapter 6. MapScript
datapattern [string] TODO not sure this is meaningful for mapscript. debug [int] MS_TRUE or MS_FALSE. extent [rectObj] Maps spatial extent. fontset [fontSetObj immutable] The maps dened fonts. height [int] Maps output image height in pixels. Note: direct setting of height is deprecated in MapServer version 4.4. Users should set width and height simultaneously using setSize(). imagecolor [colorObj] Initial map background color. imagequality [int] JPEG image quality. Note: map imagequality is deprecated in MapServer 4.4 and should instead be managed through map outputformats. imagetype [string immutable] Name of the current output format. interlace [int] Output image interlacing. Note: map interlace is deprecated in MapServer 4.4 and should instead be managed through map outputformats. lablecache [labelCacheObj immutable] Maps labelcache. legend [legendObj immutable] Reference to maps legend. mappath [string] Filesystem path of the maps maple. maxsize [int] TODO ? name [string] Unique identier. numlayers [int immutable] Number of map layers. numoutputformats [int] Number of output formats. outputformat [outputFormatObj] The currently selected output format. Note: Map outputformat should not be modied directly. Use the selectOutputFormat() method to select named formats. outputformatlist [outputFormatObj[]] Array of the available output formats. Note: Currently only available for C#. A proper typemaps should be implemented for the other languages. querymap [queryMapObj immutable] TODO should this be exposed to mapscript? reference [referenceMapObj immutable] Reference to reference map. resolution [oat] Nominal DPI resolution. Default is 72. scaledenom [oat] The nominal map scale. A value of 25000 means 1:25000 scale. scalebar [scalebarObj immutable] Reference to the scale bar. shapepath [string] Base lesystem path to layer data. 6.2. SWIG MapScript API Reference 215
status [int] MS_OFF, MS_ON, or MS_DEFAULT. symbolset [symbolSetObj immutable] The maps set of symbols. templatepattern [string] TODO not sure this is meaningful for mapscript. transparent [int] MS_TRUE or MS_FALSE. Note: map transparent is deprecated in MapServer 4.4 and should instead be managed through map outputformats. units [int] MS_DD, MS_METERS, etc. web [webObj immutable] Reference to maps web denitions. width [int] Maps output image width in pixels. Note: direct setting of width is deprecated in MapServer version 4.4. Users should set width and height simultaneously using setSize().
mapObj Methods
new mapObj( [ string lename= ] ) [mapObj] Create a new instance of mapObj. Note that the lename is now optional. appendOutputFormat( outputFormatObj format ) [int] Attach format to the maps output format list. Returns the updated number of output formats. applyCongOptions( ) [void] Apply the dened conguration options set by setCongOption(). applySLD( string sldxml ) [int] Parse the SLD XML string sldxml and apply to map layers. Returns MS_SUCCESS or MS_FAILURE. applySLDURL( string sldurl ) [int] Fetch SLD XML from the URL sldurl and apply to map layers. Returns MS_SUCCESS or MS_FAILURE. clone( ) [mapObj] Returns a independent copy of the map, less any caches. Note: In the Java module this method is named cloneMap. draw( ) [imageObj] Draw the map, processing layers according to their dened order and status. Return an imageObj. drawLabelCache( imageObj image ) [int] Draw maps label cache on image. MS_FAILURE. drawLegend( ) [imageObj] Draw map legend, returning an imageObj. drawQuery( ) [imageObj] Draw query map, returning an imageObj. drawReferenceMap( ) [imageObj] Draw reference map, returning an imageObj. drawScalebar( ) [imageObj] Draw scale bar, returning an imageObj. embedLegend( imageObj image ) [int] Embed maps legend in image. Returns MS_SUCCESS or MS_FAILURE. embedScalebar( imageObj image ) [int] Embed maps scalebar in image. MS_FAILURE. Returns MS_SUCCESS or Returns MS_SUCCESS or
freeQuery( [ int qlayer=-1 ] ) [void] Clear layer query result caches. Default is -1, or all layers.
216
Chapter 6. MapScript
generateSLD( ) [string] Return SLD XML as a string for map layers that have STATUS on. getCongOption( string key ) [string] Fetches the value of the requested conguration key if set. Returns NULL if the key is not set. getFirstMetaDataKey( ) [string] Returns the rst key in the web.metadata hash table. With getNextMetaDataKey( ), provides an opaque iterator over keys. getLayer( int index ) [layerObj] Returns a reference to the layer at index. getLayerByName( string name ) [layerObj] Returns a reference to the named layer. getLayersDrawingOrder( ) [int*] Returns an array of layer indexes in drawing order. Note: Unless the proper typemap is implemented for the modules language a user is more likely to get back an unuseable SWIG pointer to the integer array. getMetaData( string key ) [string] Return the value at key from the web.metadata hash table. getNextMetaDataKey( string lastkey ) [string] Returns the next key in the web.metadata hash table or NULL if lastkey is the last valid key. If lastkey is NULL, returns the rst key of the metadata hash table. getNumSymbols( ) [int] Return the number of symbols in map. getOutputFormatByName( string imagetype ) [outputFormatObj] Return the output format corresponding to driver name imagetype or to format name imagetype. This works exactly the same as the IMAGETYPE directive in a maple, is case insensitive and allows an output format to be found either by driver (like GD/PNG) or name (like PNG24). getProjection( ) [string] Returns the PROJ.4 denition of the maps projection. getSymbolByName( string name ) [int] Return the index of the named symbol in the maps symbolset. 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 symbols index number. insertLayer( layerObj layer [, int nIndex=-1 ] ) [int] 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. loadMapContext( string lename [, int useUniqueNames=MS_FALSE ] ) [int] Load an OGC map context le to dene 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 lename ) [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 maps 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 specied index from the maps labelcache.
217
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 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. processQueryTemplate( string names[], string values[], int numitems ) [string] Process MapServer query 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. 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 contained 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, oat 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. removeLayer( int index ) [int] Remove the layer at index. removeMetaData( string key ) [int] Delete the web.metadata hash at key. MS_FAILURE. Returns MS_SUCCESS or
removeOutputFormat( string name ) [int] Removes the format named name from the maps output format list. Returns MS_SUCCESS or MS_FAILURE. save( string lename ) [int] Save map to disk as a new map le. Returns MS_SUCCESS or MS_FAILURE. saveMapContext( string lename ) [int] Save map denition to disk as OGC-compliant XML. Returns MS_SUCCESS or MS_FAILURE. saveQuery( string lename ) [int] Save query to disk. Returns MS_SUCCESS or MS_FAILURE.
218
Chapter 6. MapScript
saveQueryAsGML( string lename ) [int] Save query to disk. Returns MS_SUCCESS or MS_FAILURE. selectOutputFormat( string imagetype ) [void] Set the maps active output format to the internal format named imagetype. Built-in formats are PNG, PNG24, JPEG, GIF, GTIFF. setCongOption( string key, string value ) [void] Set the indicated key conguration option to the indicated value. Equivalent to including a CONFIG keyword in a map le. setExtent( oat minx, oat miny, oat maxx, oat maxy ) [int] Set the map extent, returns MS_SUCCESS or MS_FAILURE. offsetExtent( oat x, oat y) [int] Offset the map extent based on the given distances in map coordinates, returns MS_SUCCESS or MS_FAILURE. scaleExtent( oat zoomfactor, oat minscaledenom, oat maxscaledenom) [int] Scale the map extent using the zoomfactor and ensure the extent within the minscaledenom and maxscaledenom domain. If minscaledenom and/or maxscaledenom is 0 then the parameter is not taken into account. returns MS_SUCCESS or MS_FAILURE. setCenter( pointObj center ) [int] Set the map center to the given map point, returns MS_SUCCESS or MS_FAILURE. setFontSet( string lename ) [int] Load fonts dened in lename into map fontset. The existing fontset is cleared. Returns MS_SUCCESS or MS_FAILURE. setImageType( string name ) [void] Sets map outputformat to the named format. Note: setImageType() remains in the module but its use is deprecated in favor of selectOutputFormat(). setLayersDrawingOrder( int layerindexes[]) [int] Set map layer drawing order. Note: Unless the proper typemap is implemented for the modules language users will not be able to pass arrays or lists to this method and it will be unusable. setMetaData( string key, string value ) [int] Assign value to the web.metadata hash at key. Return MS_SUCCESS or MS_FAILURE. setOutputFormat( outputFormatObj format ) [void] Sets map outputformat. setProjection( string proj4 ) [int] Set map projection from PROJ.4 denition string proj4. setRotation( oat rotation_angle ) [int] Set map rotation angle. The map view rectangle (specied 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. setSize( int width, int height ) [int] Set maps image width and height together and carry out the necessary subsequent geotransform computation. Returns MS_SUCCESS or MS_FAILURE. setSymbolSet( string lename ) [int] Load symbols dened in lename into map symbolset. The existing symbolset is cleared. Returns MS_SUCCESS or MS_FAILURE. setWKTProjection( string wkt ) [int] Sets map projection from OGC denition 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
219
constrained to a maximum maxextent. The imgrect rectangle contains the coordinates of the LL and UR coordinates 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( oat scale, pointObj imgpoint, int width, int height, rectObj extent, rectObj maxextent) [int] Like the previous methods, but zooms to the point at a specied scale. markerCacheMemberObj An individual marker. The markerCacheMemberObj class is associated with labelCacheObj.
+------------------+ 0..* 1 +------------+ | MarkerCacheMember | <--------- | LabelCache | +------------------+ +------------+
markerCacheMemberObj Attributes
id [int immutable] Id of the marker. poly [shapeObj immutable] Marker bounding box.
markerCacheMemberObj Methods
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 formatoption ... this eld should be considered read-only. driver [string] A string such as GD/PNG or GDAL/GTiff. extension [string] Format le 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.
220
Chapter 6. MapScript
mimetype [string] Format mimetype such as image/png. name [string] A unique identier. 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 le 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 specic. 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 xed 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 MapServers OWS capabilities. Using it permits creation of lightweight WMS services:
wms_map = mapscript.mapObj(wms.map) wms_request = mapscript.OWSRequest() # Convert application request parameters (req.args) for param, value in req.args.items(): wms_request.setParam(param, value) # Map loads parameters from OWSRequest, adjusting its SRS, extents, # active layers accordingly wms_map.loadWMSRequest(1.1.0, wms_request) # Render the Map img = wms_map.draw()
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.
221
OWSRequest Methods
new OWSRequest( ) [OWSRequest] Create a new instance. Note: MapServers OWSRequest supports only single valued parameters. setParameter( string name, string value ) [void] Set a request parameter. For example
request.setParameter(REQUEST, GetMap) request.setParameter(BBOX, -107.0,40.0,-106.0,41.0)
addParameter( string name, string value ) [void] Add a request parameter, even if the parameter key was previousely set. This is useful when multiple parameters with the same key are required. For example
request.addParameter(SIZE, x(100)) request.addParameter(SIZE, y(100))
getName( int index ) [string] Return the name of the parameter at index in the requests array of parameter names. getValue( int index ) [string] Return the value of the parameter at index in the requests array of parameter values. getValueByName( string name) [string] Return the value associated with the parameter name. loadParams() [int] Initializes the OWSRequest object from the cgi environment variables REQUEST_METHOD, QUERY_STRING and HTTP_COOKIE. Returns the number of name/value pairs collected. Warning: most errors will result in a process exit! loadParamsFromURL( string url ) [int] Initializes the OWSRequest object from the provided URL which is treated like a QUERY_STRING. Note that REQUEST_METHOD=GET and no post data is assumed in this case. This method was added in MapServer 6.0. pointObj A pointObj instance may be associated with a lineObj.
+-------+ 1..* 0..1 +------+ | Point | <--------- | Line | +-------+ +------+
pointObj Attributes
m [oat] Measure. Meaningful only for measured shapeles. Given value -2e38 if not otherwise assigned to indicate nodata. x [oat] Easting y [oat] Northing z [oat] Elevation
pointObj Methods
new pointObj( [ oat x=0.0, oat y=0.0, oat z=0.0, oat m=-2e38 ] ) [pointObj] Create new instance. Easting, northing, and measure arguments are optional. distanceToPoint( pointObj point ) [oat] Returns the distance to point.
222
Chapter 6. MapScript
distanceToSegment( pointObj point1, pointObj point2 ) [oat] Returns the minimum distance to a hypothetical line segment connecting point1 and point2. distanceToShape( shapeObj shape ) [oat] Returns the minimum distance to shape. draw( mapObj map, layerObj layer, imageObj image, int classindex, string text ) [int] Draw the point using the styles dened 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. Transformation is done in place. Returns MS_SUCCESS or MS_FAILURE. setXY( oat x, oat y [, oat 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( oat x, oat y, oat z [, oat m=-2e38 ] ) [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 -1e38. Returns MS_SUCCESS or MS_FAILURE. setXYZM( oat x, oat y, oat z, oat m ) [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 -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 }
toShape() [shapeObj] Convience method to quickly turn a point into a shapeObj. projectionObj This class is not really fully implemented yet. MapServers 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())
new projectionObj( string proj4 ) [projectionObj] Create new instance of projectionObj. Input parameter proj4 is a PROJ.4 denition string such as init=EPSG:4269. getUnits() [int] Returns the units of a projection object. Returns -1 on error. 6.2. SWIG MapScript API Reference 223
rectObj A rectObj may be a lone object or an attribute of another object and has no other associations.
rectObj Attributes
maxx [oat] Maximum easting maxy [oat] Maximum northing minx [oat] Minimum easting miny [oat] Minimum northing
rectObj Methods
new rectObj( [ oat minx=-1.0, oat miny=-1.0, oat maxx=-1.0, oat 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 fth 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 using style dened 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 ve 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 Attributes
color [colorObj] Color of reference box. extent [rectObj] Spatial extent of reference in units of parent map.
224
Chapter 6. MapScript
height [int] Height of reference map in pixels. image [string] Filename of reference map image. map [mapObj immutable] Reference to parent mapObj. marker [int] Index of a symbol in the map symbol set to use for marker. markername [string] Name of a symbol. markersize [int] Size of marker. maxboxsize [int] Pixels. minboxsize [int] Pixels. outlinecolor [colorObj] Outline color of reference box. status [int] MS_ON or MS_OFF. width [int] In pixels.
referenceMapObj Methods
None resultCacheMemberObj Has no associations with other MapScript classes and has no methods. By using several indexes, a resultCacheMemberObj refers to a single layer feature.
resultCacheMemberObj Attributes
classindex [int immutable] The index of the layer class into which the feature has been classied. shapeindex [int immutable] Index of the feature within the layer. tileindex [int immutable] Meaningful for tiled layers only, index of the shapele data tile. resultCacheObj See querying-HOWTO.txt for extra guidance in using the new 4.4 query API.
resultCacheObj Attributes
bounds [rectObj immutable] Bounding box of query results. numresults [int immutable] Length of result set.
resultCacheObj Methods
getResult( int i ) [resultCacheMemberObj] Returns the result at index i, like layerObj::getResult, or NULL if index is outside the range of results.
225
scalebarObj Attributes
backgroundcolor [colorObj] Scalebar background color. color [colorObj] Scalebar foreground color. imagecolor [colorObj] Background color of scalebar. height [int] Pixels. intervals [int] Number of intervals. label [labelObj] Scalebar label. outlinecolor [colorObj] Foreground outline color. position [int] MS_UL, MS_UC, MS_UR, MS_LL, MS_LC, or MS_LR. postlabelcache [int] MS_TRUE or MS_FALSE. status [int] MS_ON, MS_OFF, or MS_EMBED. style [int] 0 or 1. units [int] See MS_UNITS in mapserver.h. width [int] Pixels.
scalebarObj Methods
None shapeleObj
shapeleObj Attributes
bounds [rectObj] Extent of shapes numshapes [int] Number of shapes type [int] See mapshape.h for values of type.
226
Chapter 6. MapScript
shapeleObj Methods
new shapeleObj( string lename [, int type=-1 ] ) [shapeleObj] Create a new instance. Omit the type argument or use a value of -1 to open an existing shapele. add( shapeObj shape ) [int] Add shape to the shapele. Returns MS_SUCCESS or MS_FAILURE. get( int i, shapeObj shape ) [int] Get the shapele feature from index i and store it in shape. Returns MS_SUCCESS or MS_FAILURE. getShape( int i ) [shapeObj] Returns the shapele feature at index i. More effecient than get. TODO shapeObj Each feature of a layers data is a shapeObj. Each part of the shape is a closed lineObj.
+-------+ 1 1..* +------+ | Shape | --------> | Line | +-------+ +------+
shapeObj Attributes
bounds [rectObj] Bounding box of shape. classindex [int] The class index for features of a classied layer. index [int] Feature index within the layer. numlines [int immutable] Number of parts. numvalues [int immutable] Number of shape attributes. text [string] Shape annotation. tileindex [int] Index of tiled le for tileindexed layers. type [int] MS_SHAPE_POINT, MS_SHAPE_LINE, MS_SHAPE_POLYGON, or MS_SHAPE_NULL.
shapeObj Methods
new shapeObj( int type ) [shapeObj] Return a new shapeObj of the specied 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 coordinates 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. NULL/undef on failure. Requires GEOS support. Returns
227
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. MS_FALSE otherwise. Requires GEOS support. Returns -1 on error and
difference( shapeObj shape ) [shapeObj] Returns the computed difference of the supplied and existing shape. Requires 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 ) [oat] Return distance to point. distanceToShape( shapeObj shape ) [oat] Return the minimum distance to shape. draw( mapObj map, layerObj layer, imageObj img ) [int] Draws the individual shape using layer. MS_SUCCESS or MS_FAILURE. Returns
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 geometry. 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. Transformation 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. simplify( double tolerance ): shapeObj Given a tolerance, returns a simplied shape object or NULL on error. Requires GEOS support (>=3.0). symDifference( shapeObj shape ) [shapeObj] Returns the computed symmetric difference of the supplied and existing shape. Requires GEOS support. Returns NULL/undef on failure.
228
Chapter 6. MapScript
topologySimplifyPreservingSimplify( double tolerance ): shapeObj Given a tolerance, returns a simplied shape object or NULL on error. Requires GEOS support (>=3.0). 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 is associated with one instance of classObj.
+-------+ 0..* 1 +-------+ | Style | <-------- | Class | +-------+ +-------+
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]Deprecated since version 5.0: Use setBinding. antialias [int] MS_TRUE or MS_FALSE. Should TrueType fonts be antialiased. backgroundcolor [colorObj] Background pen color. color [colorObj] Foreground or ll pen color. mincolor [colorObj] Attribute for Color Range Mapping (MS RFC 6: Color Range Mapping of Continuous Feature Values). mincolor, minvalue, maxcolor, maxvalue dene 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 dene the range for mapping a continuous feature value to a continuous range of colors when rendering the feature on the map. 6.2. SWIG MapScript API Reference 229
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 dene 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 dene 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/eld 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 styles pen or symbol. sizeitem [string]Deprecated since version 5.0: Use setBinding. symbol [int] The index within the map symbolset of the styles symbol. symbolname [string immutable] Name of the styles 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. getBinding( int binding ) [string] Get the attribute binding for a specied style property. Returns NULL if there is no binding for this property. removeBinding( int binding ) [int] Remove the attribute binding for a specled style property. setBinding ( int binding, string item ) [int] Set the attribute binding for a specied style property. Binding constants look like this: MS_STYLE_BINDING_[attribute name].
setBinding(MS_STYLE_BINDING_SIZE, mySizeItem);
Update
style
from
string
snippet.
Returns
setSymbolByName(mapObj map, string symbolname) [int] Setting the symbol of the styleObj given the reference of the map object and the symbol name. updateFromString ( string snippet ) [int] MS_SUCCESS/MS_FAILURE. Update a style from a string snippet. Returns
230
Chapter 6. MapScript
A styleObj will often refer to a symbolObj by name or index, but this is not really an object association, is it?
symbolObj Attributes
antialias [int] MS_TRUE or MS_FALSE. character [string] For TrueType symbols. lled [int] MS_TRUE or MS_FALSE. font [string] For TrueType symbols. gap [int] Moved to STYLE imagepath [string] Path to pixmap le. inmaple [int] If set to TRUE, the symbol will be saved inside the maple. Added in MapServer 5.6.1 linecap [int] Moved to STYLE linejoin [int] Moved to STYLE linejoinmaxsize [oat] Moved to STYLE name [string] Symbol name numpoints [int immutable] Number of points of a vector symbol. position [int] No more available? sizex [oat] TODO what is this? sizey [oat] TODO what is this? stylelength [int] Number of intervals transparent [int] TODO what is this? transparentcolor [int] TODO is this a derelict attribute? type [int] MS_SYMBOL_SIMPLE, MS_SYMBOL_VECTOR, MS_SYMBOL_PIXMAP, or MS_SYMBOL_TRUETYPE.
symbolObj Methods
MS_SYMBOL_ELLIPSE,
new symbolObj( string symbolname [, string imagele ] ) [symbolObj] Create new default symbol named name. If imagele is specied, then the symbol will be of type MS_SYMBOL_PIXMAP. getImage() [imageObj] Returns a pixmap symbols imagery as an imageObj. getPoints() [lineObj] Returns the symbol points as a lineObj. setImage( imageObj image ) [int] Set a pixmap symbols imagery from image. setPoints( lineObj line ) [int] Sets the symbol points from the points of line. Returns the updated number of points.
231
setStyle( int index, int value ) [int] Set the style at index to value. Returns MS_SUCCESS or MS_FAILURE. symbolSetObj A symbolSetObj is an attribute of a mapObj and is associated with instances of symbolObj.
+-----------+ 1 0..* +--------+ | SymbolSet | --------> | Symbol | +-----------+ +--------+
symbolSetObj Attributes
lename [string] Symbolset lename numsymbols [int immutable] Number of symbols in the set.
symbolSetObj Methods
new symbolSetObj( [ string symbolle ] ) [symbolSetObj] Create new instance. If symbolle is specied, symbols will be loaded from the le. 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 lename ) [int] Save symbol set to a le. 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 denitions like temporary le paths, template paths, etc.
webObj Attributes
empty [string] TODO error [string] TODO extent [rectObj] Clipping extent. footer [string] Path to footer document. header [string] Path to header document. imagepath [string] Filesystem path to temporary image location. imageurl [string] URL to temporary image location. log [string] TODO map [mapObj immutable] Reference to parent mapObj.
232
Chapter 6. MapScript
maxscaledenom [oat] Minimum map scale. maxtemplate [string] TODO metadata [hashTableObj immutable] metadata hash table. minscaledenom [oat] Maximum map scale. mintemplate [string] TODO queryformat [string] TODO template [string] Path to template document.
webObj Methods
None.
Note: If you are migrating your existing application that is based on MapServer 5.6 or older, to MapServer 6.0 or beyond, please read the PHP MapScript Migration Guide for important changes.
233
Contents PHP MapScript Introduction Versions Supported How to Get More Information on PHP MapScript Important Note Constants Functions Classes * classObj * clusterObj * colorObj * errorObj * gridObj * hashTableObj * imageObj * labelcacheMemberObj * labelcacheObj * labelObj * layerObj * legendObj * lineObj * mapObj * outputformatObj * OwsrequestObj * pointObj * projectionObj * querymapObj * rectObj * referenceMapObj * resultObj * scalebarObj * shapeleObj * shapeObj * styleObj * symbolObj * webObj Memory Management
6.3.1 Introduction
This is a PHP module that makes MapServers 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.
234
Chapter 6. MapScript
The module has been tested and used on Linux, Solaris, *BSD, and Windows.
6.3.5 Constants
The following MapServer constants are available: Boolean values MS_TRUE, MS_FALSE, MS_ON, MS_OFF, MS_YES, MS_NO Map units MS_INCHES, MS_FEET, MS_MILES, MS_METERS, MS_KILOMETERS, MS_DD, MS_PIXELS, MS_NAUTICALMILES Layer types MS_LAYER_POINT, MS_LAYER_LINE, MS_LAYER_POLYGON, MS_LAYER_RASTER, MS_LAYER_ANNOTATION, MS_LAYER_QUERY, MS_LAYER_CIRCLE, MS_LAYER_TILEINDEX, MS_LAYER_CHART Layer/Legend/Scalebar/Class Status MS_ON, MS_OFF, MS_DEFAULT, MS_EMBED, MS_DELETE Layer alpha transparency allows alpha transparent pixmaps to be used with RGB map images MS_GD_ALPHA Font types MS_TRUETYPE, MS_BITMAP Label positions MS_UL, MS_LR, MS_UR, MS_LL, MS_CR, MS_CL, MS_UC, MS_LC, MS_CC, MS_XY, MS_AUTO, MS_AUTO2, MS_FOLLOW, MS_NONE Bitmap font styles MS_TINY , MS_SMALL, MS_MEDIUM, MS_LARGE, MS_GIANT Shape types MS_SHAPE_POINT, MS_SHAPE_LINE, MS_SHAPE_POLYGON, MS_SHAPE_NULL Shapele types MS_SHP_POINT, MS_SHP_ARC, MS_SHP_POLYGON, MS_SHP_MULTIPOINT Query/join types MS_SINGLE, MS_MULTIPLE Querymap styles MS_NORMAL, MS_HILITE, MS_SELECTED Connection Types MS_INLINE, MS_SHAPEFILE, MS_TILED_SHAPEFILE, MS_SDE, MS_OGR, MS_TILED_OGR, MS_POSTGIS, MS_WMS, MS_ORACLESPATIAL, MS_WFS, MS_GRATICULE, MS_RASTER, MS_PLUGIN, MS_UNION Error codes MS_NOERR, MS_IOERR, MS_TTFERR, MS_DBFERR, MS_MISCERR, MS_CGIERR, MS_NOTFOUND, MS_SHPERR, MS_MEMERR, MS_TYPEERR, MS_SYMERR, MS_REGEXERR, MS_GDERR, MS_IDENTERR, MS_EOFERR, MS_PROJERR, MS_WEBERR, MS_IMGERR, MS_HASHERR, MS_JOINERR, MS_PARSEERR, MS_SDEERR, MS_OGRERR, MS_QUERYERR,
235
MS_WMSERR, MS_WMSCONNERR, MS_ORACLESPATIALERR, MS_WFSERR, MS_WFSCONNERR, MS_MAPCONTEXTERR, MS_HTTPERR, MS_WCSERR Symbol types MS_SYMBOL_SIMPLE, MS_SYMBOL_VECTOR, MS_SYMBOL_PIXMAP, MS_SYMBOL_TRUETYPE MS_SYMBOL_ELLIPSE,
Image Mode types (outputFormatObj) MS_IMAGEMODE_PC256, MS_IMAGEMODE_RGB, MS_IMAGEMODE_RGBA, MS_IMAGEMODE_INT16, MS_IMAGEMODE_FLOAT32, MS_IMAGEMODE_BYTE, MS_IMAGEMODE_FEATURE, MS_IMAGEMODE_NULL Style/Attribue binding MS_STYLE_BINDING_SIZE, MS_STYLE_BINDING_ANGLE, MS_STYLE_BINDING_COLOR, MS_STYLE_BINDING_OUTLINECOLOR, MS_STYLE_BINDING_SYMBOL, MS_STYLE_BINDING_WIDTH Label/Attribute binding MS_LABEL_BINDING_SIZE, MS_LABEL_BINDING_ANGLE, MS_LABEL_BINDING_COLOR, MS_LABEL_BINDING_OUTLINECOLOR, MS_LABEL_BINDING_FONT, MS_LABEL_BINDING_PRIORITY, MS_LABEL_BINDING_POSITION, MS_LABEL_BINDING_SHADOWSIZEX, MS_LABEL_BINDING_SHADOWSIZEY Alignment MS_ALIGN_LEFT, MS_ALIGN_CENTER, MS_ALIGN_RIGHT OwsRequest MS_GET_REQUEST, MS_POST_REQUEST
6.3.6 Functions
string ms_GetVersion() Returns the MapServer version and options in a string. This string can be parsed to nd 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. int ms_iogetStdoutBufferBytes() Writes the current buffer to stdout. The PHP header() function should be used to set the documentss 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_iogetstdoutbufferstring() Fetch the current stdout buffer contents as a string. This method does not clear the buffer. void ms_ioinstallstdinfrombuffer() Installs a mapserver IO handler directing future stdin reading (ie. post request capture) to come from a buffer. void ms_ioinstallstdouttobuffer() Installs a mapserver IO handler directing future stdout output to a memory buffer. 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. array ms_TokenizeMap(string map_le_name) Preparses a maple through the MapServer parser and return an array with one item for each token from the maple. Strings, logical expressions, regex expressions and comments are returned as individual tokens.
6.3.7 Classes
The following class objects are available through PHP MapScript.
236
Chapter 6. MapScript
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 string string labelObj double hashTableObj double string int int string string int
Methods
Name group keyimage label maxscaledenom metadata minscaledenom name numstyles status template title type
Note
imageObj createLegendIcon(int width, int height) Draw the legend icon and return a new imageObj. int deletestyle(int index) Delete the style specied by the style index. If there are any style that follow the deleted style, their index will decrease by 1. int drawLegendIcon(int width, int height, imageObj im, int dstX, int dstY) Draw the legend icon on im object at dstX, dstY. 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. string getExpressionString() Returns the expression string for the class object. 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: getMetaDatas query is case sensitive. styleObj getStyle(int index) Return the style object using an index. index >= 0 && index < class->numstyles. string getTextString() Returns the text string for the class object.
237
int movestyledown(int index) The style specied 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 movestyleup(int index) The style specied by the style index will be moved up into the array of classes. Returns MS_SUCCESS or MS_FAILURE. ex class->movestyleup(1) will have the effect of moving style 1 up to position 0, and the style at position 0 will be moved to position 1. int removeMetaData(string name) Remove a metadata entry for the class. Returns MS_SUCCESS/MS_FAILURE. int set(string property_name, new_value) Set object property to a new value. int setExpression(string expression) Set the expression string for the class object. int setMetaData(string name, string value) Set MS_SUCCESS/MS_FAILURE. a metadata entry for the class. Returns
int settext(string text) Set the text string for the class object. int updateFromString(string snippet) Update MS_SUCCESS/MS_FAILURE. a class from a string snippet. Returns
/*set the color */ $oClass->updateFromString(CLASS STYLE COLOR 255 0 255 END END);
clusterObj
Constructor
string getFilterString() Returns the expression for this cluster lter or NULL on error. string getGroupString() Returns the expression for this cluster group or NULL on error. int setFilter(string expression) Set layer lter expression. int setGroup(string expression) Set layer group expression. colorObj
Constructor
238
Chapter 6. MapScript
Members
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 rst 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
errorObj ms_GetErrorObj() Returns a reference to the head of the list of errorObj. void ms_ResetErrorList() Clear the current error list. Note that clearing the list invalidates any errorObj handles obtained via the $error->next() method.
Members
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(); }
239
gridObj
Constructor
The grid is always embedded inside a layer object dened as a grid (layer->connectiontype = MS_GRATICULE) (for more docs : https://github.com/mapserver/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
int set(string property_name, new_value) Set object property to a new value. 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
void clear() Clear all items in the hashTable (To NULL). string get(string key) Fetch class metadata entry by name. Returns if no entry matches the name. Note that the search is case sensitive. string nextkey(string previousKey) Return the next key or rst key if previousKey = NULL. Return NULL if no item is in the hashTable or end of hashTable is reached int remove(string key) Remove a metadata entry in the hashTable. Returns MS_SUCCESS/MS_FAILURE. 240 Chapter 6. MapScript
int set(string key, string value) Set a metadata entry in the hashTable. Returns MS_SUCCESS/MS_FAILURE. imageObj
Constructor
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 wont be copied). Pass -1 if you dont want any transparent color. If optional dstx,dsty are provided then it denes 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 specied (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). int saveImage([string lename, MapObj oMap]) Writes image object to specied lename. Passing no lename or an empty lename sends output to stdout. In this case, the PHP header() function should be used to set the documents content-type prior to calling saveImage(). The output format is the one that is currently selected in the map le. The second argument oMap is not manadatory. It is usful when saving to formats like GTIFF that needs georeference informations contained in the map le. On success, it returns either MS_SUCCESS if writing to an external le, 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 le. labelcacheMemberObj Accessible only through the mapObj (map->getLabel()).
241
Members
Type int int int int int int int string int
Method
Name classindex featuresize layerindex markerid numstyles shapeindex status text tileindex
Note read-only read-only read-only read-only read-only read-only read-only read-only read-only
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
Type int double int int int colorObj colorObj int int int colorObj
Name align angle anglemode antialias autominfeaturesize backgroundcolor (deprecated since 6.0) backgroundshadowcolor (deprecated since 6.0) backgroundshadowsizex (deprecated since 6.0) backgroundshadowsizey (deprecated since 6.0) buffer color Continued on next page
242
Chapter 6. MapScript
Table 6.1 continued from previous page Type Name string encoding string font int force int maxlength int maxsize int mindistance int minfeaturesize int minlength int minsize int numstyles int offsetx int offsety colorObj outlinecolor int outlinewidth int partials int position int priority int repeatdistance colorObj shadowcolor int shadowsizex int shadowsizey int size int type int wrap
Methods
int deleteStyle(int index) Delete the style specied by the style index. If there are any style that follow the deleted style, their index will decrease by 1. 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. string getBinding(const labelbinding) Get the attribute binding for a specied 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
styleObj getStyle(int index) Return the style object using an index. index >= 0 && index < label->numstyles. int moveStyleDown(int index) The style specied by the style index will be moved down into the array of classes. Returns MS_SUCCESS or MS_FAILURE. ex label->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 moveStyleUp(int index) The style specied by the style index will be moved up into the array of classes. Returns MS_SUCCESS or MS_FAILURE. ex label->movestyleup(1) will have the effect of moving style 1 up to position 0, and the style at position 0 will be moved to position 1. int removeBinding(const labelbinding) Remove the attribute binding for a specled style property. Example:
243
$oStyle->removebinding(MS_LABEL_BINDING_COLOR);
int set(string property_name, new_value) Set object property to a new value. int setBinding(const labelbinding, string value) Set the attribute binding for a specied label property. Example:
$oLabel->setbinding(MS_LABEL_BINDING_COLOR, "FIELD_NAME_COLOR");
This would bind the color parameter with the data (ie will extract the value of the color from the eld called FIELD_NAME_COLOR int updateFromString(string snippet) Update MS_SUCCESS/MS_FAILURE. layerObj
Constructor
label
from
string
snippet.
Returns
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 int hashTableObj string string clusterObj string int string int int string string gridObj string string int int string double double string int
Name annotate bindvals classgroup classitem cluster connection connectiontype data debug dump lteritem footer grid group header index labelcache labelitem labelmaxscaledenom labelminscaledenom labelrequires maxfeatures
Note
read-only
244
Chapter 6. MapScript
Type double hashTableObj double string int int colorObj int projectionObj int string int int int string double string string string double int int int
Methods
Table 6.2 continued from previous page Name Note maxscaledenom metadata minscaledenom name num_processing numclasses read-only offsite opacity projection postlabelcache requires sizeunits startindex status MS_ON, MS_OFF, MS_DEFAULT or MS_DELETE styleitem symbolscaledenom template tileindex tileitem tolerance toleranceunits transform type
int addFeature(shapeObj shape) Add a new feature in a layer. Returns MS_SUCCESS or MS_FAILURE on error. int applySLD(string sldxml, string namedlayer) Apply the SLD document to the layer object. The matching between the sld document and the layer will be done using the layers 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 object. The matching between the sld document and the layer will be done using the layers 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. void clearProcessing() Clears all the processing strings. void close() Close layer previously opened with open(). int draw(imageObj image) Draw a single layer, add labels to cache if required. MS_FAILURE on error. int drawQuery(imageObj image) Draw query map for a single layer. string executeWFSGetfeature() Executes a GetFeature request on a WFS layer and returns the name of the temporary GML le created. Returns an empty string 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. string generateSLD() Returns an SLD XML string based on all the classes found in the layer (the layer must have STATUS on). 6.3. PHP MapScript 245 Returns MS_SUCCESS or
classObj getClass(int classIndex) Returns a classObj from the layer given an index value (0=rst class) int getClassIndex(shape [, classgroup, numclasses]) Get the class index of a shape for a given scale. Returns -1 if no class matches. classgroup is an array of class ids to check (Optionnal). numclasses is the number of classes that the classgroup array contains. By default, all the layer classes will be checked. rectObj getExtent() Returns the layers data extents or NULL on error. If the layers EXTENT member is set then this value is used, otherwise this call opens/closes the layer to read the extents. This is quick on shapeles, but can be an expensive operation on some le formats or data sources. This function is safe to use on both opened or closed layers: it is not necessary to call open()/close() before/after calling it. string getFilterString() Returns the expression for this layer or NULL on error. array getGridIntersectionCoordinates() Returns an array containing the grid intersection coordinates. If there are no coordinates, it returns an empty array. array getItems() Returns an array containing the items. Must call open function rst. If there are no items, it returns an empty array. int getMetaData(string name) Fetch layer metadata entry by name. Returns if no entry matches the name. Note that the search is case sensitive. Note: getMetaDatas query is case sensitive. int getNumResults() Returns the number of results in the last query. array getProcessing() Returns an array containing the processing strings. If there are no processing strings, it returns an empty array. string getProjection() Returns a string representation of the projection. Returns NULL on error or if no projection is set. 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. rectObj getResultsBounds() Returns the bounding box of the latest result. shapeObj getShape(resultObj result]) If the resultObj passed has a valid resultindex, retrieve shapeObj from a layers 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"; }
string getWMSFeatureInfoURL(int clickX, int clickY, int featureCount, string infoFormat) Returns a WMS GetFeatureInfo URL (works only for WMS layers) clickX, clickY is the location of to query in pixel coordinates with (0,0) at the top left of the image. featureCount is the number of results to return. infoFormat is the format the format in which the result should be requested. Depends on remote servers 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. 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.).
246
Chapter 6. MapScript
int moveclassdown(int index) The class specied 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. int moveclassup(int index) The class specied by the class index will be moved up into the array of layers. Returns 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 open() Open the layer for use with getShape(). Returns MS_SUCCESS/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();
int queryByAttributes(string qitem, string qstring, int mode) Query layer for shapes that intersect current map extents. qitem is the item (attribute) on which the query is performed, and qstring is the expression 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 layers 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 (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 set based on a previous set of results from another 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 queryByPoint(pointObj point, int mode, double buffer) Query layer at point location specied 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 -1 defaults to tolerances set in the map le (in pixels) but you can use a constant buffer (specied 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 layer using a rectangle specied 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. 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 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 (note that the error message in case nothing was found can be avoided in PHP using the @ control operator). 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 eld contains the number
247
of classes available. int removeMetaData(string name) Remove a metadata entry for the layer. Returns MS_SUCCESS/MS_FAILURE. int set(string property_name, new_value) Set object property to a new value. 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 specied so as to select the library to load by MapServer. For the other connection types this parameter is not used. int setFilter(string expression) Set layer lter expression. int setMetaData(string name, string value) Set MS_SUCCESS/MS_FAILURE. a metadata entry for the layer. Returns
int setProcessing(string) Add the string to the processing string list for the layer. The layer->num_processing is incremented by 1. Returns MS_SUCCESS or MS_FAILURE on error.
$oLayer->setprocessing("SCALE_1=AUTO"); $oLayer->setprocessing("SCALE_2=AUTO");
int setProjection(string proj_params) Set layer projection and coordinate system. Parameters are given as a single string of comma-delimited PROJ.4 parameters. Returns MS_SUCCESS or MS_FAILURE on error. int setWKTProjection(string proj_params) Same as setProjection(), but takes an OGC WKT projection denition string as input. Note: setWKTProjection requires GDAL support int updateFromString(string snippet) Update MS_SUCCESS/MS_FAILURE. a layer from a string snippet. Returns
/*modify the name */ $oLayer->updateFromString(LAYER NAME land_fn2 END); /*add a new class*/ $oLayer->updateFromString(LAYER CLASS STYLE COLOR 255 255 0 END END END);
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, MS_FAILURE or MS_DONE. MS_DONE is returned if the layer extent does not overlap the rectObj. legendObj
Constructor
Instances of legendObj are always are always embedded inside the mapObj.
248
Chapter 6. MapScript
Members
Type int colorObj int int int int labelObj colorObj int int int string int
Methods
Name height imagecolor keysizex keysizey keyspacingx keyspacingy label outlinecolor position postlabelcache status template width
Note
Color of outline of box, -1 for no outline for embeded legends, MS_UL, MS_UC, ... MS_TRUE, MS_FALSE MS_ON, MS_OFF, MS_EMBED
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. int set(string property_name, new_value) Set object property to a new value. int updateFromString(string snippet) Update MS_SUCCESS/MS_FAILURE. lineObj
Constructor new lineObj()
legend
from
string
snippet.
Returns
Members
Type int
Methods
Name numpoints
Note read-only
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 les only. It is not mandatory.
249
point
to
the
end
of
line.
Returns
Note: the 4th parameter m is used for measured shape les 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 projection (2nd argument). Returns MS_SUCCESS/MS_FAILURE. mapObj
Constructor new mapObj(string map_file_name [, string new_map_path])
or using the old constructors mapObj ms_newMapObj(string map_le_name [, string new_map_path]) Returns a new object to deal with a MapServer map le. mapObj ms_newMapObjFromString(string map_le_string [, string new_map_path]) Construct mapObj from a maple string. Returns a new object to deal with a MapServer map le. a new
Note: By default, the SYMBOLSET, FONTSET, and other paths in the maple are relative to the maple location. If new_map_path is provided then this directory will be used as the base path for all the rewlative paths inside the maple.
Members
Type double int double rectObj string int colorObj int int int int labelcacheObj legendObj string int hashTableObj string int
Name cellsize debug defresolution extent; fontsetlename height imagecolor keysizex keysizey keyspacingx keyspacingy labelcache legend mappath maxsize metadata name numlayers
Note
250
Chapter 6. MapScript
Type outputformatObj projectionObj querymapObj referenceMapObj double scalebarObj double string int string int webObj int
Methods
Table 6.3 continued from previous page Name Note outputformat projection querymap reference resolution pixels per inch, defaults to 72 scalebar scaledenom read-only, set by drawMap() shapepath status symbolsetlename read-only, set by setSymbolSet() units map units type web width see setSize()
int applycongoptions() Applies the cong options set in the map le. For example setting the PROJ_LIB using the setcongoption only modies the value in the map object. applycongoptions will actually change the PROJ_LIB value that will be used when dealing with projection. int applySLD(string sldxml) Apply the SLD document to the map le. The matching between the sld document and the map le will be done using the layers 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 le. The matching between the sld document and the map le will be done using the layers name. See SLD HowTo for more information on the SLD support. imageObj draw() Render map and return an image object or NULL on error. int drawLabelCache(imageObj image) Renders the labels for a map. Returns MS_SUCCESS or MS_FAILURE on error. imageObj drawLegend() Render legend and return an image object. imageObj drawQuery() Render a query map and return an image object or NULL on error. 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. 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. void freeQuery(layerindex) Frees the query result on a specied layer. If the layerindex is -1, all queries on layers will be freed. string generateSLD() Returns an SLD XML string based on all the classes found in all the layers that have STATUS on.
251
array getAllGroupNames() Return an array containing all the group names used in the layers. If there are no groups, it returns an empty array. array getAllLayerNames() Return an array containing all the layer names. If there are no layers, it returns an empty array. colorObj getColorbyIndex(int iCloIndex) Returns a colorObj corresponding to the color index in the palette. string getCongOption(string key) Returns the cong value associated with the key. Returns an empty sting if key not found. labelcacheMemberObj getLabel(int index) Returns a labelcacheMemberObj from the map given an index value (0=rst 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=rst layer) layerObj getLayerByName(string layer_name) Returns a layerObj from the map given a layer name. Returns NULL if layer doesnt exist. array getLayersDrawingOrder() Return an array containing layers index in the order which they are drawn. If there are no layers, it returns an empty array. array getLayersIndexByGroup(string groupname) Return an array containing all the layers indexes given a group name. If there are no layers, it returns an empty array. int getMetaData(string name) Fetch metadata entry by name (stored in the WEB object in the map le). Returns if no entry matches the name. Note: getMetaDatas query is case sensitive. int getNumSymbols() Return the number of symbols in map. string getProjection() Returns a string representation of the projection. Returns NULL on error or if no projection is set. 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. 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. int loadMapContext(string lename [, boolean unique_layer_name]) Available only if WMS support is enabled. Load a WMS Map Context XML le into the current mapObj. If the map already contains some layers then the layers dened 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 prex 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 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 loadQuery(lename) Loads a query from a le. Returns MS_SUCESS or MS_FAILURE. To be used with savequery. 252 Chapter 6. MapScript
int moveLayerDown(int layerindex) Move layer down in the hierarcy of drawing. Returns MS_SUCCESS or MS_FAILURE on error. int moveLayerUp(int layerindex) Move layer up in the hierarcy of drawing. MS_FAILURE on error. Returns MS_SUCCESS or
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 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()) imageObj prepareImage() Return a blank image object. void prepareQuery() Calculate the scale of the map and set map->scaledenom. string processLegendTemplate(array params) Process legend template les and return the result in a buffer. See Also: processtemplate string processQueryTemplate(array params, boolean generateimages) Process query template les 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 processTemplate(array params, boolean generateimages) Process the template le specied in the web object and return the result in a buffer. The processing consists of opening the template le and replace all the tags found in it. Only tags that have an equivalent element in the map object are replaced (ex [scaledenom]). The are two exceptions to the previous statement : [img], [scalebar], [ref], [legend] would be replaced with the appropriate url if the parameter generateimages is set to MS_TRUE. (Note : the images corresponding to the different objects are generated if the object is set to MS_ON in the map le) the user can use the params parameter to specify tags and their values. For example if the user have a specic tag call [my_tag] and would like it to be replaced by value_of_my_tag he would do
$tmparray["my_tag"] = "value_of_my_tag"; $map->processtemplate($tmparray, MS_FALSE);
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 specic 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 queryByPoint(pointObj point, int mode, double buffer) Query all selected layers in map at point location specied 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 le (in pixels) but you can use a constant buffer (specied in ground units) instead. Returns MS_SUCCESS if shapes were found or MS_FAILURE if nothing was found or if some other 6.3. PHP MapScript 253
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 specied 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. 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). 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. int removeMetaData(string name) Remove a metadata entry for the map (stored in the WEB object in the map le). Returns MS_SUCCESS/MS_FAILURE. int save(string lename) Save current map object state to a le. Returns -1 on error. Use absolute path. If a relative path is used, then it will be relative to the maple location. int saveMapContext(string lename) 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 le. Returns MS_SUCCESS/MS_FAILURE. int saveQuery(string lename[, int results]) Save the current query in a le. Results determines the save format MS_TRUE (or 1/true) saves the query results (tile index and shape index), MS_FALSE (or 0/false) the query parameters (and the query will be re-run in loadquery). Returns MS_SUCCESS or MS_FAILURE. Either save format can be used with loadquery. See RFC 65 and ticket #3647 for details of different save formats. 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 minscaledenom and/or maxscaledenom is 0 then the parameter is not taken into account. Returns MS_SUCCESS or MS_FAILURE. int selectOutputFormat(string type) Selects the output format to be used in the map. MS_SUCCESS/MS_FAILURE. Returns
Note: the type used should correspond to one of the output formats declared in the map le. 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 set(string property_name, new_value) Set map object property to new value. int setCenter(pointObj center) Set the map center to the given map point. MS_FAILURE. Returns MS_SUCCESS or
int setCongOption(string key, string value) Sets a cong parameter using the key and the value passed void setExtent(double minx, double miny, double maxx, double maxy) Set the map extents using the georef extents passed in argument. Returns MS_SUCCESS or MS_FAILURE on error. int setFontSet(string leName) Load and set a new FONTSET. boolean setLayersDrawingOrder(array layeryindex) Set the layers order array. The argument passed must be a valid array with all the layers index. Returns MS_SUCCESS or MS_FAILURE on error. int setMetaData(string name, string value) Set a metadata entry for the map (stored in the WEB object in the map le). Returns MS_SUCCESS/MS_FAILURE. 254 Chapter 6. MapScript
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 : bSetUnitsAndExtents is used to automatically update the map units and extents based on the new projection. Possible values are MS_TRUE and MS_FALSE. By defualt it is set at MS_FALSE. int setRotation(double rotation_angle) Set map rotation angle. The map view rectangle (specied 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 setSymbolSet(string leName) Load and set a symbol le dynamically. int setWKTProjection(string proj_params, boolean bSetUnitsAndExtents) Same as setProjection(), but takes an OGC WKT projection denition string as input. Returns MS_SUCCESS or MS_FAILURE on error. Note: setWKTProjection requires GDAL support 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 impossible 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 specied 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.
255
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 impossible to zoom/pan outside of those extents. 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
Note
MS_IMAGEMODE_* value.
string getOption(string property_name) Returns the associated value for the format option property passed as argument. Returns an empty string if property not found. int set(string property_name, new_value) Set object property to a new value. void setOption(string property_name, string new_value) Add or Modify the format option list. return true on success.
$oMap->outputformat->setOption("OUTPUT_TYPE", "RASTER");
int validate() Checks some internal consistency issues, Returns MS_SUCCESS or MS_FAILURE. Some problems are xed up internally. May produce debug output if issues encountered. OwsrequestObj
Constructor new OWSRequestObj()
256
Chapter 6. MapScript
Members
int addParameter(string name, string value) Add a request parameter, even if the parameter key was previousely set. This is useful when multiple parameters with the same key are required. For example :
$request->addparameter(SIZE, x(100)); $request->addparameter(SIZE, y(100));
string getName(int index) Return the name of the parameter at index in the requests array of parameter names. string getValue(int index) Return the value of the parameter at index in the requests array of parameter values. string getValueByName(string name) Return the value associated with the parameter name. 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);
pointObj
Constructor new pointObj()
Members
Name x y z m
Note
used for 3d shape les. set to 0 for other types used only for measured shape les - set to 0 for other types
double distanceToLine(pointObject p1, pointObject p2) Calculates distance between a point ad a lined dened by the two points passed in argument. double distanceToPoint(pointObj poPoint) Calculates distance between two points. double distanceToShape(shapeObj shape) Calculates the minimum distance between a point and a shape.
257
int draw(mapObj map, layerObj layer, imageObj img, int class_index, string text) Draws the individual point using layer. The class_index is used to classify the point based on the classes dened for the layer. The text string is used to annotate the point. Returns MS_SUCCESS/MS_FAILURE. int project(projectionObj in, projectionObj out) Project the point from in projection (1st argument) to out projection (2nd argument). Returns MS_SUCCESS/MS_FAILURE. int setXY(double x, double y [, double m]) Set X,Y coordinate values. Note: the 3rd parameter m is used for measured shape les only. It is not mandatory. int setXYZ(double x, double y , double z, [, double m]) Set X,Y,Z coordinate values. Note: the 4th parameter m is used for measured shape les only. It is not mandatory.
projectionObj
Constructor new projectionObj(string projectionString)
will create a geographic projection class. The following example will convert a lat/long point to an LCC projection:
$projInObj = ms_newprojectionobj("proj=latlong"); $projOutObj = ms_newprojectionobj("proj=lcc,ellps=GRS80,lat_0=49,". "lon_0=-95,lat_1=49,lat_2=77"); $poPoint = ms_newpointobj(); $poPoint->setXY(-92.0, 62.0); $poPoint->project($projInObj, $projOutObj);
Methods
int getUnits() Returns the units of a projection object. Returns -1 on error. querymapObj
Constructor
Instances of querymapObj are always are always embedded inside the mapObj.
258
Chapter 6. MapScript
Members
Note
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. int set(string property_name, new_value) Set object property to a new value. int updateFromString(string snippet) Update MS_SUCCESS/MS_FAILURE. rectObj
Constructor
queryMap
object
from
string
snippet.
Returns
rectObj are sometimes embedded inside other objects. New ones can also be created with:
new rectObj()
Note: the members (minx, miny, maxx ,maxy) are initialized to -1;
Members:
int draw(mapObj map, layerObj layer, imageObj img, int class_index, string text) Draws the individual rectangle using layer. The class_index is used to classify the rectangle based on the classes dened for the layer. The text string is used to annotate the rectangle. Returns MS_SUCCESS/MS_FAILURE. double t(int width, int height) Adjust extents of the rectangle to t the width/height specied. int project(projectionObj in, projectionObj out) Project the rectangle from in projection (1st argument) to out projection (2nd argument). Returns MS_SUCCESS/MS_FAILURE.
259
int set(string property_name, new_value) Set object property to a new value. void setextent(double minx, double miny, double maxx, double maxy) Set the rectangle extents. referenceMapObj
Constructor
Type ColorObj int rectObj string int string int int int ColorObj int int
Methods
Name color height extent image marker markername markersize maxboxsize minboxsize outlinecolor status width
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. int set(string property_name, new_value) Set object property to a new value. int updateFromString(string snippet) Update a referenceMap object from a string snippet. MS_SUCCESS/MS_FAILURE. resultObj
Constructor new resultObj(int shapeindex)
Returns
260
Chapter 6. MapScript
Members
None scalebarObj
Constructor
Type int colorObj colorObj int colorObj int labelObj colorObj int int int int int int
Methods
Name align backgroundcolor color height imagecolor intervals label outlinecolor position postlabelcache status style units width
Note
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. int set(string property_name, new_value) Set object property to a new value. int setImageColor(int red, int green, int blue) Sets the imagecolor propery (baclground) of the object. Returns MS_SUCCESS or MS_FAILURE on error. int updateFromString(string snippet) Update MS_SUCCESS/MS_FAILURE. a scalebar from a string snippet. Returns
261
shapeleObj
Constructor new shapeFileObj(string filename, int type)
Opens a shapele and returns a new object to deal with it. Filename should be passed with no extension. To create a new le (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 le for read-only access, and type=-2 to open an existing le for update (append).
Members
int addPoint(pointObj point) Appends a point to an open shapele. int addShape(shapeObj shape) Appends a shape to an open shapele. 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. Note: The shape le is closed (and changes committed) when the object is destroyed. You can explicitly close and save the changes by calling $shapele->free(); unset($shapele), which will also free the php object. rectObj getExtent(int i) Retrieve a shapes bounding box by index. shapeObj getPoint(int i) Retrieve point by index. shapeObj getShape(int i) Retrieve shape by index. shapeObj getTransformed(mapObj map, int i) Retrieve shape by index. shapeObj
Constructor new shapeObj(int type)
262
Chapter 6. MapScript
Type rectObj int int int int int string int array
Name bounds classindex index numlines numvalues tileindex text type values
Note 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
int add(lineObj line) Add a line (i.e. a part) to the shape. shapeobj boundary() Returns the boundary of the shape. Only available if php/mapscript is built with GEOS library. shapeobj buffer(width) Returns a new buffered shapeObj based on the supplied distance (given in the coordinates of the existing shapeObj). Only available if php/mapscript is built with GEOS library. int containsShape(shapeobj shape2) Returns true if shape2 passed as argument is entirely within the shape. Else return false. Only available if php/mapscript is built with GEOS library. shapeobj convexhull() Returns a shape object representing the convex hull of shape. Only available if php/mapscript is built with GEOS library. boolean contains(pointObj point) Returns MS_TRUE if the point is inside the shape, MS_FALSE otherwise. 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. 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. 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. int draw(mapObj map, layerObj layer, imageObj img) Draws the individual shape using layer. MS_SUCCESS/MS_FAILURE. Returns
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. 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.
263
double getArea() Returns the area of the shape (if applicable). 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. pointObj getLabelPoint() Returns a point object with coordinates suitable for labelling the shape. double getLength() Returns the length (or perimeter) of the shape. Only available if php/mapscript is built with GEOS library. pointObj getMeasureUsingPoint(pointObject point) Apply only on Measured shape les. Given an XY Location, nd the nearest point on the shape object. Return a point object of this point with the m value set. pointObj getPointUsingMeasure(double m) Apply only on Measured shape les. Given a measure m, retun the corresponding XY location on the shapeobject. string getValue(layerObj layer, string ledname) Returns the value for a given eld name. shapeobj intersection(shapeobj shape) Returns a shape object representing the intersection of the shape object with the one passed as parameter. Only available if php/mapscript is built with GEOS library. boolean intersects(shapeObj shape) Returns MS_TRUE if the two shapes intersect, MS_FALSE otherwise. LineObj line(int i) Returns a reference to line number i. 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 project(projectionObj in, projectionObj out) Project the shape from in projection (1st argument) to out projection (2nd argument). Returns MS_SUCCESS/MS_FAILURE. int set(string property_name, new_value) Set object property to a new value. int setBounds() Updates the bounds property of the shape. Must be called to calculate new bounding box after new parts have been added. shapeObj simplify(double tolerance) Given a tolerance, returns a simplied shape object or NULL on error. Only available if php/mapscript is built with GEOS library (>=3.0). 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. shapeObj topologySimplifyPreservingSimplify(double tolerance) Given a tolerance, returns a simplied shape object or NULL on error. Only available if php/mapscript is built with GEOS library (>=3.0). 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. string toWkt() Returns WKT representation of the shapes geometry. shapeobj union(shapeobj shape) Returns a shape object representing the union of the shape object with the one passed as parameter. 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. styleObj
Constructor
264
Chapter 6. MapScript
new styleObj(classObj class [, styleObj style]) // or new styleObj(labelObj label [, styleObj style])
or using the old constructor (do not support a labelObj at rst argument)
styleObj ms_newStyleObj(classObj class [, styleObj style])
The second argument style is optional. If given, the new style created will be a copy of the style passed as argument.
Members
Type double int colorObj colorObj double double double double double double int int int colorObj string double int string double
Methods
Name angle antialias backgroundcolor color maxsize maxvalue maxwidth minsize minvalue minwidth offsetx offsety opacity outlinecolor rangeitem size symbol symbolname width
Note
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. string getBinding(const stylebinding) Get the attribute binding for a specled 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
string getGeomTransform() int removeBinding(const stylebinding) Remove the attribute binding for a specled style property. Added in MapServer 5.0.
$oStyle->removebinding(MS_STYLE_BINDING_COLOR);
int set(string property_name, new_value) Set object property to a new value. int setBinding(const stylebinding, string value) Set the attribute binding for a specled style property. Added in MapServer 5.0. 6.3. PHP MapScript 265
$oStyle->setbinding(MS_STYLE_BINDING_COLOR, "FIELD_NAME_COLOR");
This would bind the color parameter with the data (ie will extract the value of the color from the eld called FIELD_NAME_COLOR int setGeomTransform(string value) int updateFromString(string snippet) Update MS_SUCCESS/MS_FAILURE. symbolObj
Constructor new symbolObj(mapObj map, string symbolname)
style
from
string
snippet.
Returns
Creates a new symbol with default values in the symbolist. Note: Using the new constructor, the symbol is automatically returned. The old constructor returns the id of the new symbol. If a symbol with the same name exists, it (or its id) will be returned. To get a symbol object using the old constructor, you need to use a method on the map object:
$nId = ms_newSymbolObj($map, "symbol-test"); $oSymbol = $map->getSymbolObjectById($nId);
Members
Type int string int string string int int int string int double double int int
Name antialias character lled font imagepath inmaple patternlength position name numpoints sizex sizey transparent transparentcolor
Note
read-only If set to TRUE, the symbol will be saved inside the maple. read-only
read-only
266
Chapter 6. MapScript
Methods
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. array getPatternArray() Returns an array containing the pattern. If there is no pattern, it returns an empty array. array getPointsArray() Returns an array containing the points of the symbol. Refer to setpoints to see how the array should be interpreted. If there are no points, it returns an empty array. int set(string property_name, new_value) Set object property to a new value. int setImagePath(char lename) Loads a pixmap symbol specied by the lename. The le should be of either Gif or Png format. int setPattern(array int) Set the pattern MS_SUCCESS/MS_FAILURE. of the symbol (used for dash patterns). Returns
int setPoints(array double) Set the points of the symbol. Note that the values passed is an array containing the x and y values of the points. Returns MS_SUCCESS/MS_FAILURE. Example:
$array[0] = 1 # x value of the first point $array[1] = 0 # y values of the first point $array[2] = 1 # x value of the 2nd point ....
Example of usage
267
webObj
Constructor
Instances of webObj are always are always embedded inside the mapObj.
Members
Type string string string rectObj string string string string string string double string hashTableObj double string string string string
Methods
Name browseformat empty error extent footer header imagepath imageurl legendformat log maxscaledenom maxtemplate metadata minscaledenom mintemplate queryformat template temppath
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. int set(string property_name, new_value) Set object property to a new value. int updateFromString(string snippet) Update MS_SUCCESS/MS_FAILURE. a web object from a string snippet. Returns
268
Chapter 6. MapScript
$map = new mapObj("mapfile.map"); $of = $map->outputformat; echo $map->extent->minx." - ".$map->extent->miny." - ".$map->extent->maxx. " - ".$map->extent->maxy."\n"; 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
$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); $map->free(); // break the circular references // at this place, the outputformat ($of) and the rect object ($map->extent) resources are freed unset($map); // the map object is immediately freed after the unset (before the end of the script)
6.4.1 Introduction
The Python MapScript module contains some class extension methods that have not yet been implemented for other languages.
6.4.2 Classes
References to sections below will be added here as the documentation grows. imageObj The Python Imaging Library, http://www.pythonware.com/products/pil/, is an indispensible tool for image manipulation. The extensions to imageObj are all geared towards better integration of PIL in MapScript applications.
269
imageObj Methods
imageObj( PyObject arg1, PyObject arg2 [, PyObject arg3 ] ) [imageObj] Create a new instance which is either empty or read from a Python le-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 le mode, arg1 should be a lename or a Python le or le-like object. If the le-like object does not have a seek attribute (such as a urllib resource handle), then a GD driver name must be provided as arg2. Heres an example of creating a 320 pixel wide by 240 pixel high JPEG using the constructors blank image mode:
image = mapscript.imageObj(320, 240, GD/JPEG)
write( [ PyObject le ] ) [void] Write image data to a Python le-like object. Default is stdout. pointObj
pointObj Methods
Note that the return value can be conveniently evald 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.
270
Chapter 6. MapScript