GeoServer User Manual 2.15.1

geoserver-2.15.1-user-manual

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 2061

DownloadGeoServer User Manual Geoserver-2.15.1-user-manual
Open PDF In BrowserView PDF
GeoServer User Manual
Release 2.15.1

GeoServer

April 29, 2019

Contents

1

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

3
3
3
4
6

Installation
2.1 Windows installer . . . . . .
2.2 Windows binary . . . . . . .
2.3 Mac OS X installer . . . . . .
2.4 Mac OS X binary . . . . . . .
2.5 Linux binary . . . . . . . . .
2.6 Web archive . . . . . . . . . .
2.7 Upgrading existing versions

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

9
9
15
17
19
21
22
23

3

Getting started
3.1 Using the web administration interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.2 Publishing a shapefile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.3 Publishing a PostGIS table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

25
25
28
33

4

Web administration interface
4.1 About & Status . . . . .
4.2 Data . . . . . . . . . . .
4.3 Services . . . . . . . . .
4.4 Settings . . . . . . . . .
4.5 Tile Caching . . . . . . .
4.6 Security . . . . . . . . .
4.7 Demos . . . . . . . . . .
4.8 Tools . . . . . . . . . . .
4.9 Extensions . . . . . . . .

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

41
41
42
42
42
43
43
43
43
44

Data management
5.1 Data settings . . . . .
5.2 Vector data . . . . . .
5.3 Raster data . . . . . .
5.4 Databases . . . . . . .
5.5 Cascaded service data

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

45
. 45
. 77
. 86
. 133
. 176

2

5

Introduction
1.1 Overview . . . .
1.2 History . . . . . .
1.3 Getting involved
1.4 License . . . . . .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.
.

.
.
.
.

.
.
.
.

i

5.6
6

Application schemas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

261
261
268
453
460
560
701
809

Services
7.1 Web Map Service (WMS) . . . . . .
7.2 Web Feature Service (WFS) . . . . .
7.3 Web Coverage Service (WCS) . . . .
7.4 Web Processing Service (WPS) . . .
7.5 Catalog Services for the Web (CSW)

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

1063
1063
1156
1178
1186
1216

Filtering
8.1 Supported filter languages
8.2 Filter Encoding Reference .
8.3 ECQL Reference . . . . . .
8.4 Filter functions . . . . . . .
8.5 Filter Function Reference .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

1227
1227
1228
1233
1238
1240

Server configuration
9.1 Status . . . . . . . . . . . . . . . . . . .
9.2 Contact Information . . . . . . . . . . .
9.3 Global Settings . . . . . . . . . . . . . .
9.4 Image Processing . . . . . . . . . . . . .
9.5 Raster Access . . . . . . . . . . . . . . .
9.6 REST Configuration . . . . . . . . . . .
9.7 Advanced log configuration . . . . . .
9.8 Coordinate Reference System Handling
9.9 Virtual Services . . . . . . . . . . . . . .
9.10 Demos . . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

1249
1249
1252
1254
1259
1261
1263
1263
1265
1275
1277

10 GeoServer data directory
10.1 Data directory default location . . . . . . . .
10.2 Setting the data directory location . . . . . .
10.3 Structure of the data directory . . . . . . . .
10.4 Migrating a data directory between versions
10.5 Parameterize catalog settings . . . . . . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

1285
1285
1286
1289
1292
1293

11 Running in a production environment
11.1 Java Considerations . . . . . . . . . . . . . . .
11.2 Container Considerations . . . . . . . . . . . .
11.3 Configuration Considerations . . . . . . . . .
11.4 Data Considerations . . . . . . . . . . . . . . .
11.5 Linux init scripts . . . . . . . . . . . . . . . . .
11.6 Other Considerations . . . . . . . . . . . . . .
11.7 Troubleshooting . . . . . . . . . . . . . . . . .
11.8 Make cluster nodes identifiable from the GUI

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

1295
1295
1299
1301
1304
1306
1306
1307
1313

7

8

9

Styling
6.1 Styles . . . . . . . . . . . . . . . . .
6.2 SLD Styling . . . . . . . . . . . . .
6.3 Generating SLD styles with QGIS
6.4 CSS Styling . . . . . . . . . . . . .
6.5 YSLD Styling . . . . . . . . . . . .
6.6 MBStyle Styling . . . . . . . . . . .
6.7 Styling Workshop . . . . . . . . .

12 REST

ii

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

1315

12.1 API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1315
12.2 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1317
13 Security
13.1 Security settings .
13.2 Role system . . . .
13.3 Authentication . .
13.4 Passwords . . . . .
13.5 Root account . . .
13.6 Service Security . .
13.7 Layer security . . .
13.8 REST Security . . .
13.9 Disabling security
13.10 Tutorials . . . . . .

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

1385
1385
1416
1429
1439
1442
1442
1445
1451
1453
1453

14 GeoWebCache
14.1 GeoWebCache settings . .
14.2 Using GeoWebCache . . .
14.3 Configuration . . . . . . .
14.4 Seeding and refreshing .
14.5 HTTP Response Headers
14.6 GeoWebCache REST API
14.7 Troubleshooting . . . . .

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

1493
1493
1511
1514
1519
1520
1523
1534

15 Extensions
15.1 Control flow module . . . . . . . . . . . . . . . . . . . . .
15.2 DXF OutputFormat for WFS and WPS PPIO . . . . . . .
15.3 Excel WFS Output Format . . . . . . . . . . . . . . . . . .
15.4 GRIB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
15.5 Imagemap . . . . . . . . . . . . . . . . . . . . . . . . . . .
15.6 Importer . . . . . . . . . . . . . . . . . . . . . . . . . . . .
15.7 INSPIRE . . . . . . . . . . . . . . . . . . . . . . . . . . . .
15.8 JP2K Plugin . . . . . . . . . . . . . . . . . . . . . . . . . .
15.9 libjpeg-turbo Map Encoder Extension . . . . . . . . . . .
15.10 Monitoring . . . . . . . . . . . . . . . . . . . . . . . . . .
15.11 NetCDF . . . . . . . . . . . . . . . . . . . . . . . . . . . .
15.12 NetCDF Output Format . . . . . . . . . . . . . . . . . . .
15.13 OGR based WFS Output Format . . . . . . . . . . . . . .
15.14 OGR based WPS Output Format . . . . . . . . . . . . . .
15.15 GeoServer Printing Module . . . . . . . . . . . . . . . . .
15.16 Cross-layer filtering . . . . . . . . . . . . . . . . . . . . .
15.17 Vector Tiles . . . . . . . . . . . . . . . . . . . . . . . . . .
15.18 XSLT WFS output format module . . . . . . . . . . . . .
15.19 Web Coverage Service 2.0 Earth Observation extensions
15.20 MongoDB Data Store . . . . . . . . . . . . . . . . . . . .
15.21 SLD REST Service . . . . . . . . . . . . . . . . . . . . . .
15.22 Geofence Plugin . . . . . . . . . . . . . . . . . . . . . . .
15.23 Geofence Internal Server . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

1539
1539
1543
1546
1547
1548
1549
1587
1592
1593
1595
1608
1616
1619
1622
1623
1649
1654
1660
1664
1674
1675
1685
1691

16 Community modules
16.1 Key authentication module . . . . . . . . . . . .
16.2 Authentication with OAuth2 . . . . . . . . . . .
16.3 Authentication with Keycloak . . . . . . . . . .
16.4 DDS/BIL(World Wind Data Formats) Extension
16.5 Scripting . . . . . . . . . . . . . . . . . . . . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

1705
1705
1714
1733
1737
1741

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

iii

16.6
16.7
16.8
16.9
16.10
16.11
16.12
16.13
16.14
16.15
16.16
16.17
16.18
16.19
16.20
16.21
16.22
16.23
16.24
16.25
16.26
16.27
16.28
16.29
16.30
16.31
16.32
16.33
16.34
16.35

SpatiaLite . . . . . . . . . . . . . . . . . . . . . . . . . . .
Dynamic colormap generation . . . . . . . . . . . . . . .
JDBCConfig . . . . . . . . . . . . . . . . . . . . . . . . . .
MBTiles Extension . . . . . . . . . . . . . . . . . . . . . .
GeoPackage Extension . . . . . . . . . . . . . . . . . . . .
PGRaster . . . . . . . . . . . . . . . . . . . . . . . . . . .
WPS download community module . . . . . . . . . . . .
JMS based Clustering . . . . . . . . . . . . . . . . . . . .
SOLR data store . . . . . . . . . . . . . . . . . . . . . . .
GeoMesa data store . . . . . . . . . . . . . . . . . . . . .
GWC Distributed Caching community module . . . . .
GDAL based WCS Output Format . . . . . . . . . . . . .
GWC S3 BlobStore plugin . . . . . . . . . . . . . . . . . .
GWC SQLite Plugin . . . . . . . . . . . . . . . . . . . . .
Parameters Extractor . . . . . . . . . . . . . . . . . . . . .
WPS Remote community module . . . . . . . . . . . . .
JDBCStore . . . . . . . . . . . . . . . . . . . . . . . . . . .
ncWMS WMS extensions support . . . . . . . . . . . . .
Backup and Restore Documentation . . . . . . . . . . . .
OneLogin Authentication Filter . . . . . . . . . . . . . .
WMTS Multidimensional . . . . . . . . . . . . . . . . . .
Notification community module Plugin Documentation
OpenSearch for EO . . . . . . . . . . . . . . . . . . . . . .
S3 Support for GeoTiff . . . . . . . . . . . . . . . . . . . .
Status Monitoring . . . . . . . . . . . . . . . . . . . . . .
NSG Profile . . . . . . . . . . . . . . . . . . . . . . . . . .
GHRSST NetCDF output . . . . . . . . . . . . . . . . . .
Monitoring Hibernate storage . . . . . . . . . . . . . . .
Geoserver Task Manager . . . . . . . . . . . . . . . . . .
Quality of Service and Experience Module (QoSE) . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

1762
1764
1768
1770
1772
1775
1777
1792
1806
1813
1814
1814
1818
1821
1825
1829
1876
1879
1885
1903
1905
1917
1921
1933
1934
1938
1940
1943
1946
1969

17 Tutorials
17.1 Freemarker Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . .
17.2 GeoRSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
17.3 GetFeatureInfo Templates . . . . . . . . . . . . . . . . . . . . . . . . . .
17.4 Paletted Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
17.5 Serving Static Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
17.6 WMS Reflector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
17.7 WMS Animator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
17.8 CQL and ECQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
17.9 Using the ImageMosaic plugin for raster time-series data . . . . . . . .
17.10 Using the ImageMosaic plugin for raster with time and elevation data
17.11 Using the ImageMosaic plugin with footprint mangement . . . . . . .
17.12 Building and using an image pyramid . . . . . . . . . . . . . . . . . . .
17.13 Storing a coverage in a JDBC database . . . . . . . . . . . . . . . . . . .
17.14 Using the GeoTools feature-pregeneralized module . . . . . . . . . . .
17.15 Setting up a JNDI connection pool with Tomcat . . . . . . . . . . . . .
17.16 geoserver on JBoss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

1975
1975
1977
1981
1986
1994
1994
1997
2001
2006
2018
2021
2030
2033
2040
2048
2053

Python Module Index

iv

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

2055

GeoServer User Manual, Release 2.15.1

GeoServer is an open source software server written in Java that allows users to share and edit geospatial data. Designed for interoperability, it publishes data from any major spatial data source using open
standards.
This User Manual is a comprehensive guide to all aspects of using GeoServer. Whether you are a novice or
a veteran user of this software, we hope that this documentation will be a helpful reference.
Introduction Learn about GeoServer.
Installation Install GeoServer for your platform.
Getting started Tutorials to help you get started with GeoServer.
Web administration interface Navigate the GeoServer graphical interface.
Data management Load and publish data from a variety of sources.
Styling Styling and visualization for published layers in GeoServer.
Services OGC services, the primary method of publishing data in GeoServer.
Filtering Filter your requests and responses to increase efficiency.
Server configuration Configuration options for GeoServer administrators.
GeoServer data directory Settings and configuration files for GeoServer.
Running in a production environment Best practices for using GeoServer.
REST Interact programmatically with GeoServer without using the graphical interface.
Security Secure and restrict access to data and services.
GeoWebCache Accelerate your GeoServer with tile caching.
Extensions Add extra functionality to GeoServer with extensions.
Community modules Add cutting-edge functionality to GeoServer with community modules.
Tutorials Other tips and tricks for getting the most out of your GeoServer instance.

Contents

1

GeoServer User Manual, Release 2.15.1

2

Contents

CHAPTER

1

Introduction

This section gives an overview of GeoServer the project, its background, and what it can do for you.
For those who wish to get started with GeoServer right away, feel free to skip to the Installation section.

1.1 Overview
GeoServer is an open source software server written in Java that allows users to share and edit geospatial data. Designed for interoperability, it publishes data from any major spatial data source using open
standards.
Being a community-driven project, GeoServer is developed, tested, and supported by a diverse group of
individuals and organizations from around the world.
GeoServer is the reference implementation of the Open Geospatial Consortium (OGC) Web Feature Service
(WFS) and Web Coverage Service (WCS) standards, as well as a high performance certified compliant Web
Map Service (WMS). GeoServer forms a core component of the Geospatial Web.

1.2 History
GeoServer was started in 2001 by The Open Planning Project (TOPP), a non-profit technology incubator
based in New York. TOPP was creating a suite of tools to enable open democracy and to help make government more transparent. The first of these was GeoServer, which came out of a recognition that a suite of
tools to enable citizen involvement in government and urban planning would be greatly enhanced by the
ability to share spatial data.
The GeoServer founders envisioned a Geospatial Web, analogous to the World Wide Web. With the World
Wide Web, one can search for and download text. With the Geospatial Web, one can search for and download spatial data. Data providers would be able to publish their data straight to this web, and users could
directly access it, as opposed to the now indirect and cumbersome methods of sharing data that exist today.

3

GeoServer User Manual, Release 2.15.1

Those involved with GeoServer founded the GeoTools project, an open source GIS Java toolkit. Through
GeoTools, support for shapefiles, Oracle databases, ArcSDE integration, and much more was added.
Around the same time as GeoServer was founded, The OpenGIS Consortium (now the Open Geospatial
Consortium) was working on the Web Feature Service standard. It specifies a protocol to make spatial data
directly available on the web, using GML (Geographic Markup Language), an interoperable data format. A
Web Map Service was also created, a protocol for creating and displaying map images created from spatial
data.
Other projects became interrelated. Refractions Research created PostGIS, a free and open spatial database,
which enabled GeoServer to connect to a free database. Also, MetaCarta originally created OpenLayers, an
open source browser-based map viewing utility. Together, these tools have all enhanced the functionality
of GeoServer.
GeoServer can now read data from over a dozen spatial data sources and output to many different formats.
Now in its second decade, GeoServer is continuing on its mission to make spatial data more accessible to
all.

1.3 Getting involved
GeoServer exists because of the efforts of people like you.
There are many ways that you can help out with the GeoServer project. GeoServer fully embraces an open
source development model that does not see a split between user and developer, producer and consumer,
but instead sees everyone as a valuable contributor.

1.3.1 Development
Helping to develop GeoServer is the obvious way to help out. Developers usually start with bug fixes and
other small patches, and then move into larger contributions as they learn the system. Our developers are
more than happy to help out as you learn and get acquainted. We try our hardest to keep our code clean
and well documented.
You can find the project on GitHub. As part of the GitHub model, anyone can submit patches as pull
requests, which will be evaluated by the team. To learn more about contributing to the GeoServer codebase,
we highly recommend joining the GeoServer developers mailing list. See details below.

1.3.2 Documentation
Another crucial way to help out is with documentation. Whether it’s adding tutorials or just correcting
mistakes, every contribution serves to make the project more healthy. And the best part is that you do not
need to be a developer in order to contribute.
Our official documentation is contained as part of our official code repository. As part of the GitHub model,
anyone can submit patches as pull requests, which will be evaluated by the team.
To learn more about contributing to the GeoServer codebase, we highly recommend joining the GeoServer
developers mailing list (see details below). For typos and other small changes, please see our Documentation Guide for how to make quick fixes.

1.3.3 Mailing lists
GeoServer maintains two email lists:

4

Chapter 1. Introduction

GeoServer User Manual, Release 2.15.1

• GeoServer Users
• GeoServer Developers
The Users list is mainly for those who have questions relating to the use of GeoServer, and the Developers
list is for more code-specific and roadmap-based discussions. If you see a question asked on these lists that
you know the answer to, please respond!
These lists are publicly available and are a great resource for those who are new to GeoServer, who need a
question answered, or who are interested in contributing code.

1.3.4 IRC
Users can join the IRC channel, #geoserver, on the Freenode network, in order to collaborate in real time.
GeoServer developers occasionally will be in this channel as well.

1.3.5 Bug tracking
If you have a problem when working with GeoServer, then please let us know through the mailing lists.
GeoServer uses JIRA , a bug tracking website, to manage issue reports. In order to submit an issue, you’ll
need to create an account first.
Everyone is encouraged to submit patches and, if possible, fix issues as well. We welcome patches through
JIRA, or pull requests to GitHub.
Responsible Disclosure
Warning: If you encounter a security vulnerability in GeoServer please take care to report the issue in
a responsible fashion:
• Keep exploit details out of issue report (send to developer/PSC privately – just like you would do
for sensitive sample data)
• Mark the issue as a vulnerability.
• Be prepared to work with Project Steering Committee (PSC) members on a solution
Keep in mind PSC members are volunteers and an extensive fix may require fundraising / resources
If you are not in position to communicate in public please consider commercial support, contacting a PSC
member, or reaching us via the Open Source Geospatial Foundation at info@osgeo.org.

1.3.6 Translation
We would like GeoServer available in as many languages as possible. The two areas of GeoServer to translate are the text that appears in the Web administration interface and this documentation. If you are interested
in helping with this task, please let us know via the mailing lists.

1.3.7 Suggest improvements
If you have suggestions as to how we can make GeoServer better, we would love to hear them. You can
contact us through the mailing lists or submit a feature request through JIRA.

1.3. Getting involved

5

GeoServer User Manual, Release 2.15.1

1.3.8 Spread the word
A further way to help out the GeoServer project is to spread the word. Word-of-mouth information sharing
is more powerful than any marketing, and the more people who use our software, the better it will become.

1.3.9 Fund improvements
A final way to help out is to push for GeoServer to be used in your own organization. A number of commercial organizations offer support for GeoServer, and any improvements made due to that funding will
benefit the entire GeoServer community.

1.4 License
For complete license details review LICENSE.txt.
GeoServer is free software and is licensed under the GNU General Public License:
GeoServer, open geospatial information server
Copyright (C) 2014-2016 Open Source Geospatial Foundation.
Copyright (C) 2001-2014 OpenPlans
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version (collectively, "GPL").
As an exception to the terms of the GPL, you may copy, modify,
propagate, and distribute a work formed by combining GeoServer with the
EMF, XSD and OSHI Libraries, or a work derivative of such a combination, even if
such copying, modification, propagation, or distribution would otherwise
violate the terms of the GPL. Nothing in this exception exempts you from
complying with the GPL in all respects for all of the code used other
than the EMF, XSD and OSHI Libraries. You may include this exception and its grant
of permissions when you distribute GeoServer. Inclusion of this notice
with such a distribution constitutes a grant of such permissions. If
you do not wish to grant these permissions, remove this paragraph from
your distribution. "GeoServer" means the GeoServer software licensed
under version 2 or any later version of the GPL, or a work based on such
software and licensed under the GPL. "EMF, XSD and OSHI Libraries" means
Eclipse Modeling Framework Project and XML Schema Definition software
distributed by the Eclipse Foundation and the OSHI library, all licensed
under the Eclipse Public License Version 1.0 ("EPL"), or a work based on
such software and licensed under the EPL.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335

USA

This product includes software developed by the Apache Software Foundation (http://www.apache.org/)
licensed under the Apache License Version 2.0 and Apache License Version 1.1.
6

Chapter 1. Introduction

GeoServer User Manual, Release 2.15.1

This product includes software developed by the Eclipse Software Foundation under the Eclipse
Public License.

1.4. License

7

GeoServer User Manual, Release 2.15.1

8

Chapter 1. Introduction

CHAPTER

2

Installation

There are many ways to install GeoServer on your system. This section will discuss the various installation
paths available.
If using Windows or OS X, we recommend using the installers.
Note: To run GeoServer as part of an existing servlet container such as Tomcat, please see the Web archive
section.

Warning: GeoServer requires a Java 8 environment (JRE) to be installed on your system. This must be
done prior to installation.

2.1 Windows installer
The Windows installer provides an easy way to set up GeoServer on your system, as it requires no configuration files to be edited or command line settings.
1. Make sure you have a Java Runtime Environment (JRE) installed on your system. GeoServer requires
a Java 8 environment. The Oracle JRE is preferred, but OpenJDK has been known to work adequately.
You can download JRE 8 from Oracle.
Note: Java 9 is not currently supported.

Note: For more information about Java and GeoServer, please see the section on Java Considerations.
2. Navigate to the GeoServer Download page.

9

GeoServer User Manual, Release 2.15.1

3. Select the version of GeoServer that you wish to download. If you’re not sure, select Stable.
4. Click the link for the Windows installer.

Fig. 2.1: Downloading the Windows installer
5. After downloading, double-click the file to launch.
6. At the Welcome screen, click Next.

Fig. 2.2: Welcome screen
7. Read the License and click I Agree.
8. Select the directory of the installation, then click Next.
9. Select the Start Menu directory name and location, then click Next.
10. Enter the path to a valid Java Runtime Environment (JRE). GeoServer requires a valid JRE in order
to run, so this step is required. The installer will inspect your system and attempt to automatically
populate this box with a JRE if it is found, but otherwise you will have to enter this path manually.
When finished, click Next.
Note: A typical path on Windows would be C:\Program Files\Java\jre8.

Note: Don’t include the \bin in the JRE path. So if java.exe is located at C:\Program Files
(x86)\Java\jre8\bin\java.exe, set the path to be C:\Program Files (x86)\Java\jre8.

10

Chapter 2. Installation

GeoServer User Manual, Release 2.15.1

Fig. 2.3: GeoServer license

Fig. 2.4: GeoServer install directory

2.1. Windows installer

11

GeoServer User Manual, Release 2.15.1

Fig. 2.5: Start menu location

Note: For more information about Java and GeoServer, please see the section on Java Considerations.

Fig. 2.6: Selecting a valid JRE
11. Enter the path to your GeoServer data directory or select the default. If this is your first time using
GeoServer, select the Default data directory. When finished, click Next.
12. Enter the username and password for administration of GeoServer. GeoServer’s Web administration
interface requires authentication for management, and what is entered here will become those administrator credentials. The defaults are admin / geoserver. It is recommended to change these from the
defaults. When finished, click Next.
13. Enter the port that GeoServer will respond on. This affects the location of the GeoServer Web administration interface, as well as the endpoints of the GeoServer services such as Web Map Service (WMS)
and Web Feature Service (WFS). The default port is 8080, though any valid and unused port will work.
When finished, click Next.
12

Chapter 2. Installation

GeoServer User Manual, Release 2.15.1

Fig. 2.7: Setting a GeoServer data directory

Fig. 2.8: Setting the username and password for GeoServer administration

2.1. Windows installer

13

GeoServer User Manual, Release 2.15.1

Fig. 2.9: Setting the GeoServer port
14. Select whether GeoServer should be run manually or installed as a service. When run manually,
GeoServer is run like a standard application under the current user. When installed as a service,
GeoServer is integrated into Windows Services, and thus is easier to administer. If running on a
server, or to manage GeoServer as a service, select Install as a service. Otherwise, select Run manually.
When finished, click Next.

Fig. 2.10: Installing GeoServer as a service
15. Review your selections and click the Back button if any changes need to be made. Otherwise, click
Install.
16. GeoServer will install on your system. When finished, click Finish to close the installer.
17. If you installed GeoServer as a service, it is already running. Otherwise, you can start GeoServer by
going to the Start Menu, and clicking Start GeoServer in the GeoServer folder.
18. Navigate to http://localhost:8080/geoserver (or wherever you installed GeoServer) to access the GeoServer Web administration interface.
14

Chapter 2. Installation

GeoServer User Manual, Release 2.15.1

Fig. 2.11: Verifying settings
If you see the GeoServer logo, then GeoServer is successfully installed.

Fig. 2.12: GeoServer installed and running successfully

2.1.1 Uninstallation
GeoServer can be uninstalled in two ways: by running the uninstall.exe file in the directory where
GeoServer was installed, or by standard Windows program removal.

2.2 Windows binary
Note: For the wizard-based installer on Windows, please see the section on the Windows installer. For
installing on Windows with an existing application server such as Tomcat, please see the Web archive section.

2.2. Windows binary

15

GeoServer User Manual, Release 2.15.1

An alternate way of installing GeoServer on Windows is to use the platform-independent binary. This
version is a GeoServer web application bundled inside Jetty, a lightweight and portable application server.
It has the advantages of working very similarly across all operating systems and is very simple to set up.

2.2.1 Installation
1. Make sure you have a Java Runtime Environment (JRE) installed on your system. GeoServer requires
a Java 8 environment. The Oracle JRE is preferred, but OpenJDK has been known to work adequately.
You can download JRE 8 from Oracle.
Note: Java 9 is not currently supported.

Note: For more information about Java and GeoServer, please see the section on Java Considerations.
2. Navigate to the GeoServer Download page.
3. Select the version of GeoServer that you wish to download. If you’re not sure, select Stable.
4. Select Platform Independent Binary on the download page.
5. Download the archive and unpack to the directory where you would like the program to be located.
Note: A suggested location would be C:\Program Files\GeoServer.

Setting environment variables
You will need to set the JAVA_HOME environment variable if it is not already set. This is the path to your
JRE such that %JAVA_HOME%\bin\java.exe exists.
1. Navigate to Control Panel → System → Advanced → Environment Variables.
2. Under System variables click New.
3. For Variable name enter JAVA_HOME. For Variable value enter the path to your JDK/JRE.
4. Click OK three times.
Note: You may also want to set the GEOSERVER_HOME variable, which is the directory where GeoServer
is installed, and the GEOSERVER_DATA_DIR variable, which is the location of the GeoServer data directory
(which by default is %GEOSERVER_HOME\data_dir). The latter is mandatory if you wish to use a data
directory other than the default location. The procedure for setting these variables is identical to setting the
JAVA_HOME variable.

2.2.2 Running
Note: This can be done either via Windows Explorer or the command line.
1. Navigate to the bin directory inside the location where GeoServer is installed.

16

Chapter 2. Installation

GeoServer User Manual, Release 2.15.1

2. Run startup.bat. A command-line window will appear and persist. This window contains diagnostic and troubleshooting information. This window must be left open, otherwise GeoServer will
shut down.
3. Navigate to http://localhost:8080/geoserver (or wherever you installed GeoServer) to access the GeoServer Web administration interface.
If you see the GeoServer logo, then GeoServer is successfully installed.

Fig. 2.13: GeoServer installed and running successfully

2.2.3 Stopping
To shut down GeoServer, either close the persistent command-line window, or run the shutdown.bat file
inside the bin directory.

2.2.4 Uninstallation
1. Stop GeoServer (if it is running).
2. Delete the directory where GeoServer is installed.

2.3 Mac OS X installer
The Mac OS X installer provides an easy way to set up GeoServer on your system, as it requires no configuration files to be edited or command line settings.
1. Make sure you have a Java Runtime Environment (JRE) installed on your system. GeoServer requires
a Java 8 environment, and the JRE supplied by OS X is not sufficient. For more information, please
see the instructions for installing Oracle Java on OS X.
Note: Java 9 is not currently supported.

2.3. Mac OS X installer

17

GeoServer User Manual, Release 2.15.1

Note: For more information about Java and GeoServer, please see the section on Java Considerations.
2. Navigate to the GeoServer Download page.
3. Select the version of GeoServer that you wish to download. If you’re not sure, select Stable.
4. Click the link for the Mac OS X installer to begin the download.
5. When downloaded, double click on the file to open it.
6. Drag the GeoServer icon to the Applications folder.

Fig. 2.14: Drag the GeoServer icon to Applications to install

7. Navigate to your Applications folder and double click the GeoServer icon.
8. In the resulting GeoServer console window, start GeoServer by going to Server → Start.

Fig. 2.15: Starting GeoServer

9. The console window will be populated with log entries showing the GeoServer loading process.
Once GeoServer is completely started, a browser window will open at http://localhost:8080/
geoserver, which is the Web administration interface for GeoServer.
Warning: If you encounter the following error during startup, you may have some
invalid JAI jars from the default Mac Java install:
java.lang.NoClassDefFoundError: Could not initialize class javax.media.
,→jai.JAI

18

Chapter 2. Installation

GeoServer User Manual, Release 2.15.1

To fix this error, locate your Java extensions folder (Usually /System/Library/Java/
Extensions and/or ~/Library/Java/Extensions), and delete the following jars:
jai_codec-1.1.3.jar
jai_core-1.1.3.jar
jai_imageio-1.1.jar

If you have upgraded your OS from an older version, you may not have permission to
delete these jars. In this case, you will first need to disable System Integrity Protection.

2.4 Mac OS X binary
Note: For the installer on OS X, please see the section on the Mac OS X installer. For installing on OS X
with an existing application server such as Tomcat, please see the Web archive section.
An alternate way of installing GeoServer on OS X is to use the platform-independent binary. This version
is a GeoServer web application bundled inside Jetty, a lightweight and portable application server. It has
the advantages of working very similarly across all operating systems and is very simple to set up.

2.4.1 Installation
1. Make sure you have a Java Runtime Environment (JRE) installed on your system. GeoServer requires
a Java 8 environment, and the JRE supplied by OS X is not sufficient. For more information, please
see the instructions for installing Oracle Java on OS X.
Note: Java 9 is not currently supported.

Note: For more information about Java and GeoServer, please see the section on Java Considerations.
2. Navigate to the GeoServer Download page.
3. Select the version of GeoServer that you wish to download. If you’re not sure, select Stable.
4. Select Platform Independent Binary on the download page.
5. Download the archive and unpack to the directory where you would like the program to be located.
Note: A suggested location would be /usr/local/geoserver.
6. Add an environment variable to save the location of GeoServer by typing the following command:
echo "export GEOSERVER_HOME=/usr/local/geoserver" >> ~/.profile
. ~/.profile

7. Make yourself the owner of the geoserver folder, by typing the following command:
sudo chown -R  /usr/local/geoserver/

2.4. Mac OS X binary

19

GeoServer User Manual, Release 2.15.1

where USER_NAME is your user name
8. Start GeoServer by changing into the directory geoserver/bin and executing the startup.sh
script:
cd geoserver/bin
sh startup.sh

Warning: If you encounter the following error during startup, you may have some
invalid JAI jars from the default Mac Java install:
java.lang.NoClassDefFoundError: Could not initialize class javax.media.
,→jai.JAI

To fix this error, locate your Java extensions folder (Usually /System/Library/Java/
Extensions and/or ~/Library/Java/Extensions), and delete the following jars:
jai_codec-1.1.3.jar
jai_core-1.1.3.jar
jai_imageio-1.1.jar

If you have upgraded your OS from an older version, you may not have permission to
delete these jars. In this case, you will first need to disable System Integrity Protection.
9. In a web browser, navigate to http://localhost:8080/geoserver.
If you see the GeoServer logo, then GeoServer is successfully installed.

Fig. 2.16: GeoServer installed and running successfully

To shut down GeoServer, either close the persistent command-line window, or run the shutdown.sh file
inside the bin directory.

2.4.2 Uninstallation
1. Stop GeoServer (if it is running).
2. Delete the directory where GeoServer is installed.

20

Chapter 2. Installation

GeoServer User Manual, Release 2.15.1

2.5 Linux binary
Note: For installing on Linux with an existing application server such as Tomcat, please see the Web archive
section.
The platform-independent binary is a GeoServer web application bundled inside Jetty, a lightweight and
portable application server. It has the advantages of working very similarly across all operating systems
and is very simple to set up.

2.5.1 Installation
1. Make sure you have a Java Runtime Environment (JRE) installed on your system. GeoServer requires
a Java 8 environment. The Oracle JRE is preferred, but OpenJDK has been known to work adequately.
You can download JRE 8 from Oracle.
Note: Java 9 is not currently supported.
2. Select the version of GeoServer that you wish to download. If you’re not sure, select Stable.
3. Select Platform Independent Binary on the download page.
4. Download the archive and unpack to the directory where you would like the program to be located.
Note: A suggested location would be /usr/share/geoserver.
5. Add an environment variable to save the location of GeoServer by typing the following command:
echo "export GEOSERVER_HOME=/usr/share/geoserver" >> ~/.profile
. ~/.profile

6. Make yourself the owner of the geoserver folder. Type the following command in the terminal
window, replacing USER_NAME with your own username :
sudo chown -R USER_NAME /usr/share/geoserver/

7. Start GeoServer by changing into the directory geoserver/bin and executing the startup.sh
script:
cd geoserver/bin
sh startup.sh

8. In a web browser, navigate to http://localhost:8080/geoserver.
If you see the GeoServer logo, then GeoServer is successfully installed.

To shut down GeoServer, either close the persistent command-line window, or run the shutdown.sh file
inside the bin directory.

2.5. Linux binary

21

GeoServer User Manual, Release 2.15.1

Fig. 2.17: GeoServer installed and running successfully

2.5.2 Uninstallation
1. Stop GeoServer (if it is running).
2. Delete the directory where GeoServer is installed.

2.6 Web archive
GeoServer is packaged as a standalone servlet for use with existing application servers such as Apache
Tomcat and Jetty.
Note: GeoServer has been mostly tested using Tomcat, and so is the recommended application server.
GeoServer requires a newer version of Tomcat (7.0.65 or later) that implements Servlet 3 and annotation
processing. Other application servers have been known to work, but are not guaranteed.

2.6.1 Installation
1. Make sure you have a Java Runtime Environment (JRE) installed on your system. GeoServer requires
a Java 8 environment. The Oracle JRE is preferred, but OpenJDK has been known to work adequately.
You can download JRE 8 from Oracle.
Note: Java 9 is not currently supported.

Note: For more information about Java and GeoServer, please see the section on Java Considerations.
2. Navigate to the GeoServer Download page.
3. Select Web Archive on the download page.
4. Download and unpack the archive.

22

Chapter 2. Installation

GeoServer User Manual, Release 2.15.1

5. Deploy the web archive as you would normally. Often, all that is necessary is to copy the geoserver.
war file to the application server’s webapps directory, and the application will be deployed.
Note: A restart of your application server may be necessary.

2.6.2 Running
Use your container application’s method of starting and stopping webapps to run GeoServer.
To access the Web administration interface, open a browser and navigate to http://SERVER/geoserver
. For example, with Tomcat running on port 8080 on localhost, the URL would be http://
localhost:8080/geoserver.

2.6.3 Uninstallation
1. Stop the container application.
2. Remove the GeoServer webapp from the container application’s webapps directory. This will usually
include the geoserver.war file as well as a geoserver directory.

2.7 Upgrading existing versions
Warning: Be aware that some upgrades are not reversible, meaning that the data directory may be
changed so that it is no longer compatible with older versions of GeoServer. See Migrating a data directory
between versions for more details.
The general GeoServer upgrade process is as follows:
1. Back up the current data directory. This can involve simply copying the directory to an additional
place.
2. Make sure that the current data directory is external to the application (not located inside the application file structure).
3. Uninstall the old version and install the new version.
Note: Alternately, you can install the new version directly over top of the old version.
4. Make sure that the new version continues to point to the same data directory used by the previous
version.

2.7.1 Notes on upgrading specific versions
GeoJSON encoding (GeoServer 2.6 and newer)
As of GeoServer 2.6, the GeoJSON produced by the WFS service no longer uses a nonstandard encoding for the CRS. To reenable this behavior for compatibility purposes, set

2.7. Upgrading existing versions

23

GeoServer User Manual, Release 2.15.1

GEOSERVER_GEOJSON_LEGACY_CRS=true as a system property, context parameter, or environment
variable.
JTS Type Bindings (GeoServer 2.14 and newer)
As of GeoServer 2.14, the output produced by REST featuretype and structured coverage requests using
a different package name (org.locationtech instead of com.vividsolutions) for geometry type
bindings, due to the upgrade to JTS (Java Topology Suite) 1.16.0. For example:
Before:
...

geom
0
1
true
com.vividsolutions.jts.geom.Point

...

After:
...

geom
0
1
true
org.locationtech.jts.geom.Point

...

Any REST clients which rely on this binding information should be updated to support the new names.

24

Chapter 2. Installation

CHAPTER

3

Getting started

This section contains short tutorials for common tasks in GeoServer to get new users using the system
quickly.

3.1 Using the web administration interface
GeoServer has a browser-based web administration interface application used to configure all aspects of
GeoServer, from adding and publishing data to changing service settings.
The web admin interface is accessed via a web browser at:
http://:/geoserver

For a default installation on a server the link is:
http://localhost:8080/geoserver

When the application starts, it displays the Welcome page.

Fig. 3.1: Welcome Page

25

GeoServer User Manual, Release 2.15.1

3.1.1 Logging In
In order to change any server settings or configure data, a user must first be authenticated.
1. Navigate to the upper right of the web interface to log into GeoServer. The default administration
credentials are:
• User name: admin
• Password: geoserver
Note: These can be changed in the Security section.

Fig. 3.2: Login
2. Once logged in, the Welcome screen changes to show the available admin functions. These are primarily shown in the menus on the left side of the page.

Fig. 3.3: Additional options when logged in

3.1.2 Layer Preview
The Layer Preview page allows you to quickly view the output of published layers.
1. Click the Layer Preview link on the menu to go to this page.
2. From here, you can find the layer you’d like to preview and click a link for an output format. Click
the OpenLayers link for a given layer and the view will display.
3. To sort a column alphabetically, click the column header.
26

Chapter 3. Getting started

GeoServer User Manual, Release 2.15.1

Fig. 3.4: Unsorted (left) and sorted (right) columns

3.1. Using the web administration interface

27

GeoServer User Manual, Release 2.15.1

4. Searching can be used to filter the number of items displayed. This is useful for working with data
types that contain a large number of items. To search data type items, enter the search string in the
search box and click Enter. GeoServer will search the data type for items that match your query, and
display a list view showing the search results.

Fig. 3.5: Search results for the query “top” on the Workspace page

Note: Sorting and searching apply to all data configuration pages.

Note: For more information, please see the Layer Preview section.

3.2 Publishing a shapefile
This tutorial walks through the steps of publishing a Shapefile with GeoServer.
Note: This tutorial assumes that GeoServer is running at http://localhost:8080/geoserver.

3.2.1 Data preparation
First let’s gather that the data that we’ll be publishing.
1. Download the file nyc_roads.zip. This archive contains a shapefile of roads from New York City
that will be used during in this tutorial.
2. Unzip the nyc_roads.zip into a new directory named nyc_roads. The archive contains the following four files:
nyc_roads.shp
nyc_roads.shx
nyc_roads.dbf
nyc_roads.prj

3. Move
the
nyc_roads
directory
into
/data,
where
 is the root of the GeoServer data directory. If no changes have been
made to the GeoServer file structure, the path is geoserver/data_dir/data/nyc_roads.

3.2.2 Creating a new workspace
The next step is to create a workspace for the shapefile. A workspace is a container used to group similar
layers together.

28

Chapter 3. Getting started

GeoServer User Manual, Release 2.15.1

Note: This step is optional if you’d like to use an existing workspace. Usually, a workspace is created for
each project, which can include stores and layers that are related to each other.
1. In a web browser, navigate to http://localhost:8080/geoserver.
2. Log into GeoServer as described in the Logging In section.
3. Navigate to Data → Workspaces.

Fig. 3.6: Workspaces page
4. Click the Add new workspace button.
5. You will be prompted to enter a workspace Name and Namespace URI.

Fig. 3.7: Configure a new workspace
6. Enter the Name as nyc and the Namespace URI as http://geoserver.org/nyc.
Note: A workspace name is a identifier describing your project. It must not exceed ten characters
or contain spaces. A Namespace URI (Uniform Resource Identifier) can usually be a URL associated
with your project with an added trailing identifier indicating the workspace. The Namespace URI
filed does not need to resolve to an actual valid web address.

3.2. Publishing a shapefile

29

GeoServer User Manual, Release 2.15.1

Fig. 3.8: nyc workspace
7. Click the Submit button. The nyc workspace will be added to the Workspaces list.

3.2.3 Create a store
Once the workspace is created, we are ready to add a new store. The store tells GeoServer how to connect
to the shapefile.
1. Navigate to Data→Stores.
2. You should see a list of stores, including the type of store and the workspace that the store belongs to.
3. In order to add the shapefile, you need to create a new store. Click the Add new Store button. You
will be redirected to a list of the data sources supported by GeoServer. Note that the data sources are
extensible, so your list may look slightly different.

Fig. 3.9: Stores
4. Click Shapefile. The New Vector Data Source page will display.
5. Begin by configuring the Basic Store Info.
• Select the workspace nyc from the drop down menu.
• Enter the Data Source Name as NYC Roads
• Enter a brief Description (such as “Roads in New York City”).
30

Chapter 3. Getting started

GeoServer User Manual, Release 2.15.1

6. Under Connection Parameters, browse to the location URL of the shapefile, typically nyc_roads/
nyc_roads.shp.

Fig. 3.10: Basic Store Info and Connection Parameters
7. Click Save. You will be redirected to the New Layer page in order to configure the nyc_roads layer.

3.2.4 Creating a layer
Now that the store is loaded, we can publish the layer.
1. On the New Layer page, click Publish beside the nyc_roads layer name.

Fig. 3.11: New layer
2. The Edit Layer page defines the data and publishing parameters for a layer. Enter a short Title and an
Abstract for the nyc_roads layer.
3. Generate the layer’s bounding boxes by clicking the Compute from data and then Compute from native
bounds links.
4. Click the Publishing tab at the top of the page.
5. We can set the layer’s style here. Under WMS Settings, ensure that the Default Style is set to line.
6. Finalize the layer configuration by scrolling to the bottom of the page and clicking Save.
3.2. Publishing a shapefile

31

GeoServer User Manual, Release 2.15.1

Fig. 3.12: Basic Resource Information

Fig. 3.13: Generating bounding boxes

Fig. 3.14: Select Default Style

32

Chapter 3. Getting started

GeoServer User Manual, Release 2.15.1

3.2.5 Previewing the layer
In order to verify that the nyc_roads layer is published correctly, we can preview the layer.
1. Navigate to the Layer Preview screen and find the nyc:nyc_roads layer.

Fig. 3.15: Layer Preview
2. Click the OpenLayers link in the Common Formats column.
3. An OpenLayers map will load in a new tab and display the shapefile data with the default line style.
You can use this preview map to zoom and pan around the dataset, as well as display the attributes
of features.

Fig. 3.16: Preview map of nyc_roads

3.3 Publishing a PostGIS table
This tutorial walks through the steps of publishing a PostGIS table with GeoServer.

3.3. Publishing a PostGIS table

33

GeoServer User Manual, Release 2.15.1

Note:
This tutorial assumes that PostgreSQL/PostGIS has been previously installed on the system and responding on localhost on port 5432, and also that GeoServer is running at http://
localhost:8080/geoserver.

3.3.1 Data preparation
First let’s gather that the data that we’ll be publishing.
1. Download the file nyc_buildings.zip. It contains a PostGIS dump of a dataset of buildings from
New York City.
2. Create a PostGIS database called nyc. This can be done with the following commands:
createdb nyc
psql -d nyc -c 'CREATE EXTENSION postgis'

Note: You may need to supply a user name and password with these commands.
3. Extract nyc_buildings.sql from nyc_buildings.zip.
4. Import nyc_buildings.sql into the nyc database:
psql -f nyc_buildings.sql nyc

3.3.2 Creating a new workspace
The next step is to create a workspace for the data. A workspace is a container used to group similar layers
together.
Note: This step is optional if you’d like to use an existing workspace. Usually, a workspace is created for
each project, which can include stores and layers that are related to each other.
1. In a web browser, navigate to http://localhost:8080/geoserver.
2. Log into GeoServer as described in the Logging In section.
3. Navigate to Data → Workspaces.
4. Click the Add new workspace button.
5. You will be prompted to enter a workspace Name and Namespace URI.
6. Enter the Name as nyc and the Namespace URI as http://geoserver.org/nyc.
Note: A workspace name is a identifier describing your project. It must not exceed ten characters
or contain spaces. A Namespace URI (Uniform Resource Identifier) can usually be a URL associated
with your project with an added trailing identifier indicating the workspace. The Namespace URI
filed does not need to resolve to an actual valid web address.
7. Click the Submit button. The nyc workspace will be added to the Workspaces list.

34

Chapter 3. Getting started

GeoServer User Manual, Release 2.15.1

Fig. 3.17: Workspaces page

Fig. 3.18: Configure a new workspace

3.3. Publishing a PostGIS table

35

GeoServer User Manual, Release 2.15.1

3.3.3 Creating a store
Once the workspace is created, we are ready to add a new store. The store tells GeoServer how to connect
to the shapefile.
1. Navigate to Data→Stores.
2. You should see a list of stores, including the type of store and the workspace that the store belongs to.

Fig. 3.19: Adding a new data source
3. Create a new store by clicking the PostGIS link.
4. Enter the Basic Store Info:
• Select the nyc Workspace
• Enter the Data Source Name as nyc_buildings
• Add a brief Description

Fig. 3.20: Basic Store Info
5. Specify the PostGIS database Connection Parameters:

36

Chapter 3. Getting started

GeoServer User Manual, Release 2.15.1

Option
dbtype
host
port
database
schema
user
passwd
validate connections

Value
postgis
localhost
5432
nyc
public
postgres
(Password for the postgres user)
(Checked)

Note: Leave all other fields at their default values.

Fig. 3.21: Connection Parameters
6. Click Save.

3.3.4 Creating a layer
Now that the store is loaded, we can publish the layer.
1. Navigate to Data → Layers.
2. Click Add a new resource.
3. From the New Layer chooser menu, select nyc:nyc_buidings.
4. On the resulting layer row, select the layer name nyc_buildings.
5. The Edit Layer page defines the data and publishing parameters for a layer. Enter a short Title and an
Abstract for the nyc_buildings layer.
3.3. Publishing a PostGIS table

37

GeoServer User Manual, Release 2.15.1

Fig. 3.22: Store selection

Fig. 3.23: New layer selection

Fig. 3.24: Basic Resource Info

38

Chapter 3. Getting started

GeoServer User Manual, Release 2.15.1

6. Generate the layer’s bounding boxes by clicking the Compute from data and then Compute from native
bounds links.

Fig. 3.25: Generating bounding boxes
7. Click the Publishing tab at the top of the page.
8. We can set the layer’s style here. Under WMS Settings, ensure that the Default Style is set to polygon.

Fig. 3.26: Select Default Style
9. Finalize the layer configuration by scrolling to the bottom of the page and clicking Save.

3.3.5 Previewing the layer
In order to verify that the nyc_buildings layer is published correctly, we can preview the layer.
1. Navigate to the Layer Preview screen and find the nyc:nyc_buildings layer.
2. Click the OpenLayers link in the Common Formats column.
3. An OpenLayers map will load in a new tab and display the shapefile data with the default line style.
You can use this preview map to zoom and pan around the dataset, as well as display the attributes
of features.

3.3. Publishing a PostGIS table

39

GeoServer User Manual, Release 2.15.1

Fig. 3.27: Preview map of nyc_buildings

40

Chapter 3. Getting started

CHAPTER

4

Web administration interface

The Web administration interface is a web-based tool for configuring all aspects of GeoServer, from adding
data to changing service settings. In a default GeoServer installation, this interface is accessed via a web
browser at http://localhost:8080/geoserver/web. However, this URL may vary depending on
your local installation.

Fig. 4.1: Web admin interface
The following sections detail the menu options available in GeoServer. Unless otherwise specified, you
will need to be logged in with administrative credentials to see these options.

4.1 About & Status
The About & Status section provides access to GeoServer diagnostic and configuration tools, and can be
particularly useful for debugging.
• The Status page shows a summary of server configuration parameters and run-time status.
• The GeoServer Logs page shows the GeoServer log output. This is useful for determining errors without having to leave the browser.

41

GeoServer User Manual, Release 2.15.1

• The Contact Information page sets the public contact information available in the Capabilities document of the WMS server.
• The About GeoServer section provides links to the GeoServer documentation, homepage and bug
tracker. You do not need to be logged into GeoServer to access this page.

4.2 Data
The Data management section contains configuration options for all the different data-related settings.
• The Layer Preview page provides links to layer previews in various output formats, including the common OpenLayers and KML formats. This page helps to visually verify and explore the configuration
of a particular layer. You do not need to be logged into GeoServer to access the Layer Preview.
• The Workspaces page displays a list of workspaces, with the ability to add, edit, and delete. Also shows
which workspace is the default for the server.
• The Stores page displays a list of stores, with the ability to add, edit, and delete. Details include the
workspace associated with the store, the type of store (data format), and whether the store is enabled.
• The Layers page displays a list of layers, with the ability to add, edit, and delete. Details include the
workspace and store associated with the layer, whether the layer is enabled, and the spatial reference
system (SRS) of the layer.
• The Layer Groups page displays a list of layer groups, with the ability to add, edit, and delete. Details
include the associated workspace (if any).
• The Styles page displays a list of styles, with the ability to add, edit, and delete. Details include the
associated workspace (if any).
In each of these pages that contain a table, there are three different ways to locate an object: sorting, searching, and paging. To alphabetically sort a data type, click on the column header. For simple searching, enter
the search criteria in the search box and hit Enter. And to page through the entries (25 at a time), use the
arrow buttons located on the bottom and top of the table.

4.3 Services
The Services section is for configuring the services published by GeoServer.
• The Web Coverage Service (WCS) page manages metadata, resource limits, and SRS availability for
WCS.
• The Web Feature Service (WFS) page manages metadata, feature publishing, service level options, and
data-specific output for WFS.
• The Web Map Service (WMS) page manages metadata, resource limits, SRS availability, and other dataspecific output for WMS.

4.4 Settings
The Settings section contains configuration settings that apply to the entire server.
• The Global Settings page configures messaging, logging, character and proxy settings for the entire
server.

42

Chapter 4. Web administration interface

GeoServer User Manual, Release 2.15.1

• The Image Processing page configures several JAI parameters, used by both WMS and WCS operations.
• The Coverage Access page configures settings related to loading and publishing coverages.

4.5 Tile Caching
The Tile Caching section configures the embedded GeoWebCache.
• The Tile Layers page shows which layers in GeoServer are also available as tiled (cached)layers, with
the ability to add, edit, and delete.
• The Caching Defaults page sets the global options for the caching service.
• The Gridsets page shows all available gridsets for the tile caches, with the ability to add, edit, and
delete.
• The Disk Quota page sets the options for tile cache management on disk, including strategies to reduce
file size when necessary.
• The BlobStores pages manages the different blobstores (tile cache sources) known to the embedded
GeoWebCache.

4.6 Security
The Security section configures the built-in security subsystem.
• The Settings page manages high-level options for the security subsystem.
• The Authentication page manages authentication filters, filter chains, and providers.
• The Passwords page manages the password policies for users and the master (root) account.
• The Users, Groups, Roles page manages the users, groups, and roles, and how they are all associated
with each other. Passwords for user accounts can be changed here.
• The Data page manages the data-level security options, allowing workspaces and layers to be restricted by role.
• The Services page manages the service-level security options, allowing services and operations to be
restricted by role.

4.7 Demos
The Demos section contains links to example WMS, WCS, and WFS requests for GeoServer as well as a listing all SRS info known to GeoServer. In addition, there is a reprojection console for converting coordinates
between spatial reference systems, and a request builder for WCS requests. You do not need to be logged
into GeoServer to access these pages.

4.8 Tools
The Tools section contains administrative tools. By default, the only tool is the Catalog Bulk Load Tool, which
can bulk copy test data into the catalog.

4.5. Tile Caching

43

GeoServer User Manual, Release 2.15.1

4.9 Extensions
GeoServer extensions can add functionality and extra options to the web interface. Details can be found in
the section for each extension.

44

Chapter 4. Web administration interface

CHAPTER

5

Data management

GeoServer connects to and publishes data from a wide variety of sources. This section will discuss how to
use the GeoServer web interface to accomplish most common tasks, along with the different data formats
served by GeoServer.
Note: There are many more data sources available through Extensions and Community modules. If you are
looking for a specific data format and not finding it here, please check those sections.

5.1 Data settings
This section describes how to manage load, manage, and publish data in the GeoServer web interface.
It describes the core configuration data types that GeoServer uses to access and publish geospatial information. Each subsection describes the data type pages which provide add, view, edit, and delete capabilities.

5.1.1 Layer Preview
This page provides layer views in various output formats. A layer must be enabled to be previewed.
Each layer row consists of a type, name, title, and available formats for viewing.
Field Description
Raster (grid)
Polygon
Line
Point
Other Geometry
Layer Group
Cascading WMS
Unknown/Other
45

GeoServer User Manual, Release 2.15.1

Fig. 5.1: Layer Preview Page
Name refers to the Workspace and Layer Name of a layer, while Title refers to the brief description configured in the Edit Layer: Data panel. In the following example, nurc refers to the Workspace, Arc_Sample
refers to the Layer Name and “A sample ArcGrid field” is specified on the Edit Later Data panel.

Fig. 5.2: Single Layer preview row

Output Formats
The Layer Preview page supports a variety of output formats for further use or data sharing. You can
preview all three layer types in the common OpenLayers and KML formats. Similarly, using the “All
formats” menu you can preview all layer types in seven additional output formats—AtomPub, GIF, GeoRss,
JPEG, KML (compressed), PDF, PNG, SVG, and TIFF. Only Vector layers provide the WFS output previews,
including the common GML as well as the CSV, GML3, GeoJSON and shapefile formats. The table below
provides a brief description of all supported output formats, organized by output type (image, text, or
data).
Image Outputs
All image outputs can be initiated from a WMS getMap request on either a raster, vector or coverage data.
WMS are methods that allows visual display of spatial data without necessarily providing access to the
features that comprise those data.

46

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Format
KML

Description
KML (Keyhole Markup Language) is an XML-based language schema for expressing geographic data in an Earth browser, such as Google Earth or Google Maps. KML uses a tagbased structure with nested elements and attributes. For GeoServer, KML files are distributed
as a KMZ, which is a zipped KML file.
JPEG
WMS output in raster format. The JPEG is a compressed graphic file format, with some loss
of quality due to compression. It is best used for photos and not recommended for exact
reproduction of data.
GIF
WMS output in raster format. The GIF (Graphics Interchange Format) is a bitmap image
format best suited for sharp-edged line art with a limited number of colors. This takes advantage of the format’s lossless compression, which favors flat areas of uniform color with well
defined edges (in contrast to JPEG, which favors smooth gradients and softer images). GIF is
limited to an 8-bit palette, or 256 colors.
SVG
WMS output in vector format. SVG (Scalable Vector Graphics) is a language for modeling
two-dimensional graphics in XML. It differs from the GIF and JPEG in that it uses graphic
objects rather than individual points.
TIFF
WMS output in raster format. TIFF (Tagged Image File Format) is a flexible, adaptable format
for handling multiple data in a single file. GeoTIFF contains geographic data embedded as
tags within the TIFF file.
PNG
WMS output in raster format. The PNG (Portable Network Graphics) file format was created
as the free, open-source successor to the GIF. The PNG file format supports truecolor (16
million colors) while the GIF supports only 256 colors. The PNG file excels when the image
has large, uniformly coloured areas.
OpenLayers
WMS GetMap request outputs a simple OpenLayers preview window. OpenLayers is an open
source JavaScript library for displaying map data in web browsers. The OpenLayers output
has some advanced filters that are not available when using a standalone version of OpenLayers. Further, the generated preview contains a header with easy configuration options for
display. Version 3 of the OpenLayers library is used by default. Version 3 can be disabled
with the ENABLE_OL3 (true/false) format option or system property. For older browsers not
supported by OpenLayers 3, version 2 is used regardless of the setting.
PDF
A PDF (Portable Document Format) encapsulates a complete description of a fixed-layout 2D
document,including any text, fonts, raster images, and 2D vector graphics.

Fig. 5.3: Sample Image Output-an OpenLayers preview of nurc:Pk50095

5.1. Data settings

47

GeoServer User Manual, Release 2.15.1

Text Outputs

Format
Description
AtomPub WMS output of spatial data in XML format. The AtomPub (Atom Publishing Protocol) is an
application-level protocol for publishing and editing Web Resources using HTTP and XML.
Developed as a replacement for the RSS family of standards for content syndication, Atom
allows subscription of geo data.
GeoRss WMS GetMap request output of vector data in XML format. RSS (Rich Site Summary) is an
XML format for delivering regularly changing web content. GeoRss is a standard for encoding
location as part of a RSS feed.supports Layers Preview produces a RSS 2.0 documents, with
GeoRSS Simple geometries using Atom.
GeoJSON JavaScript Object Notation (JSON) is a lightweight data-interchange format based on the
JavaScript programming language. This makes it an ideal interchange format for browser
based applications since it can be parsed directly and easily in to javascript. GeoJSON is a
plain text output format that add geographic types to JSON.
CSV
WFS GetFeature output in comma-delimited text. CSV (Comma Separated Values) files
are text files containing rows of data. Data values in each row are separated by commas.
CSV files also contain a comma-separated header row explaining each row’s value ordering.
GeoServer’s CSVs are fully streaming, with no limitation on the amount of data that can be
outputted.
A fragment of a simple GeoRSS for nurc:Pk50095 using Atom:



Pk50095
Feed auto-generated by GeoServer
>

fid--f04ca6b_1226f8d829e_-7ff4
46.722110379286 13.00635746384126
46.72697223230676 13.308182612644663 46.91359611878293
13.302316867622581 46.90870264238999 12.999446822650462
46.722110379286 13.00635746384126





Data Outputs
All data outputs are initiated from a WFS GetFeature request on vector data.

48

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Format
Description
GML2/3 GML (Geography Markup Language) is the XML grammar defined by the Open Geospatial
Consortium (OGC) to express geographical features. GML serves as a modeling language for
geographic systems as well as an open interchange format for geographic data sharing. GML2
is the default (Common) output format, while GML3 is available from the “All Formats”
menu.
Shapefile The ESRI Shapefile, or simply a shapefile, is the most commonly used format for exchanging
GIS data. GeoServer outputs shapefiles in zip format, with a directory of .cst, .dbf, .prg, .shp,
and .shx files.

5.1.2 Workspaces
This section describes how to view and configure workspaces. Analogous to a namespace, a workspace is a
container which organizes other items. In GeoServer, a workspace is often used to group similar layers together. Layers may be referred to by their workspace name, colon, layer name (for example topp:states).
Two different layers can have the same name as long as they belong to different workspaces (for example
sf:states and topp:states).

Fig. 5.4: Workspaces page

Edit a Workspace
To view or edit a workspace, click the workspace name. A workspace configuration page will be displayed.
A workspace is defined by a name and a Namespace URI (Uniform Resource Identifier). The workspace
name is limited to ten characters and may not contain space. A URI is similar to a URL, except URIs do not
need to point to a actual location on the web, and only need to be a unique identifier. For a Workspace URI,
we recommend using a URL associated with your project, with perhaps a different trailing identifier. For
example, http://www.openplans.org/topp is the URI for the “topp” workspace.

5.1. Data settings

49

GeoServer User Manual, Release 2.15.1

Fig. 5.5: Workspace named “topp”
Root Directory for REST PathMapper

Fig. 5.6: Workspace Root Directory parameter
This parameter is used by the RESTful API as the Root Directory for uploaded files, following the structure:
${rootDirectory}/workspace/store[/]

Note: This parameter is visible only when the Enabled parameter of the Settings section is checked.

Add a Workspace
The buttons for adding and removing a workspace can be found at the top of the Workspaces view page.

Fig. 5.7: Buttons to add and remove
To add a workspace, select the Add new workspace button. You will be prompted to enter the the workspace
name and URI.
Remove a Workspace
To remove a workspace, select it by clicking the checkbox next to the workspace. Multiple workspaces
can be selected, or all can be selected by clicking the checkbox in the header. Click the Remove selected
workspaces(s) button. You will be asked to confirm or cancel the removal. Clicking OK removes the selected
workspace(s).

50

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.8: New Workspace page with example

Fig. 5.9: Workspace removal confirmation

5.1. Data settings

51

GeoServer User Manual, Release 2.15.1

Isolated Workspaces
Isolated workspaces content is only visible and queryable in the context of a virtual service bound to the
isolated workspace. This means that isolated workspaces content will not show up in global capabilities
documents and global services cannot query isolated workspaces contents. Is worth mentioning that those
restrictions don’t apply to the REST API.
A workspace can be made isolated by checking the Isolated Workspace checkbox when creating or editing a
workspace.

Fig. 5.10: Making a workspace isolated
An isolated workspace will be able to reuse a namespace already used by another workspace, but its resources (layers, styles, etc . . . ) can only be retrieved when using that workspace virtual services and will
only show up in those virtual services capabilities documents.
It is only possible to create two or more workspaces with the same namespace in GeoServer if only one
of them is non isolated, i.e. isolated workspaces have no restrictions in namespaces usage but two non
isolated workspaces can’t use the same namespace.
The following situation will be valid:
• Prefix: st1 Namespace: http://www.stations.org/1.0 Isolated: false
• Prefix: st2 Namespace: http://www.stations.org/1.0 Isolated: true
• Prefix: st3 Namespace: http://www.stations.org/1.0 Isolated: true
But not the following one:
• Prefix: st1 Namespace: http://www.stations.org/1.0 Isolated: false
• Prefix: st2 Namespace: http://www.stations.org/1.0 Isolated: false
• Prefix: st3 Namespace: http://www.stations.org/1.0 Isolated: true
At most only one non isolated workspace can use a certain namespace.
Consider the following image which shows to workspaces (st1 and st2) that use the same namespace (http:
//www.stations.org/1.0) and several layers contained by them:

Fig. 5.11: Two workspaces using the same namespace, one of them is isolated.
In the example above st2 is the isolated workspace. Consider the following WFS GetFeature requests:
52

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

1. http://localhost:8080/geoserver/ows?service=WFS&version=2.0.0&request=
DescribeFeatureType&typeName=layer2
2. http://localhost:8080/geoserver/st2/ows?service=WFS&version=2.0.0&request=
DescribeFeatureType&typeName=layer2
3. http://localhost:8080/geoserver/ows?service=WFS&version=2.0.0&request=
DescribeFeatureType&typeName=st1:layer2
4. http://localhost:8080/geoserver/st2/ows?service=WFS&version=2.0.0&request=
DescribeFeatureType&typeName=st2:layer2
5. http://localhost:8080/geoserver/ows?service=WFS&version=2.0.0&request=
DescribeFeatureType&typeName=st2:layer2
6. http://localhost:8080/geoserver/ows?service=WFS&version=2.0.0&request=
DescribeFeatureType&typeName=layer5
The first request is targeting WFS global service and requesting layer2, this request will use layer2 contained
by workspace st1. The second request is targeting st2 workspace WFS virtual service, layer2 belonging to
workspace st2 will be used. Request three and four will use layer2 belonging to workspace, respectively,
st1 and st2. The last two requests will fail saying that the feature type was not found, isolated workspaces
content is not visible globally.
The rule of thumb is that resources (layers, styles, etc . . . ) belonging to an isolated workspace can only
be retrieved when using that workspaces virtual services and will only show up in those virtual services
capabilities documents.

5.1.3 Stores
A store connects to a data source that contains raster or vector data. A data source can be a file or group
of files, a table in a database, a single raster file, or a directory (for example, a Vector Product Format
library). The store construct allows connection parameters to be defined once, rather than for each dataset
in a source. As such, it is necessary to register a store before configuring datasets within it.

Fig. 5.12: Stores View

5.1. Data settings

53

GeoServer User Manual, Release 2.15.1

Store types
While there are many potential formats for data sources, there are only four kinds of stores. For raster data,
a store can be a file. For vector data, a store can be a file, database, or server.
Type Icon

Description
raster data in a file
vector data in a file
vector data in a database
vector server (web feature server)

Edit a Store
To view or edit a store, click the store name. A store configuration page will be displayed. The exact
contents of this page depend on the specific format of the store. See the sections Vector data, Raster data,
and Databases for information about specific data formats. The example shows the configuration for the
nurc:ArcGridSample store.

Fig. 5.13: Editing a raster data store

Basic Store Info
The basic information is common for all formats.
• Workspace - the store is assigned to the selected workspace
• Data Source Name - the store name as listed on the view page
• Description - (optional) a description that displays in the administration interface
• Enabled - enables or disables access to the store, along with all datasets defined for it
Connection Parameters
The connection parameters vary depending on data format.
54

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Add a Store
The buttons for adding and removing a store can be found at the top of the Stores page.

Fig. 5.14: Buttons to add and remove a Store
To add a store, select the Add new Store button. You will be prompted to choose a data source. GeoServer
natively supports many formats (with more available via extensions). Click the appropriate data source to
continue.

Fig. 5.15: Choosing the data source for a new store
The next page configures the store. Since connection parameters differ across data sources, the exact contents of this page depend on the store’s specific format. See the sections Vector data, Raster data, and Databases
for information on specific data formats. The example below shows the ArcGrid raster configuration page.

Remove a Store
To remove a store, click the checkbox next to the store. Multiple stores can be selected, or all can be selected
by clicking the checkbox in the header.
Click the Remove selected Stores button. You will be asked to confirm the removal of the configuration for
the store(s) and all resources defined under them. Clicking OK removes the selected store(s), and returns to
the Stores page.

5.1.4 Layers
In GeoServer, the term “layer” refers to a raster or vector dataset that represents a collection of geographic
features. Vector layers are analogous to “featureTypes” and raster layers are analogous to “coverages”. All
layers have a source of data, known as a Store. The layer is associated with the Workspace in which the
Store is defined.
5.1. Data settings

55

GeoServer User Manual, Release 2.15.1

Fig. 5.16: Configuration page for an ArcGrid raster data source

Fig. 5.17: Stores selected for removal

56

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.18: Confirm removal of stores
In the Layers section of the web interface, you can view and edit existing layers, add (register) a new
layer, or remove (unregister) a layer. The Layers View page displays the list of layers, and the Store and
Workspace in which each layer is contained. The View page also displays the layer’s status and native SRS.

Layer types
Layers can be divided into two types of data: raster and vector. These two formats differ in how they store
spatial information. Vector types store information about feature types as mathematical paths—a point as
a single x,y coordinate, lines as a series of x,y coordinates, and polygons as a series of x,y coordinates that
start and end on the same place. Raster format data is a cell-based representation of features on the earth
surface. Each cell has a distinct value, and all cells with the same value represent a specific feature.
Field Description
Raster (grid)
Polygon
Line
Point

Add a Layer
At the upper left-hand corner of the layers view page there are two buttons for the adding and removal of
layers. The green plus button allows you to add a new layer. The red minus button allows you to remove
selected layers.
Clicking the Add a new layer button brings up a New Layer Chooser panel. The menu displays all currently
enabled stores. From this menu, select the Store where the layer should be added.
Upon selection of a Store, a list is displayed of resources within the store. Resources which have already
been published as layers are listed first, followed by other resources which are available to be published. In
this example, giant_polygon, poi, poly_landmarks and tiger_roads are all existing layers within
the NYC store.

5.1. Data settings

57

GeoServer User Manual, Release 2.15.1

Fig. 5.19: Layers View

Fig. 5.20: Buttons to Add and Remove a Layer

Fig. 5.21: List of all currently enabled stores

58

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.22: List of published and available resources in a store
To add a layer for an available resource click Publish. To add a new layer for a published resource click
Publish Again. (Note that when re-publishing the name of the new layer may have to be modified to avoid
conflict with an existing layer.) The actions display an Edit Layer page to enter the definition of the new
layer.
Remove a Layer
To remove a layer, select it by clicking the checkbox next to the layer. As shown below, multiple layers can
be selected for batch removal. Note that selections for removal will not persist from one results pages to the
next.
All layers can be selected for removal by clicking the checkbox in the header.
Once layer(s) are selected, the Remove selected resources link is activated. Once you’ve clicked the link, you
will be asked to confirm or cancel the removal. Selecting OK removes the selected layer(s).
Edit Layer: Data
To view or edit a layer, click the layer name. A layer configuration page will be displayed. The Data tab,
activated by default, allows you to define and change data parameters for a layer.
Basic Info
The beginning sections—Basic Resource Info, Keywords and Metadata link—are analogous to the Service
Metadata section for WCS, WFS, and WMS. These sections provide “data about the data,” specifically textual
information that make the layer data easier to understand and work with. The metadata information will
appear in the capabilities documents which refer to the layer.
• Name—Identifier used to reference the layer in WMS requests. (Note that for a new layer for an
already-published resource, the name must be changed to avoid conflict.)
• Title—Human-readable description to briefly identify the layer to clients (required)
• Abstract—Describes the layer in detail
• Keywords—List of short words associated with the layer to assist catalog searching
• Metadata Links—Allows linking to external documents that describe the data layer. Currently only
two standard format types are valid: TC211 and FGDC. TC211 refers to the metadata structure established by the ISO Technical Committee for Geographic Information/Geomatics (ISO/TC 211) while

5.1. Data settings

59

GeoServer User Manual, Release 2.15.1

Fig. 5.23: Some layers selected for removal

Fig. 5.24: All layers selected for removal

60

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.25: Edit Layer: Data tab
FGDC refers to those set out by the Federal Geographic Data Committee (FGDC) of the United States.

Fig. 5.26: Adding a metadata link in FGDC format

Coordinate Reference Systems
A coordinate reference system (CRS) defines how georeferenced spatial data relates to real locations on the
Earth’s surface. CRSes are part of a more general model called Spatial Reference Systems (SRS), which
includes referencing by coordinates and geographic identifiers. GeoServer needs to know the Coordinate
Reference System of your data. This information is used for computing the latitude/longitude bounding
box and reprojecting the data during both WMS and WFS requests.

Fig. 5.27: Coordinate reference system of a layer
• Native SRS—Specifies the coordinate system the layer is stored in. Clicking the projection link displays a description of the SRS.
5.1. Data settings

61

GeoServer User Manual, Release 2.15.1

• Declared SRS—Specifies the coordinate system GeoServer publishes to clients
• SRS Handling—Determines how GeoServer should handle projection when the two SRSes differ.
Possible values are:
– Force declared (default): the declared SRS is forced upon the data, overwriting the native one.
This is the default option and normally the best course of action, the declared code comes from
the EPSG database and has a wealth of extra information in it, starting from a valid EPSG code,
an area of validity, a link back in the database to find the best transformation steps to other
coordinate reference systems should reprojection be required. Use this option when the source
has no native CRS, has a wrong one, or has one matching the EPSG code (in order to get full
metadata in the CRS used by GeoServer).
– Reproject from native: This setting should be used when the native data set has a CRS that is not
matching any official EPSG. OGC protocols need to advertise a EPSG code for the layers, with
this setting the declared one will be advertised, and reprojection from native will happen on the
fly as needed (in case a third CRS is requested, the reprojection will go directly from native to
declared)
– Keep native: this is a setting that should be used in very rare cases. Keeping native means using
the declared one in the capabilities documents, but then using the native CRS in all othe requests
(with no reprojection in between, unless explicitly requested from client). This is particularly
problematic if the source is a shapefile, as the PRJ files lack all the extra information provided by
the EPSG database (it will for example break WFS 1.1 and 2.0 SRS declarations in GML output).
The setting meant to be used in cases where WMS is the primary target, and the native and
declared CRSs have very small differences, avoiding on the fly reprojection and datum change.
In summary, use Force Declared as your primary option, Reproject from native only if your source data
does not match any EPSG code, and Keep Native only if you really know what you’re doing.
Bounding Boxes
The bounding box determines the extent of the data within a layer.
• Native Bounding Box—The bounds of the data specified in the Native SRS. These bounds can be
generated by clicking the Compute from data button or they can be generated from the SRS definition
by clicking the Compute from SRS bounds button. The SRS used depends on the SRS Handling chosen:
the declared SRS when Force declared or Reproject native to declared are chosen, otherwise the native SRS
is used. If the SRS does not have a bounding defined then none is generated.
• Lat/Lon Bounding Box—The bounds specified in geographic coordinates. These bounds can be calculated by clicking the Compute from native bounds button.

Fig. 5.28: Bounding Boxes of a layer

62

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Coverage Parameters (Raster)
Optional coverage parameters are possible for certain types of raster data. For example, WorldImage formats request a valid range of grid coordinates in two dimensions known as a ReadGridGeometry2D. For
ImageMosaic, you can use InputImageThresholdValue, InputTransparentColor, and OutputTransparentColor to
control the rendering of the mosaic in terms of thresholding and transparency.
Curves support (Vector)
GeoServer can handle geometries containing circular arcs (initially only from Oracle Spatial and the “properties data store”, though more data sources are planned).
These geometries are kept in memory in their circular representation for as long as possible, are properly
visually depicted in WMS, and encoded in GML 3.x as curved.
There are two options pertaining the circular arcs:
• Linear geometries can contain circular arcs should be checked to inform the GML encoder that
the layer can contain circular arcs among other linear segments in the geometries, and thus use
“gml:Curve” in place of “gml:LineString” in GML 3.1 output format. This is required because there is
no quick way to know from the data sources if the linear geometries do contain circular arcs, and the
choice of top level GML elements influences whether it is possible, or not, to represent circular arcs in
their natural form.
• Linearization tolerance controls how accurately the linearized version of geometries matches the
original circular version of them. The tolerance can be expressed as an absolute number in the native
unit of measure of the data, or it can be expressed in meters or feet using the “m” and “ft” suffixes
(such as “10m” or “15ft”).

Fig. 5.29: Curved geometry control

Feature Type Details (Vector)
Vector layers have a list of the Feature Type Details. These include the Property and Type of a data source. For
example, the sf:archsites layer shown below includes a geometry (the_geom) of type “point”.

Fig. 5.30: Feature Type Details
The Nillable option refers to whether the property requires a value or may be flagged as being null. Meanwhile Min/Max Occurrences refers to how many values a field is allowed to have. Currently both Nillable and
Min/Max Occurrences are set to true and 0/1 but may be extended with future work on complex features.
5.1. Data settings

63

GeoServer User Manual, Release 2.15.1

Restricting features showing up in the layer
By default GeoServer will publish all the features available in the layer. It is possible to restrict the features
to a subset by specifying a CQL filter in the configuration:

Fig. 5.31: Restrict the features on layer by CQL filter

Note: It is recommended to use this setting for layers that are not meant to be edited. The filter is only
applied to reads, if a WFS-T insert adds a feature not matching the filter, it will be added to the store
anyways, but won’t show up in any of the outputs.

Edit Layer: Publishing
The Publishing tab configures HTTP and WMS/WFS/WCS settings.

Fig. 5.32: Edit Layer: Publishing tab
• Enabled—A layer that is not enabled won’t be available to any kind of request, it will just show up in
the configuration (and in REST config)

64

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

• Advertised—A layer is advertised by default. A non-advertised layer will be available in all data
access requests (for example, WMS GetMap, WMS GetFeature) but won’t appear in any capabilities
document or in the layer preview.
HTTP Settings
Cache parameters that apply to the HTTP response from client requests.
• Response Cache Headers— If selected, GeoServer will not request the same tile twice within the time
specified in Cache Time. One hour measured in seconds (3600), is the default value for Cache Time.
Services Settings
Sets services configuration on layer level.

Fig. 5.33: Services Settings

• Selectively enable services for layer—Activate/deactivate service enable/disable configuration for
the layer.
• Enabled Services—Selects enabled services list for this layer.
• Disabled Services—Selects disabled services list for this layer.
Note: It is also possible to set by-default disabled services to all layers using the org.geoserver.
service.disabled system/env/servlet context variable. This variable accepts a comma separated
list of services that should be disabled by default, in case the resource in question has no explicit
configuration.

5.1. Data settings

65

GeoServer User Manual, Release 2.15.1

WMS Settings
Sets the WMS specific publishing parameters.

Fig. 5.34: WMS Settings

• Queryable—Controls whether the layer is queryable via WMS GetFeatureInfo requests.
• Default style—Style that will be used when the client does not specify a named style in GetMap
requests.
• Additional styles—Other styles that can be associated with this layer. Some clients (and the
GeoServer Layer Preview) will present those as styling alternatives for that layer to the user.
• Default rendering buffer—Default value of the buffer GetMap/GetFeatureInfo vendor parameter.
See the WMS vendor parameters for more details.
• Default WMS path—Location of the layer in the WMS capabilities layer tree. Useful for building
non-opaque layer groups
• Default Interpolation Method—Allows to specify a default resampling (interpolation) method for
this layer. The available options are Nearest neighbor, Bilinear, Bicubic, or Use service default, which
means that no layer specific configuration will be created (the default interpolation method selected
in the WMS service configuration page will be used, see Raster Rendering Options for details). Can be
overridden by the interpolations vendor parameter.
WMS Attribution
Sets publishing information about data providers.

• Attribution Text—Human-readable text describing the data provider. This might be used as the text
for a hyperlink to the data provider’s web site.
66

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.35: WMS Attribution
• Attribution Link—URL to the data provider’s website.
• Logo URL—URL to an image that serves as a logo for the data provider.
• Logo Content Type, Width, and Height—These fields provide information about the logo image that
clients may use to assist with layout. GeoServer will auto-detect these values if you click the Autodetect image size and type link at the bottom of the section. The text, link, and URL are each advertised in
the WMS Capabilities document if they are provided. Some WMS clients will display this information
to advise users which providers provide a particular dataset. If you omit some of the fields, those that
are provided will be published and those that are not will be omitted from the Capabilities document.
WFS Settings
Sets the WFS specific publishing parameters.

Fig. 5.36: WFS Settings

• Per-Request Feature Limit—Sets the maximum number of features for a layer a WFS GetFeature
operation should generate (regardless of the actual number of query hits)
• Maximum number of decimals—Sets the maximum number of decimals in GML output.

5.1. Data settings

67

GeoServer User Manual, Release 2.15.1

Note: It is also possible to override the OtherSRS/OtherCRS list configured in the WFS service,
including overriding it with an empty list if need be. The input area will accept a comma separated
list of EPSG codes:

Fig. 5.37: WFS otherSRS/otherCRS override
The list will be used only for the capabilities document generation, but will not be used to limit the
actual target SRS usage in GetFeature requests.
• Encode coordinates measures—Checking this setting will cause coordinates measures (“M”) to be
encoded in WFS output formats that support measures. The default (not checked) is to not encode
coordinates measures.
WCS Settings
• Request SRS—Provides a list of SRSs the layer can be converted to. New Request SRS allows you to
add an SRS to that list.
• Interpolation Methods—Sets the raster rendering process, if applicable.
• Formats—Lists which output formats a layers supports.
• GeoSearch—When enabled, allows the Google Geosearch crawler to index from this particular layer.
See What is a Geo Sitemap? for more information.
KML Format Settings
Limits features based on certain criteria, otherwise known as regionation.
• Default Regionating Attribute—Choose which feature should show up more prominently than others.
• Regionating Methods—There are four types of regionating methods:
– external-sorting—Creates a temporary auxiliary database within GeoServer. The first request to
build an index takes longer than subsequent requests.
– geometry—Externally sorts by length (if lines) or area (if polygons)
– native-sorting—Uses the default sorting algorithm of the backend where the data is hosted. It is
faster than external-sorting, but will only work with PostGIS datastores.

68

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

– random—Uses the existing order of the data and does not sort
Edit Layer: Dimensions
GeoServer supports adding specific dimensions to WMS layers, as specified in WMS 1.1.1 and WMS 1.3.0
standards. There are two pre-defined dimensions in the WMS standards mentioned above, TIME and
ELEVATION. Enabling dimensions for a layer allows users to specify those as extra parameters in GetMap
requests, useful for creating maps or animations from underlying multi-dimensional data.
These dimensions can be enabled and configured on the Dimensions tab.

Fig. 5.38: TIME dimension enabled for a WMS layer
For each enabled dimension the following configuration options are available:
• Attribute—Attribute name for picking the value for this dimension (vector only). This is treated at
start of the range if End attribute is also given.
• End attribute—Attribute name for picking the end of the value range for this dimension (optional,
vector only).
• Presentation—The presentation type for the available values in the capabilities document. Either each
value separately (list), interval and resolution, or continuous interval.
• Default value—Default value to use for this dimension if none is provided with the request. Select
one of from four strategies:
– smallest domain value—Uses the smallest available value from the data
– biggest domain value—Uses the biggest available value from the data
– nearest to the reference value—Selects the data value closest to the given reference value
– reference value—Tries to use the given reference value as-is, regardless of whether its actually
available in the data or not.
• Reference value—The default value specifier. Only shown for the default value strategies where its
used.
• Nearest match—Whether to enable, or not, WMS nearest match support on this dimension. Currently
supported only on the time dimension.
• Acceptable interval—A maximum search distance from the specified value (available only when
nearest match is enabled). Can be empty (no limit), a single value (symmetric search) or using a
before/after syntax to specify an asymmetric search range. Time distances should specified using

5.1. Data settings

69

GeoServer User Manual, Release 2.15.1

the ISO period syntax. For example, PT1H/PT0H allows to search up to one hour before the user
specified value, but not after.
For time dimension the value must be in ISO 8601 DateTime format yyyy-MM-ddThh:mm:ss.SSSZ For
elevation dimension, the value must be and integer of floating point number.
Only for the “Reference value” strategy, it is also possible to use ranges or times and ranges of elevation,
in the form fromValue/toValue. Only for the “Reference value” strategy, and limited to times, it’s also
possible to use relative times like P1M/PRESENT, but caution is given that the reference value is copied
verbatim into the capabilities document, and as a result, not all client might be recognizing that syntax.
Note: For more information on specifying times, please see the section on Time Support in GeoServer WMS.

5.1.5 Layer Groups
A layer group is a container in which layers and other layer groups can be organized in a hierarchical
structure. A layer group can be referred to by a single name in WMS requests. This allows simpler requests,
as one layer can be specified instead of multiple individual layers. A layer group also provides a consistent,
fixed ordering of the layers it contains, and can specify alternate (non-default) styles for layers.

Fig. 5.39: Layer Groups page

Layer Group modes
Layer group behaviour can be configured by setting its mode. There are 5 available values:
• single: the layer group is exposed as a single layer with a name, acting as an alias for a list of layers.
The layers are still showing up as top level entries in the WMS capabilities document (unless explicitly
referred by a tree group).
• opaque container: the layer group is exposed as a single layer with a name, acting as an alias for a
list of layers. However, the layers and sub-groups contained in it won’t show up in the capabilities
document (unless explicitly referred by a tree group) and won’t be available by themselves in WMS
calls and in the WMS capabilities document, but only as part of the group.
• named tree: the layer group can be referred to by one name, but also exposes its nested layers and
groups in the capabilities document.
• container tree: the layer group is exposed in the capabilities document, but does not have a name,
making it impossible to render it on its own. This is called “containing category” in the WMS specification.

70

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

• Earth Observation tree: a special type of group created to manage the WMS Earth Observation requirements. This group does not render its nested layers and groups, but only a “preview layer”
called Root Layer. When this mode is chosen, a new field “Root Layer” will be exposed in the configuration UI.
If a layer is included in any non single mode group, it will no longer be listed in the flat layer list. It will still
be possible to include the layer in other layer groups.
Layer Group Mode
Single
Opaque Container
Named Tree
Container Tree
Earth Observation Tree

Named
named
named
named
named

Contains Children
yes
yes
yes
yes

Lists Children
no
no
lists children
lists children
lists children

Details
hides children

has root layer

Edit a Layer Group
To view or edit a layer group, click the layer group name. A layer group configuration page will be displayed. The initial fields allow you to configure the name, title, abstract, workspace, bounds, projection and
mode of the layer group. To automatically set the bounding box, select the Generate Bounds button or the
Generate Bounds From CRS button to use the bounds defined in the CRS (if available). You may also provide
your own custom bounding box extents. To select an appropriate projection click the Find button.
Note: A layer group can contain layers with dissimilar bounds and projections. GeoServer automatically
reprojects all layers to the projection of the layer group.
The table at the bottom of the page lists layers and groups contained within the current layer group. We
refer to layers and layer groups as publishable elements. When a layer group is processed, the layers are
rendered in the order provided, so the publishable elements at the bottom of list will be rendered last and will
show on top of the other publishable elements.
A publishable element can be positioned higher or lower on this list by clicking the green up or down arrows,
respectively, or can be simply dragged in the target position. The layer at the top of the list is the first one
to be painted, the layer below it will be painted second, and so on, the last layer will be painted on top of
all others (this is the so called “painter’s model”).
The Style column shows the style associated with each layer. To change the style associated with a layer,
click the appropriate style link. A list of enabled styles will be displayed. Clicking on a style name reassigns
the layer’s style.
To remove a publishable element from the layer group, select its button in the Remove column. You will now
be prompted to confirm or cancel this deletion.
A layer can be added to the list by clicking the Add Layer. . . button at the top of the table. From the list of
layers, select the layer to be added by clicking the layer name. The selected layer will be appended to the
bottom of the publishable list.
A layer group can be added by clicking the Add Layer Group. . . button at the top of the table. From the list of
layer groups, select the layer group to be added by clicking its name. The selected group will be appended
to the bottom of the publishable list.
A style group can be added by clicking the Add Style Group. . . button at the top of the table. From the list
of styles, select the style group to be added by clicking its name. The selected style will be appended to the
bottom of the publishable list.
You can view layer groups in the Layer Preview section of the web admin.
5.1. Data settings

71

GeoServer User Manual, Release 2.15.1

Fig. 5.40: Layer Groups Edit page

72

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.41: Style editing for a layer within a layer group

Fig. 5.42: Dialog for adding a layer to a layer group

Fig. 5.43: Dialog for adding a layer group to a layer group

Fig. 5.44: Dialog for adding a style group to a layer group
5.1. Data settings

73

GeoServer User Manual, Release 2.15.1

Fig. 5.45: Openlayers preview of the layer group “tasmania”

Note: By default, a layer group is queryable when at least a child layer is queryable. Uncheck “Queryable”
box if you want to explicitly indicate that it is not queryable independently of how the child layers are
configured.

Add a Layer Group
The buttons for adding and removing a layer group can be found at the top of the Layer Groups page.

Fig. 5.46: Buttons to add or remove a layer group
To add a new layer group, select the “Add a new layer group” button. You will be prompted to name the
layer group.
When finished, click Submit. You will be redirected to an empty layer group configuration page. Begin by
adding layers by clicking the Add layer. . . button (described in the previous section). Once the layers are
positioned accordingly, press Generate Bounds to automatically generate the bounding box and projection.
You may also press the Generate Bounds From CRS button to use the CRS bounds (if available). Press Save to
save the new layer group.

74

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.47: New layer group dialog

Fig. 5.48: New layer group configuration page

5.1. Data settings

75

GeoServer User Manual, Release 2.15.1

Remove a Layer Group
To remove a layer group, select it by clicking the checkbox next to the layer group. Multiple layer groups
can be selected, or all can be selected by clicking the checkbox in the header. Click the Remove selected layer
group(s) link. You will be asked to confirm or cancel the deletion. Selecting OK removes the selected layer
group(s).

Fig. 5.49: Removing a layer group

Layer Group Keywords
Is possible to associate a layer group with some keywords that will be used to assist catalog searching.

Fig. 5.50: Layer groups keywords editor
Layer groups keywords will no be merged with contained layers keywords but keywords of a layer group
should be logically inherited by contained layers.
Note: Information on the Styles pages can be found on the Styles page.

76

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

5.2 Vector data
This section discusses the vector data sources that GeoServer can access.
The standard GeoServer installation supports the loading and serving of the following data formats:

5.2.1 Shapefile
A shapefile is a popular geospatial vector data format.
Note: While GeoServer has robust support for the shapefile format, it is not the recommended format
of choice in a production environment. Databases such as PostGIS are more suitable in production and
offer better performance and scalability. See the section on Running in a production environment for more
information.

Adding a shapefile
A shapefile is actually a collection of files (with the extensions: .shp, .dbf, .shx, .prj, and sometimes
others). All of these files need to be present in the same directory in order for GeoServer to accurately read
them. As with all formats, adding a shapefile to GeoServer involves adding a new store to the existing
Stores through the Web administration interface.
Warning: The .prj file, while not mandatory, is strongly recommended when working with GeoServer
as it contains valuable projection info. GeoServer may not be able to load your shapefile without it!
To begin, navigate to Stores → Add a new store → Shapefile.
Option
Workspace
Data Source Name

Description
Enabled
URL

namespace
create spatial index
charset
memory
mapped
buffer Cache and
reuse memory maps

Description
Name of the workspace to contain the store. This will also be the prefix of the layer
created from the store.
Name of the shapefile as known to GeoServer. Can be different from the filename.
The combination of the workspace name and this name will be the full layer name
(ex: topp:states).
Description of the shapefile/store.
Enables the store. If unchecked, no data in the shapefile will be served.
Location of the shapefile.
Can be an absolute path (such as
file:C:\Data\shapefile.shp) or a path relative to the data directory
(such as file:data/shapefile.shp.
Namespace to be associated with the shapefile. This field is altered by changing
the workspace name.
Enables the automatic creation of a spatial index.
Character set used to decode strings from the .dbf file.
Enables the use of memory mapped I/O, improving caching of the file in memory.
Turn off on Windows servers.

When finished, click Save.

5.2. Vector data

77

GeoServer User Manual, Release 2.15.1

Fig. 5.51: Adding a shapefile as a store

78

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Configuring a shapefile layer
Shapefiles contain exactly one layer, which needs to be added as a new layer before it will be able to be
served by GeoServer. See the section on Layers for how to add and edit a new layer.

5.2.2 Directory of spatial files
The directory store automates the process of loading multiple shapefiles into GeoServer. Loading a directory that contains multiple shapefiles will automatically add each shapefile to GeoServer.
Note: While GeoServer has robust support for the shapefile format, it is not the recommended format
of choice in a production environment. Databases such as PostGIS are more suitable in production and
offer better performance and scalability. See the section on Running in a production environment for more
information.

Adding a directory
To begin, navigate to Stores → Add a new store → Directory of spatial files.

Fig. 5.52: Adding a directory of spatial files as a store

5.2. Vector data

79

GeoServer User Manual, Release 2.15.1

Option
Workspace
Data Source Name
Description
Enabled
URL

namespace

Description
Name of the workspace to contain the store. This will also be the prefix of all of the
layer names created from shapefiles in the store.
Name of the store as known to GeoServer.
Description of the directory store.
Enables the store. If disabled, no data in any of the shapefiles will be served.
Location of the directory.
Can be an absolute path (such as
file:C:\Data\shapefile_directory) or a path relative to the data directory (such as file:data/shapefile_directory.
Namespace to be associated with the store. This field is altered by changing the
workspace name.

When finished, click Save.
Configuring shapefiles
All of the shapefiles contained in the directory store will be loaded as part of the directory store, but they
will need to be individually configured as new layers they can be served by GeoServer. See the section on
Layers for how to add and edit new layers.

5.2.3 Java Properties
The Properties data store provides access to one or more feature types (layers) stored in Java property
files; these are plain text files stored on the local filesystem. The Properties data store was never intended
to be shipped with GeoServer. It originated in a GeoTools tutorial, and later found widespread use by
developers in automated tests that required a convenient store for small snippets of data. It slipped into
GeoServer through the completeness of the packaging process, and was automatically detected and offered
to users via the web interface. The Property data store has proved useful in tutorials and examples.
• We do not recommend the use the Properties data store for large amounts of data, with either many
features or large geometries. Its performance will be terrible.
• For small data sets, such as collections of a few dozen points, you may find it to be satisfactory. For
example, if you have a few points you wish to add as an extra layer, and no convenient database in
which store them, the Properties data store provides a straightforward means of delivering them.
• Changes to a property file are immediately reflected in GeoServer responses. There is no need to
recreate the data store unless the first line of a property file is changed, or property files are added or
removed.
Adding a Properties data store
By default, Properties will be an option in the Vector Data Sources list when creating a new data store.

Fig. 5.53: Properties in the list of vector data stores

80

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Configuring a Properties data store

Fig. 5.54: Configuring a Properties data store
Option
Workspace
Data Source
Name
Description
Enabled
directory

Description
Sets the namespace prefix of the feature types (layers) and their properties
Unique identifier to distinguish this data store
Optional text giving a verbose description of the data store
Features will be delivered only if this option is checked
Filesystem path to a directory containing one or more property files, for example
/usr/local/geoserver/data/ex

Every property file TYPENAME.properties in the designated directory is served as a feature type
TYPENAME (the name of the file without the .properties), in the namespace of the data store.
Before a feature type (layer) can be used, you must edit it to ensure that its bounding box and other metadata
is configured.
Property file format
The property file format is a subset of the Java properties format: a list of lines of the form KEY=VALUE.
This example stations.properties defines four features of the feature type (layer) stations:
_=id:Integer,code:String,name:String,location:Geometry:srid=4326
stations.27=27|ALIC|Alice Springs|POINT(133.8855 -23.6701)
stations.4=4|NORF|Norfolk Island|POINT(167.9388 -29.0434)
stations.12=12|COCO|Cocos|POINT(96.8339 -12.1883)
stations.31=31|ALBY|Albany|POINT(117.8102 -34.9502)

5.2. Vector data

81

GeoServer User Manual, Release 2.15.1

• Blank lines are not permitted anywhere in the file.
• The first line of the property file begins with _= and defines the type information required to interpret
the following lines.
– Comma separated values are of the form NAME:TYPE
– Names are the property name that are used to encode the property in WFS responses.
– Types include Integer, String, Float, and Geometry
– Geometry can have an extra suffix :srid=XXXX that defines the Spatial Reference System by its
numeric EPSG code. Note that geometries defined in this way are in longitude/latitude order.
• Subsequent lines define features, one per line.
– The key before the = is the feature ID (fid or gml:id in WFS responses). Each must be an
NCName.
– Feature data follows the = separated by vertical bars (|). The types of the data must match the
declaration on the first line.
– Leave a field empty if you want it to be null; in this case the property will be ignored.
Note that in this example srid=4326 sets the spatial reference system (SRS) to EPSG:4326, which is
by convention in longitude/latitude order when referred to in the short form. If you request these features in GML 3 you will see that GeoServer correctly translates the geometry to the URN form SRS
urn:x-ogc:def:crs:EPSG:4326 in latitude/longitude form. See the WFS settings page for more on
SRS axis order options.

5.2.4 GeoPackage
GeoPackage is an SQLite based standard format that is able to hold multiple vector and raster data layers
in a single file.
GeoPackage files can be used both as Raster Data Stores as well as Vector Data Stores (so that both kinds of
layers can published).
Adding a GeoPackage Vector Data Store
When the extension has been installed, GeoPackage will be an option in the Vector Data Sources list when
creating a new data store.

Fig. 5.55: GeoPackage in the list of vector data stores

82

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.56: Configuring a GeoPackage Vector data store

5.2. Vector data

83

GeoServer User Manual, Release 2.15.1

Option
database
user
passwd
namespace
max connections
min connections
fetch size
Connection timeout
validate connections

Description
URI specifying geopackage file.
User to access database.
Password to access database.
Namespace to be associated with the database. This field is altered by changing the
workspace name.
Maximum amount of open connections to the database.
Minimum number of pooled connections.
Number of records read with each interaction with the database.
Time (in seconds) the connection pool will wait before timing out.
Checks the connection is alive before using it.

When finished, click Save.
Other data sources are supplied as GeoServer extensions. Extensions are downloadable modules that add
functionality to GeoServer. Extensions are available at the GeoServer download page.
Warning: The extension version must match the version of the GeoServer instance.

5.2.5 GML
Note: GeoServer does not come built-in with support for GML; it must be installed through an extension.
Proceed to Installing the GML extension for installation details.

Warning: Currently the GML extension is unmaintained and carries unsupported status. While still
usable, do not expect the same reliability as with other extension.
Geographic Markup Language (GML) is a XML based format for representing vector based spatial data.
Supported versions
Currently GML version 2 is supported.
Installing the GML extension
1. Download the GML extension from the GeoServer download page.
Warning: Make sure to match the version of the extension to the version of the GeoServer instance!
2. Extract the contents of the archive into the WEB-INF/lib directory of the GeoServer installation.

84

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Adding a GML data store
Once the extension is properly installed GML will be an option in the Vector Data Sources list when creating
a new data store.

Fig. 5.57: GML in the list of vector data stores

Configuring a GML data store

Fig. 5.58: Configuring a GML data store

5.2.6 Pregeneralized Features
Note: GeoServer does not come built-in with support for Pregeneralized Features; it must be installed
through an extension.

Installing the Pregeneralized Features extension
1. Download the Pregeneralized Features extension from the GeoServer download page.
Warning: Make sure to match the version of the extension to the version of the GeoServer instance!

5.2. Vector data

85

GeoServer User Manual, Release 2.15.1

2. Extract the contents of the archive into the WEB-INF/lib directory of the GeoServer installation.
Adding a Pregeneralized Features data store
If the extension is properly installed, Generalized Data Store will be listed as an option when creating a new
data store.

Fig. 5.59: Generalized Data Store in the list of vector data stores

Configuring a Pregeneralized Features data store

Fig. 5.60: Configuring a Pregeneralized Features data store
For a detailed description, look at the Tutorial

5.3 Raster data
This section discusses the raster (coverage) data sources that GeoServer can access.
The standard GeoServer installation supports the loading and serving of the following data formats:

86

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

5.3.1 GeoTIFF
A GeoTIFF is a georeferenced TIFF (Tagged Image File Format) file.
Adding a GeoTIFF data store
By default, GeoTIFF will be an option in the Raster Data Sources list when creating a new data store.

Fig. 5.61: GeoTIFF in the list of raster data stores

Configuring a GeoTIFF data store

Fig. 5.62: Configuring a GeoTIFF data store
Option
Workspace
Data Source
Name
Description
Enabled
URL

5.3. Raster data

Description
Name of the workspace to contain the GeoTIFF store. This will also be the prefix of
the raster layer created from the store.
Name of the GeoTIFF as it will be known to GeoServer. This can be different from
the filename. The combination of the workspace name and this name will be the
full layer name (ex: world:landbase)
A full free-form description of the GeoTIFF store.
If checked, it enables the store. If unchecked (disabled), no data in the GeoTIFF will
be served from GeoServer.
Location of the GeoTIFF file.
This can be an absolute path (such as
file:C:\Data\landbase.tif) or a path relative to GeoServer’s data directory
(such as file:data/landbase.tif).
87

GeoServer User Manual, Release 2.15.1

Note: Notice that the GeoTiff plugin is able to handle internal/external overviews and internal/external
masks.

Custom CRS definition
Creating an auxiliary .prj file that contains coordinate reference system information as described in the
Custom CRS Definitions chapter will override internal CRS tags that are included in the original GeoTIFF
file. This can be used to work-around problematic source files without making modifications to the file.

5.3.2 GTOPO30
GTOPO30 is a Digital Elevation Model (DEM) dataset with a horizontal grid spacing of 30 arc seconds.
Note: An example of a GTOPO30 can be found at http://edc.usgs.gov/products/elevation/gtopo30/
gtopo30.html

Adding a GTOPO30 data store
By default, GTOPO30 will be an option in the Raster Data Sources list when creating a new data store.

Fig. 5.63: GTOPO30 in the list of raster data stores

Configuring a GTOPO30 data store
Option
Workspace
Data Source
Name
Description
Enabled
URL

Description

5.3.3 WorldImage
A world file is a plain text file used to georeference raster map images. This file (often with an extension
of .jgw or .tfw) accompanies an associated image file (.jpg or .tif). Together, the world file and the
corresponding image file is known as a WorldImage in GeoServer.

88

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.64: Configuring a GTOPO30 data store
Adding a WorldImage data store
By default, WorldImage will be an option in the Raster Data Sources list when creating a new data store.

Fig. 5.65: WorldImage in the list of raster data stores

Configuring a WorldImage data store
Option
Workspace
Data Source
Name
Description
Enabled
URL

Description

5.3.4 ImageMosaic
The ImageMosaic data store allows the creation of a mosaic from a number of georeferenced rasters.
The mosaic operation creates a mosaic from two or more source images. This operation could be used to
assemble a set of overlapping geospatially rectified images into a contiguous image. It could also be used
to create a montage of photographs such as a panorama.

5.3. Raster data

89

GeoServer User Manual, Release 2.15.1

Fig. 5.66: Configuring a WorldImage data store
The plugin can be used with GeoTIFFs, as well as rasters accompanied by a world file (.wld, .pgw for PNG
files, .jgw for JPG files, etc.). In addition, if imageIO-ext GDAL extension is properly installed, the plugin
can also serve all the formats supported by it such as MrSID, ECW, JPEG2000. It also supports NetCDF and
GRIB.

ImageMosaic configuration
Granules
Each individual image is commonly referred to as a granule. In recent releases of GeoServer the similarities
requirements for the granules have been dropped significantly, including:
• The granules do not need to share the same coordinate reference system (see the multi-CRS mosaic
tutorial)
• The granules can be in different color models, with an allowance of mixing gray, RGB, RGBA and
indexed color granules (it is however not possible to mix colored granules with scientific data types
like as float/double). In order to benefit of mixed color models JAI-Ext support must be enabled, see
the JAI-EXT support documentation.
In addition it is worth remarking on the fact that currently the ImageMosaic is able to handle raster data
whose grid-to-world transformation is a scale and translate transformation, hence no rotation or skew.
Index and configuration file creation
When a new store is created, an index shapefile will be generated to associate each granule file with its
bounding box. The index creation respects directory trees as well as single directories. All you need to

90

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

do is point the store to the root of the hierarchy, and all images will be considered for inclusion in the
ImageMosaic.
The index will contain the enclosing polygon for each raster file (in an appropriate coordinate reference
system) and the path to each of these files. The location attribute can be relative to the configuration folder
or absolute. By default, the name of this attribute is location, but this can be changed in the main configuration file.
If you already have these files generated, GeoServer will respect them and not generate a new index. By
default, a shapefile is used for the index, but PostGIS, H2, and Oracle are also supported, with additional
configuration steps.
Configuration files
Within each store there are multiple configuration files that determine how the mosaic is rendered.
Primary configuration file
The mosaic configuration file is the primary file used to store the configuration parameters that control
the ImageMosaic plugin. When created by GeoServer it is by default called .properties,
where  is the name of the root directory of the store. (It is not related to the store name in
GeoServer.) It can have other names, as long as it does not conflict with other files such as datastore.
properties or indexer.properties. This file usually does not require manual editing.
The table below describes the various elements in this configuration file.

5.3. Raster data

91

GeoServer User Manual, Release 2.15.1

Parameter
Mandatory?
Description
Levels
Y
Represents the resolutions for the various levels of the granules of this mosaic.
Heterogeneous N
Sets whether the image files are heterogeneous. Default is false.
AbsolutePath N
Controls whether or not the path stored inside the location attribute represents
an absolute path or a path relative to the location of the shapefile index. Notice that
a relative index ensures much more portability of the mosaic itself. Default value
for this parameter is false, which means relative paths.
Name
N
The name to be assigned to the index. If unspecified, the index name will usually
match the name of the folder containing the mosaic.
TypeName
Y
Featuretype name for this mosaic. Usually the name as Name.
Caching
N
Boolean value to enable caching. When set to true, the ImageMosaic will try to
save in memory the entire contents of the index to reduce loading/query time. Set
to false for a large granule index and/or if new granules are to be ingested (for
example, when the index is on a database and we interact directly with it). Default
is false.
ExpandToRGB N
Boolean flag to force color expansion from index color model (paletted datasets) to
component color model (RGB). Default is false.
LocationAttributeY
The name of the attribute path in the shapefile index. Default is location.
SuggestedSPI Y
Suggested plugin for reading the image files.
Envelope2D
N
Envelope for the mosaic formatted as LLX,LLY URX,URY (notice the space between the lower left and upper right coordinate pairs).
CheckAuxiliaryMetadata
N
This parameter allows to specify whether the ImageMosaic plugin should check
for the presence of a GDAL aux.xml file beside each granule file. For most common use cases, you don’t need to set or specify this parameter. Being disabled by
Default, ImageMosaic won’t look for an ancillary file for each granule being initialized in the GranuleCatalog. This avoid useless checks, especially when dealing
with thousand of granules. You should set that parameter to true when you want
to instruct the ImageMosaic to look for a GDAL generated aux.xml file containing PAM (Persistent Auxiliary Metadata) for each granule, to be attached to the
Granule info (GranuleDescriptor). This is specially useful when you have setup
a Dynamic ColorMap rendering transformation which dynamically set a color map
based on the statistics collected into the granule’s GDAL PAM being previously
generated with a gdalinfo -stats parameter.
LevelsNum
Y
Represents the number of reduced resolution layers that we currently have for the
granules of this mosaic.
A sample configuration file follows:
Levels=0.4,0.4
Heterogeneous=false
AbsolutePath=false
Name=osm
TypeName=osm
Caching=false
ExpandToRGB=false
LocationAttribute=location
SuggestedSPI=it.geosolutions.imageioimpl.plugins.tiff.TIFFImageReaderSpi
CheckAuxiliaryMetadata=false
LevelsNum=1

92

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

datastore.properties
By default the ImageMosaic index is specified by a shapefile, which is located at the root of the ImageMosaic
directory, just like the primary configuration file.
If needed, different storage can be used for the index — like a spatial DBMS, which is the preferred solution
when you wish to share the ImageMosaic itself in a cluster of GeoServer instances. In this case the user must
supply GeoServer with the proper connection parameters, which can be specified by using a datastore.
properties file placed at the root of the ImageMosaic directory.
Note: A shapefile is created automagically if it does not exist or if there is no datastore.properties
file.

Warning: At the time of writing the following spatial DBMS have been tested successfully: Oracle,
PostgreSQL, H2. SQl Server is not yet supported.

Parameter
StoreName

SPI

Connection
parameters

Mandatory?
Description
N
Can be used to refer to a GeoServer registered store, using a
“workspace:storeName” syntax. When this is used, the no other connection
parameters need to be provided. The SPI can still be provided to inform the mosaic
of the resulting type of store (e.g., Oracle) in case specific behavior need to be
enacted for it (e.g., in the case of Oracle the attributes are all uppercase and cannot
be longer than 30 chars, the mosaic will respect the limits but the SPI parameter
needs to be explicitly set to org.geotools.data.oracle.OracleNGDataStoreFactory as the
actual store type is hidden when it reaches the mosaic code). Also, as a reminder,
the code is picking up a Store reference, not a layer one, meaning that security
restrictions that might have been applied to a layer exposing the feature type do
not apply to the mosaic code (e.g., if a user has restrictions such as a spatial filter
on said layer, it won’t transfer to the mosaic, which needs to be secured separately)
Y
The DataStoreFactory used to connect to the index store:
• PostGIS: org.geotools.data.postgis.PostgisNGDataStoreFactory
• Oracle: org.geotools.data.oracle.OracleNGDataStoreFactory
• H2: org.geotools.data.h2.H2DataStoreFactory
JNDI can also be used with any of these stores. If JNDI is used, the DataStoreFactory name will differ from the above.
Y
The connection parameters used by the specified SPI. The list of these connection
parameters can be found in the GeoTools documentation on the relevant store:
• PostGIS
• Oracle
• H2
If JNDI is used, the connection parameters will include jndiReferenceName instead of host, port, etc. Note that for any connection parameters that include a
space (such as loose bbox), the space must be escaped by preceding it with a
backslash (loose\ bbox).

Here is a sample datastore.properties file for a PostGIS index:
SPI=org.geotools.data.postgis.PostgisNGDataStoreFactory
host=localhost
port=5432

5.3. Raster data

93

GeoServer User Manual, Release 2.15.1

database=osm
schema=public
user=user
passwd=password
Loose\ bbox=true
Estimated\ extends=false
validate\ connections=true
Connection\ timeout=10
preparedStatements=true

Here is a sample datastore.properties file for a PostGIS index via JNDI:
SPI=org.geotools.data.postgis.PostgisNGJNDIDataStoreFactory
#String
# JNDI data source
# Default "java:comp/env/"+"jdbc/mydatabase"
jndiReferenceName=
#Boolean
# perform only primary filter on bbox
# Default Boolean.TRUE
Loose\ bbox=true
#Boolean
# use prepared statements
#Default Boolean.FALSE
preparedStatements=false

indexer.properties
In addition to the required envelope and location attributes, the schema for the index store may expose
other custom attributes which can be used later for filtering the ImageMosaic granules on the fly during a
WMS or WCS request or to diver WMS and WCS dimensions like TIME, ELEVATION and so on. This is
configured by the indexer.properties file:

94

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Parameter
Schema

Mandatory?
Description
Y
A comma-separated sequence describing the mapping between attribute and data
type.
PropertyCollectors
Y
A comma-separated list of PropertyCollectors. Each entry in the list includes the
extractor class, the file name (within square brackets [ ] and not including the
.properties suffix) containing the regular expression needed to extract the attribute value from the granule file name, and the attribute name (within parentheses ( )). The instance of the extractor class also indicates the type of object computed by the specific collector, so a TimestampFileNameExtractorSPI will return Timestamps while a DoubleFileNameExtractorSPI will return Double
numbers.
TimeAttribute N
Specifies the name of the time-variant attribute.
ElevationAttribute
N
Specifies the name of the elevation attribute.
AuxiliaryFile
N
Path to an auxiliary file to be used for internal purposes (For example: when dealing with NetCDF granules, it refers to the NetCDF XML ancillary file.)
AbsolutePath N
Controls whether or not the path stored inside the location attribute represents
an absolute path or a path relative to the location of the shapefile index. Notice that
a relative index ensures better portability of the mosaic itself. Default value for this
parameter is false, which means relative paths.
Caching
N
Boolean value to enable caching. When set to true, the ImageMosaic will try to
save in memory the entire contents of the index to reduce loading/query time. Set
to false for a large granule index and/or if new granules are to be ingested (for
example, when the index is on a database and we interact directly with it). Default
is false.
CanBeEmpty N
Boolean flag used for configuring empty mosaics. When enabled the ImageMosaic
will not throw an exception caused by the absence of any coverage. By default it is
set to false.
Envelope2D
N
Envelope for the mosaic formatted as LLX,LLY URX,URY (notice the space between the lower left and upper right coordinate pairs).
ExpandToRGB N
Boolean flag to force color expansion from index color model (paletted datasets) to
component color model (RGB). Default is false.
IndexingDirectories
N
Comma separated values list of paths referring to directories containing granules
to be indexed. If unspecified, the IndexingDirectory will be the mosaic configuration directory. This parameter allows configuration of a mosaic in a folder which
contains only configuration files, while the granules to be indexed are stored somewhere else.
Name
N
The name to be assigned to the index. If unspecified, the index name will usually
match the name of the folder containing the mosaic.
CoverageNameCollectorSPI
N
As described in the previous row, the Name parameter allows specification of the
coverage name to be exposed by the ImageMosaic. An ImageMosaic of NetCDFs
instead exposes a coverage for each supported variable found in the NetCDF,
using the variable’s name as the coverage name (for instance, air_temperature,
wind_speed, etc.) The optional CoverageNameCollectorSPI property allows specification of a CoverageNameCollector plugin to be used to instruct the ImageMosaic
on how to setup different coverageNames for granules. It should contains the full
name of the implementing class plus an optional set of semicolon-separated keyValue pairs prefixed by “:”. See below for an example.
Recursive
N
Boolean flag used at indexing time. When set to true, the indexer will look for
granules by scanning any subdirectory contained in the indexing directory. If
false, only the main folder will be analyzed. Default is true.
UseExistingSchema
N
Boolean flag used for enabling/disabling the use of existing schemas. When enabled, the ImageMosaic will start indexing granules using the existing database
schema (from datastore.properties) instead of populating it. This is useful
when you already have a database with a valid mosaic schema (the_geom, location
and other attributes, take a look at gdalindex) or when you do not want to rename
5.3. Raster data
the images to add times and dimensions (you should simply add them to the table,95
to AdditionalDomainAttributes and to PropertyCollectors). Default is false.
Wildcard
N
Wildcard used to specify which files should be scanned by the indexer. (For instance: “.”)

GeoServer User Manual, Release 2.15.1

Here is a sample indexer.properties file:
Schema=*the_geom:Polygon,location:String,ingestion:java.util.Date,elevation:Double
PropertyCollectors=TimestampFileNameExtractorSPI[timeregex](ingestion),
,→DoubleFileNameExtractorSPI[elevationregex](elevation)
TimeAttribute=ingestion
ElevationAttribute=elevation
Caching=false
AbsolutePath=false

An example of optional CoverageNameCollectorSPI could be:
CoverageNameCollectorSPI=org.geotools.gce.imagemosaic.namecollector.
,→FileNameRegexNameCollectorSPI:regex=^([a-zA-Z0-9]+)

This defines a regex-based name collector which extracts the coverage name from the prefix of the file
name, so that an ImageMosaic with temperature_2015.tif, temperature_2016.tif, pressure_2015.tif, pressure_2016.tif will put temperature* granules on a temperature coverage and pressure* granules on a
pressure coverage.
Property collectors
The following table enumerates the available property collectors
Collector
SPI Description
name
ByteFileNameExtractorSPI
Extracts an number from the file name using a regular expression specified in a
DoubleFileNamesidecar file, casting it to the desired type based on the SPI name (e..g, DoubleFileExtractorSPI
NameExtractorSPI extracts double precision floating points, IntegerFileNameExFloatFileNametractorSPI extracts 32 bit integers)
ExtractorSPI
IntegerFileNameExtractorSPI
LongFileNameExtractorSPI
ShortFileNameExtractorSPI
TimestampFileNameExtractorSPI
Extracts a timestamp from the filename using a regular expression specified in a
sidecar file
StringFileNameExtractorSPI
Extracts a string from the filename using a regular expression specified in a sidecar
file
CurrentDateExtractorSPI
Returns the current date and time (useful to track ingestion times in a mosaic)
FSDateExtractorSPI Returns the creation date of the file being harvested
DateExtractorSPI
Returns the date found in tiff file header “DateTime” (code 306)
ResolutionExtractorSPI
Returns the native resolution of the raster being harvested. ResolutionExtractorSPI
ResolutionXExand ResolutionXExtractorSPI return the x resolution of the raster, ResolutionYExtractorSPI Resolu- tractorSPI returns the resolution on the Y axis instead
tionYExtractorSPI
CRSExtractorSPI
Returns the code of the the raster coordinate reference system, as a string, e.g.
“EPSG:4326”
The PropertyCollectors parameter in the example above indicates two additional .properties files
used to populate the ingestion and elevation attributes:

96

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

timeregex.properties:
regex=[0-9]{8}T[0-9]{9}Z(\?!.\*[0-9]{8}T[0-9]{9}Z.\*)

The above is a property file containing a regex used to extract Date and Time represented in ISO-8601 as
part of the filename. (Note the T char between digits for date and digits for time, as per ISO-8601)
In case of custom format datetimes in filename, an additional format element should be added after the
regex, preceded by a comma, defining the custom representation.

Example:
Temperature_2017111319.tif
an hourly Temperature file with datetime = November, 13 2017 at 7:00 PM (the last 2 digits = 19)
In that case, the timeregex.properties file should be like this:
regex=.*([0-9]{10}).*,format=yyyyMMddHH
elevationregex.properties:
regex=(?<=_)(\\d{4}\\.\\d{3})(?=_)

Store parameters
By default, ImageMosaic will be an option in the Raster Data Sources list when creating a new data store.

Fig. 5.67: ImageMosaic in the list of raster data stores

Option
Workspace
Data
Source
Name
Description
Enabled
URL

Description
Workspace for the store
Name of the store
Description of the store
Determines whether the store is enabled. If unchecked, all layers in the store will
be disabled.
The location of the store. Can be a local directory.

Coverage parameters
Creation of the store is the first step to getting an ImageMosaic published in GeoServer. Most of the configuration is done when publishing the resulting coverage (layer).
The Coverage Editor gives users the possibility to set a few control parameters to further control the mosaic
creation process.
The parameters are as follows:

5.3. Raster data

97

GeoServer User Manual, Release 2.15.1

Fig. 5.68: Configuring an ImageMosaic data store

Fig. 5.69: Coverage parameters

98

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Parameter
Accurate
resolution
computation

AllowMultithreading

BackgroundValues

Filter

Description
Boolean value. If true, computes the resolution of the granules in 9 points:
the corners of the requested area and the middle points, taking the better one.
This will provide better results for cases where there is a lot more deformation on a subregion (top/bottom/sides) of the requested bounding box with
respect to others. If false, computes the resolution using a basic affine scale
transform.
If true, enables multithreaded tile loading. This allows performing parallelized loading of the granules that compose the mosaic. Setting this to true
makes sense only if you set USE_JAI_IMAGEREAD to false at the same
time to force immediate loading of data into memory.
Sets the value of the mosaic background. Depending on the nature of the
mosaic it is wise to set a value for the “nodata” area (usually -9999). This
value is repeated on all the mosaic bands.
Sets the default mosaic filter. It should be a valid ECQL query to be used
by default if no cql_filter is specified (instead of Filter.INCLUDE). This
filter will be applied against the mosaic index, and may include any attributes
exposed by the index store. If the cql_filter is specified in the request it
will be overridden.
Note: Do not use this filter to change time or elevation dimensions defaults.
It will be added as AND condition with CURRENT for “time” and LOWER
for “elevation”.

FootprintBehavior

InputTransparentColor

MaxAllowedTiles

MergeBehavior

OutputTransparentColor
5.3. Raster data

Sets the behavior of the regions of a granule that are outside of the granule footprint. Can be None (ignore the footprint), Cut (remove regions
outside the footprint from the image and don’t add an alpha channel), or
Transparent (make regions outside the footprint completely transparent,
and add an alpha channel if one is not already present). Defaults to None.
Sets the transparent color of the granules prior to processing by the ImageMosaic plugin, in order to control how they are superimposed. When
GeoServer composes the granules to satisfy a user request, some can
overlap others; setting this parameter with an appropriate color avoids
the overlap of “nodata” areas between granules. See below for an example:

Fig. 5.70: InputTransparentColor parameter not configured
Sets the maximum number of tiles that can be loaded simultaneously for a
request. For large mosaics, this parameter should be set to avoid saturating
the server by loading too many granules simultaneously.
The method used to handle overlapping granules during the mosaic operation. Can be FLAT (only the topmost granule is visible in the case of an overlap) or STACK (a band-stacking merge is applied to the overlapping granules).
Default is FLAT.
Set the transparent color for the mosaic.
This parameter make sense for RGB or paletted mosaics,
but not99
for a DEM or MetOc data.
See below for an example:

Fig. 5.7

GeoServer User Manual, Release 2.15.1

Continue on with the ImageMosaic tutorial to learn more and see examples.
Using the ImageMosaic extension
This tutorial will show you how to configure and publish an ImageMosaic store and coverage, followed by
some configuration examples.
Configuring a coverage in GeoServer
This is a process very similar to creating a featuretype. More specifically, one has to perform the steps
highlighted in the sections below:
Create a new store
1. Go to Data Panel → Stores and click Add new Store.
2. Select ImageMosaic under Raster Data Source:

Fig. 5.74: ImageMosaic in the list of raster data stores
3. In order to create a new mosaic it is necessary to choose a workspace and store name in the Basic Store
Info section, as well as a URL in the Connection Parameters section. Valid URLs include:
• The absolute path to the shapefile index, or a directory containing the shapefile index.
• The absolute path to the configuration file (*.properties‘) or a directory containing the configuration file. If datastore.properties and indexer.properties exist, they should be in the
same directory as this configuration file.
• The absolute path of a directory where the files you want to mosaic reside. In this case GeoServer
automatically creates the needed mosaic files (.dbf, .prj, .properties, .shp and .shx) by inspecting
the data present in the given directory and any subdirectories.
4. Click Save:
Create a new coverage
1. Navigate to Data Panel → Layers and click Add a new resource.
2. Choose the name of the store you just created:
3. Click the layer you wish to configure and you will be presented with the Coverage Editor:
4. Make sure there is a value for Native SRS, then click the Submit button. If the Native CRS is UNKNOWN,
you must declare the SRS in the Declared SRS field.
5. Click Save.
6. Use the Layer Preview to view the mosaic.

100

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.75: Configuring an ImageMosaic data store

Fig. 5.76: Layer Chooser

5.3. Raster data

101

GeoServer User Manual, Release 2.15.1

Fig. 5.77: Coverage Editor

102

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Warning: If the created layer appears to be all black, it may be that GeoServer has not found any
acceptable granules in the provided index. It is also possible that the shapefile index is empty (no
granules were found in the provided directory) or it might be that the granules’ paths in the shapefile
index are not correct, which could happen if an existing index (using absolute paths) is moved to another
place. If the shapefile index paths are not correct, then the DBF file can be opened and fixed with an
editor. Alternately, you can delete the index and let GeoServer recreate it from the root directory.

Configuration examples
Below are a few examples of mosaic configurations to demonstrate how we can make use of the ImageMosaic parameters.
DEM/Bathymetry
Such a mosaic can be used to serve large amounts of data representing altitude or depth and therefore does
not specify colors directly (it needs an SLD to generate pictures). In our case, we have a DEM dataset which
consists of a set of raw GeoTIFF files.
The first operation is to create the CoverageStore specifying, for example, the path of the shapefile in the
URL field.
Inside the Coverage Editor Publishing tab, you can specify the dem default style in order to represent the
visualization style of the mosaic. The following is an example style:



gtopo

dem
Simple DEM style
Classic elevation color progression



1.0













5.3. Raster data

103

GeoServer User Manual, Release 2.15.1





In this way you have a clear distinction between the different intervals of the dataset that compose the
mosaic, like the background and the “nodata” area.

Note: The “nodata” on the sample mosaic is -9999. The default background value is for mosaics is 0.0.
The result is the following:
By setting the other configuration parameters appropriately, it is possible to improve both the appearance
of the mosaic as well as its performance. For instance, we could:
• Make the “nodata” areas transparent and coherent with the real data. To achieve this we need
to change the opacity of the “nodata” ColorMapEntry in the dem style to 0.0 and set the
BackgroundValues parameter to -9999 so that empty areas will be filled with this value. The
result is as follows:
• Allow multithreaded granules loading. By setting the AllowMultiThreading parameter to true,
GeoServer will load the granules in parallel using multiple threads with a increase in performance on
some architectures.
The configuration parameters are as follows:
104

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.78: Basic configuration

Fig. 5.79: Advanced configuration

5.3. Raster data

105

GeoServer User Manual, Release 2.15.1

Parameter
Value
MaxAllowedTiles
2147483647
BackgroundValues
-9999
OutputTransparentColor “no color”
InputTransparentColor
“no color”
AllowMultiThreading
True
USE_JAI_IMAGEREAD True
SUGGESTED_TILE_SIZE512,512

Aerial imagery
In this example we are going to create a mosaic that will serve aerial imagery, specifically RGB GeoTIFFs.
Because this is visual data, in the Coverage Editor you can use the basic raster style, which is just a stub
SLD to instruct the GeoServer raster renderer to not do anything particular in terms of color management:



raster

raster
Raster
A sample style for rasters, good for displaying imagery


Feature


1.0







The result is the following:
Note: Those ugly black areas are the result of applying the default mosaic parameters to a mosaic that does
not entirely cover its bounding box. The areas within the BBOX that are not covered with data will default
to a value of 0 on each band. Since this mosaic is RGB we can simply set the OutputTransparentColor
to 0,0,0 in order to get transparent fills for the BBOX.
The various parameters can be set as follows:

106

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.80: Basic configuration

Parameter
Value
MaxAllowedTiles
2147483647
BackgroundValues
(default)
OutputTransparentColor #000000
InputTransparentColor
“no color”
AllowMultiThreading
True
USE_JAI_IMAGEREAD True
SUGGESTED_TILE_SIZE512,512
The result is the following:

Fig. 5.81: Advanced configuration

Scanned maps
In this case we want to show how to serve scanned maps (mostly B&W images) via a GeoServer mosaic.

5.3. Raster data

107

GeoServer User Manual, Release 2.15.1

In the Coverage Editor you can use the basic raster since there is no need to use any of the advanced
RasterSymbolizer capabilities.
The result is the following.

Fig. 5.82: Basic configuration
This mosaic, formed by two single granules, shows a typical case where the “nodata” collar areas of the
granules overlap, as shown in the picture above. In this case we can use the InputTransparentColor
parameter to make the collar areas disappear during the superimposition process — in this case, by using
an InputTransparentColor of #FFFFFF.
The final configuration parameters are the following:
Parameter
Value
MaxAllowedTiles
2147483647
BackgroundValues
(default)
OutputTransparentColor “no color”
InputTransparentColor
#FFFFFF
AllowMultiThreading
True
USE_JAI_IMAGEREAD True
SUGGESTED_TILE_SIZE512,512
This is the result:

Fig. 5.83: Advanced configuration

Dynamic imagery
A mosaic need not be static. It can contain granules which change, are added or deleted. In this example,
we will create a mosaic that changes over time.
108

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

1. Create a mosaic in the standard way. (The specific configuration isn’t important.)

Fig. 5.84: This mosaic contains 5 granules. Note that InputTransparentColor is set to #FFFFFF here.
To add new granules, the index that was created when the mosaic was originally created needs to be regenerated. There are two ways to do this:
• Manually through the file system
• Through the REST interface
To update an ImageMosaic through the file system:
1. Update the contents of the mosaic by copying the new files into place. (Subdirectories are acceptable.)
2. Delete the index files. These files are contained in the top level directory containing the mosaic files
and include (but are not limited to) the following:
• .dbf
• .fix
• .prj
• .properties
• .shp
• .shx
3. (Optional but recommended) Edit the layer definition in GeoServer, making to sure to update the bounding box information (if changed).
4. Save the layer. The index will be recreated.
Note: Please see the REST section for information on Uploading a new image mosaic.

Multi-resolution imagery with reprojection
As a general rule, we want to have the highest resolution granules shown “on top”, with the lowerresolution granules filling in the gaps as necessary.

5.3. Raster data

109

GeoServer User Manual, Release 2.15.1

Fig. 5.85: This mosaic contains 9 granules
In this example, we will serve up overlapping granules that have varying resolutions. In addition, we will
mix resolutions, such that the higher resolution granule is reprojected to match the resolution of the lower
resolution granules.
1. In the Coverage Editor, use the basic raster style.
2. Create the mosaic in GeoServer.
3. One important configuration setting is the SORTING parameter of the layer. In order to see the highest
resolution imagery on top (the typical case), it must be set to resolution A. (For the case of lowest
resolution on top, use resolution D .)
4. Make any other configuration changes.
5. Also, in order to allow for multiple CRSs in a single mosaic, an indexer.properties file will need
to be created. Use the following
GranuleAcceptors=org.geotools.gce.imagemosaic.acceptors.
,→HeterogeneousCRSAcceptorFactory
GranuleHandler=org.geotools.gce.imagemosaic.granulehandler.
,→ReprojectingGranuleHandlerFactory
HeterogeneousCRS=true
MosaicCRS=EPSG\:4326
PropertyCollectors=CRSExtractorSPI(crs),ResolutionExtractorSPI(resolution)
Schema=*the_geom:Polygon,location:String,crs:String,resolution:String

The MosaicCRS property is not mandatory, but it’s a good idea to set a predictable target CRS that
all granule footprints can be reprojected into, otherwise the mosaic machinery will use the CRS of the
first indexed granule.
6. Save this file in the root of the mosaic directory (along with the index files). The result is the following:

110

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.86: Closeup of granule overlap (high resolution granule on right)
7. To remove the reprojection artifact (shown in the above as a black area) edit the layer configuration to
set InputTransparentColor to #000000.
Referring to a datastore configured in GeoServer
It is possible to make the mosaic refer to an existing data store. The “datastore.properties“ file in this case
will contain only one or two properties, referring to the store to be used via the StoreName property. For
simple cases, e.g., a PostGIS store, the following will be sufficient:
StoreName=workspace:storename

For Oracle or H2, it’s best to also specify the SPI in order to inform the mosaic that it needs to work around
specific limitations of the storage (e.g., forced uppercase attribute usage, limitation in attribute name length
5.3. Raster data

111

GeoServer User Manual, Release 2.15.1

Fig. 5.87: Closeup of granule overlap (high resolution granule on right)

112

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

and the like):
StoreName=workspace:storename
SPI=org.geotools.data.oracle.OracleNGDataStoreFactory

The above will be sufficient in case the image mosaic can create the index table and perform normal indexing, using the directory name as the table name. In case a specific table name needs to be used, add an
“indexer.properties“ specifying the TypeName property, e.g.:
TypeName=myMosaicTypeName
In case the index “table” already exists instead, then a “indexer.properties“ file will be required, with the
following contents:
UseExistingSchema=true
TypeName=nameOfTheFeatureTypeContainingTheIndex
AbsolutePath=true

The above assumes location attribute provides absolute paths to the mosaic granules, instead of paths
relative to the mosaic configuration files directory.

5.3.5 GeoPackage
GeoPackage is an SQLite based standard format that is able to hold multiple vector and raster data layers
in a single file.
GeoPackage files can be used both as Vector Data Stores as well as Raster Data Stores (so that both kinds of
layers can published).
Adding a GeoPackage Raster (Mosaic) Data Store
By default, GeoPackage (mosaic) will be an option in the Raster Data Sources list when creating a new data
store.

Fig. 5.88: GeoPackage (mosaic) in the list of raster data stores

Option
Workspace
Data Source
Name
Description
Enabled
URL

Description
Name of the workspace to contain the GeoPackage Mosaic store. This will also be
the prefix of the raster layers created from the store.
Name of the GeoPackage Mosaic Store as it will be known to GeoServer. This can
be different from the filename. )
A full free-form description of the GeoPackage Mosaic Store.
If checked, it enables the store. If unchecked (disabled), no data in the GeoPackage
Mosaic Store will be served from GeoServer.
Location of the GeoPackage file. This can be an absolute path (such as
file:C:\Data\landbase.gpkg) or a path relative to GeoServer’s data directory (such as file:data/landbase.gpkg).

When finished, click Save.

5.3. Raster data

113

GeoServer User Manual, Release 2.15.1

Fig. 5.89: Configuring a GeoPackage (mosaic) data store
Other data sources are supplied as GeoServer extensions. Extensions are downloadable modules that add
functionality to GeoServer. Extensions are available at the GeoServer download page.
Warning: The extension version must match the version of the GeoServer instance.

5.3.6 ArcGrid
ArcGrid is a coverage file format created by ESRI.
Adding an ArcGrid data store
By default, ArcGrid will be an option in the Raster Data Sources list when creating a new data store.

Fig. 5.90: ArcGrid in the list of raster data stores

Configuring a ArcGrid data store
Option
Workspace
Data Source
Name
Description
Enabled
URL

114

Description

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.91: Configuring an ArcGrid data store

5.3.7 GDAL Image Formats
GeoServer can leverage the ImageI/O-Ext GDAL libraries to read selected coverage formats. GDAL is able
to read many formats, but for the moment GeoServer supports only a few general interest formats and
those that can be legally redistributed and operated in an open source server.
The following image formats can be read by GeoServer using GDAL:
• DTED, Military Elevation Data (.dt0, .dt1, .dt2): http://www.gdal.org/frmt_dted.html
• EHdr, ESRI .hdr Labelled: 
• ENVI, ENVI .hdr Labelled Raster: 
• HFA, Erdas Imagine (.img): 
• JP2MrSID, JPEG2000 (.jp2, .j2k): 
• MrSID, Multi-resolution Seamless Image Database: 
• NITF: 
• ECW, ERDAS Compressed Wavelets (.ecw): 
• JP2ECW, JPEG2000 (.jp2, .j2k): http://www.gdal.org/frmt_jp2ecw.html
• AIG, Arc/Info Binary Grid: 
• JP2KAK, JPEG2000 (.jp2, .j2k): 
Installing GDAL extension
From GeoServer version 2.2.x, GDAL must be installed as an extension. To install it:
• Navigate to the GeoServer download page

5.3. Raster data

115

GeoServer User Manual, Release 2.15.1

• Find the page that matches the version of the running GeoServer.
Warning: Be sure to match the version of the extension with that of GeoServer, otherwise errors will occur.
• Download the GDAL extension. The download link for GDAL will be in the Extensions section under
Coverage Format.

• Extract the files in this archive to the WEB-INF/lib directory of your GeoServer installation. On
Windows You may be prompted for confirmation to overwrite existing files, confirm the replacement
of the files
Moreover, in order for GeoServer to leverage these libraries, the GDAL (binary) libraries must be installed
through your host system’s OS. Once they are installed, GeoServer will be able to recognize GDAL data
types. See below for more information.
Installing GDAL native libraries
The ImageIO-Ext GDAL plugin for geoserver master uses ImageIO-Ext whose latest artifacts can be downloaded from here.
Browse to the native and then gdal directory for the Image IO-Ext download link. Now you should see a
list of artifacts that can be downloaded. We need to download two things now:

116

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

5.3. Raster data

117

GeoServer User Manual, Release 2.15.1

1. The CRS definitions
2. The native libraries matching the target operating system (more details on picking the right one for
your windows installation in the “Extra Steps for Windows Platforms” section)
Let’s now install the CRS definitions.
• Click on the “gdal_data.zip” to download the CRS definitions archive.
• Extract this archive on disk and place it in a proper directory on your system.
• Create a GDAL_DATA environment variable to the folder where you have extracted this file. Make
also sure that this directory is reachable and readable by the application server process’s user.
We now have to install the native libraries.
• Assuming you are using a 64 bit Ubuntu 11 Linux Operating System (for instance), click on the
linux folder and then on “gdal192-Ubuntu11-gcc4.5.2-x86_64.tar.gz” to download the native libraries
archive (Before doing this, make sure to read and agree with the ECWEULA if you intend to use
ECW).
• If you are using a Windows Operating System make sure to download the archive matching your
Microsoft Visual C++ Redistributables and your architecture. For example on a 64 bit Windows with
2010 Redistributables, download the gdal-1.9.2-MSVC2010-x64.zip archive
• Extract the archive on disk and place it in a proper directory on your system.
Warning:
If you are using a version of GDAL more recent than 1.9.2, replace the
imageio-ext-gdal-bindings-1.9.2.jar file with the equivalent java binding jar (typically named either gdal.jar or imageio-ext-gdal-bindings-*.jar) included with
your GDAL version. If your GDAL version does not include a bindings jar, it was probably
not compiled with the java bindings and will not work with GeoServer.

Warning: If you are on Windows, make sure that the GDAL DLL files are on your PATH. If
you are on Linux, be sure to set the LD_LIBRARY_PATH environment variable to refer to the
folder where the SOs are extracted.

Note: The native libraries contains the GDAL gdalinfo utility which can be used to test whether
or not the libs are corrupted. This can be done by browsing to the directory where the libs have
been extracted and performing a gdalinfo command with the formats options that shows all the
formats supported. The key element of GDAL support in GeoServer is represented by the JAVA
bindings. To test the bindings, the package contains a Java version of the gdalinfo utility inside
the “javainfo” folder (a .bat script for Windows and a .sh for Linux), it is very important to run
it (again, with the formats options) to make sure that the Java bindings are working properly
since that is what GeoServer uses. An error message like Can’t load IA 32-bit .dll on a AMD 64-bit
platform in the log files indicates a mixed version of the tools, please go through the installation
process again and pick the appropriate versions. More details on troubleshooting are provided
in the Note on running GeoServer as a Service on Windows section below.
Once these steps have been completed, restart GeoServer. If all the steps have been performed correctly,
new data formats will be in the Raster Data Sources list when creating a new data store in the Stores section
as shown here below.
If new formats do not appear in the GUI and you see the following message in the log file:

118

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.92: GDAL image formats in the list of raster data stores

5.3. Raster data

119

GeoServer User Manual, Release 2.15.1

it.geosolutions.imageio.gdalframework.GDALUtilities
loadGDAL
failed.java.lang.UnsatisfiedLinkError: no gdaljni in java.library.path

WARNING:

Native

library

load

that means that the installations failed for some reason.
Extra Steps for Windows Platforms
There are a few things to be careful with as well as some extra steps if you are deploying on Windows.
As stated above, we have multiple versions like MSVC2005, MSVC2008 and so on matching the Microsoft
Visual C++ Redistributables. Depending on the version of the underlying operating system you’ll have to
pick up the right one. You can google around for the one you need. Also make sure you download the
32 bit version if you are using a 32 bit version of Windows or the 64 bit version (has a “-x64” suffix in the
name of the zip file) if you are running a 64 bit version of Windows. Again, pick the one that matches your
infrastructure.
Note on running GeoServer as a Service on Windows
Note that if you downloaded an installed GeoServer as a Windows service you installed the 32 bit version.
Simply deploying the GDAL ImageI/O-Ext native libraries in a location referred by the PATH environment
variable (like, as an instance, the JDK/bin folder) doesn’t allow GeoServer to leverage on GDAL, when run
as a service. As a result, during the service startup, GeoServer log reports this worrisome message:
it.geosolutions.imageio.gdalframework.GDALUtilities
loadGDAL
failed.java.lang.UnsatisfiedLinkError: no gdaljni in java.library.path

WARNING:

Native

library

load

Taking a look at the wrapper.conf configuration file available inside the GeoServer installation (at
bin/wrapper/wrapper.conf), there is this useful entry:
#
Java
Library
Path
(location
per.java.library.path.1=bin/wrapper/lib

of

Wrapper.DLL

or

libwrapper.so)

wrap-

To allow the GDAL native DLLs to be loaded, you have two options:
1. Move the native DLLs to the referenced path (bin/wrapper/lib)
2. Add a wrapper.java.library.path.2=path/where/you/deployed/nativelibs entry just after the wrapper.java.library.path1=bin/wrapper/lib line.
Adding support for ECW and MrSID on Windows
If you are on Windows and you want to add support for ECW and MrSID there is an extra step to perform.
Download and install ECW and MrSID from GeoSolutions site
In the Windows packaging ECW and MrSID are built as plugins hence they are not loaded by default but
we need to place their DLLs in a location that is pointed to by the GDAL_DRIVER_PATH environment
variable. By default the installer place the plugins in C:\Program Files\GDAL\gdalplugins.
GDAL internally uses an environment variable to look up additional drivers (notice that there are a few
default places where GDAL will look anyway). For additional information, please see the GDAL wiki.
Restart GeoServer, you should now see the new data sources available

120

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

5.3. Raster data

121

GeoServer User Manual, Release 2.15.1

Fig. 5.93: Configuring a DTED data store
Configuring a DTED data store
Configuring a EHdr data store
Configuring a ERDASImg data store
Configuring a JP2MrSID data store
Configuring a NITF data store
Supporting vector footprints
Starting with version 2.9.0, GeoServer supports vector footprints. A footprint is a shape used as a mask
to hide those pixels that are outside of the mask, hence making that part of the parent image transparent.
The currently supported footprint formats are WKB, WKT and Shapefile. By convention, the footprint file
should be located in the same directory as the raster data that the footprint applies to.
Note: In the examples of this section and related subsections, we will always use .wkt as extension, representing a WKT footprint, although both .wkb and .shp are supported too.
For example, supposing you have a MrSID file located at /mnt/storage/data/landsat/
N-32-40_2000.sid to be masked, you just need to place a WKT file on the same folder, as /mnt/
storage/data/landsat/N-32-40_2000.wkt Note that the footprint needs to have same path and
name of the original data file, with .wkt extension.
This is how the sample footprint geometry looks:
Once footprint file has been added, you need to change the FootprintBehavior parameter from None (the
default value) to Transparent, from the layer configuration.

122

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.94: Configuring a EHdr data store

Fig. 5.95: Configuring a ERDASImg data store

5.3. Raster data

123

GeoServer User Manual, Release 2.15.1

Fig. 5.96: Configuring a JP2MrSID data store

Fig. 5.97: Configuring a NITF data store

124

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.98: A sample geometry stored as WKT, rendered on OpenJump

Fig. 5.99: Setting the FootprintBehavior parameter
The next image depicts 2 layer previews for the same layer: the left one has no footprint, the right one has
a footprint available and FootprintBehavior set to transparent.

Fig. 5.100: No Footprint VS FootprintBehavior = Transparent

External Footprints data directory
As noted above, the footprint file should be placed in the same directory as the raster file. However in some
cases this may not be possible. For example, the folder containing the raster data may be read only.
As an alternative, footprint files can be located in a common directory, the footprints data directory. The
subdirectories and file names under that directory must match the original raster path and file names. The
footprints data directory is specified as a Java System Property or an Environment Variable, by setting the
FOOTPRINTS_DATA_DIR property/variable to the directory to be used as base folder.
Example
Suppose you have 3 raster files with the following paths:
• /data/raster/charts/nitf/italy_2015.ntf

5.3. Raster data

125

GeoServer User Manual, Release 2.15.1

• /data/raster/satellite/ecw/orthofoto_2014.ecw
• /data/raster/satellite/landsat/mrsid/N-32-40_2000.sid
They can be represented by this tree:
/data
\---raster
+---charts
|
\---nitf
|
italy_2015.ntf
|
\---satellite
+---ecw
|
orthofoto_2014.ecw
|
\---landsat
\---mrsid
N-32-40_2000.sid

In order to support external footprints you should
1. Create a /footprints (as an example) directory on disk
2. Set the FOOTPRINTS_DATA_DIR=/footprints variable/property.
3. Replicate the rasters folder hierarchy inside the specified folder, using the full paths.
4. Put the 3 WKT files in the proper locations:
• /footprints/data/raster/charts/nitf/italy_2015.wkt
• /footprints/data/raster/satellite/ecw/orthofoto_2014.wkt
• /footprints/data/raster/satellite/landsat/mrsid/N-32-40_2000.wkt
Which can be represented by this tree:
/footprints
\---data
\---raster
+---charts
|
\---nitf
|
italy_2015.wkt
|
\---satellite
+---ecw
|
orthofoto_2014.wkt
|
\---landsat
\---mrsid
N-32-40_2000.wkt

Such that, in the end, you will have the following folders hierarchy tree:
+---data
|
\---raster
|
+---charts
|
|
\---nitf
|
|
italy_2015.ntf
|
|
|
\---satellite

126

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

|
+---ecw
|
|
orthofoto_2014.ecw
|
|
|
\---landsat
|
\---mrsid
|
N-32-40_2000.sid
|
\---footprints
\---data
\---raster
+---charts
|
\---nitf
|
italy_2015.wkt
|
\---satellite
+---ecw
|
orthofoto_2014.wkt
|
\---landsat
\---mrsid
N-32-40_2000.wkt

Note the parallel mirrored folder hierarchy, with the only differences being a /footprints prefix at the
beginning of the path, and the change in suffix.

5.3.8 Oracle Georaster
Note: GeoServer does not come built-in with support for Oracle Georaster; it must be installed through
an extension. Proceed to Image Mosaic JDBC for installation details. This extension includes the support for
Oracle Georaster.

Adding an Oracle Georaster data store
Read the geotools documentation for Oracle Georaster Support: http://docs.geotools.org/latest/
userguide/library/coverage/oracle.html. After creating the xml config file proceed to the section Configuring GeoServer in the Image Mosaic JDBC Tutorial

5.3.9 Postgis Raster
Note: GeoServer does not come built-in with support for Postgis raster columns, it must be installed
through an extension. Proceed to Image Mosaic JDBC for installation details. This extension includes the
support for Postgis raster.

Adding an Postgis raster data store
Read the geotools documentation for Postgis raster Support: http://docs.geotools.org/latest/userguide/
library/coverage/pgraster.html. After creating the xml config file proceed to the section Configuring
GeoServer in the Image Mosaic JDBC Tutorial
5.3. Raster data

127

GeoServer User Manual, Release 2.15.1

5.3.10 ImagePyramid
Note: GeoServer does not come built-in with support for Image Pyramid; it must be installed through an
extension. Proceed to Installing the ImagePyramid extension for installation details.
An image pyramid is several layers of an image rendered at various image sizes, to be shown at different
zoom levels.
Installing the ImagePyramid extension
1. Download the ImagePyramid extension from the GeoServer download page.
Warning: Make sure to match the version of the extension to the version of the GeoServer instance!
2. Extract the contents of the archive into the WEB-INF/lib directory of the GeoServer installation.
Adding an ImagePyramid data store
Once the extension is properly installed ImagePyramid will be an option in the Raster Data Sources list when
creating a new data store.

Fig. 5.101: ImagePyramid in the list of raster data stores

Configuring an ImagePyramid data store
Option
Workspace
Data Source
Name
Description
Enabled
URL

Description

5.3.11 Image Mosaic JDBC
Note: GeoServer does not come built-in with support for Image Mosaic JDBC; it must be installed through
an extension. Proceed to Installing the JDBC Image Mosaic extension for installation details.

128

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.102: Configuring an ImagePyramid data store
Installing the JDBC Image Mosaic extension
1. Download the JDBC Image Mosaic extension from the GeoServer download page.
Warning: Make sure to match the version of the extension to the version of the GeoServer instance!
2. Extract the contents of the archive into the WEB-INF/lib directory of the GeoServer installation.
Adding an Image Mosaic JDBC data store
Once the extension is properly installed Image Mosaic JDBC will be an option in the Raster Data Sources list
when creating a new data store.

Fig. 5.103: Image Mosaic JDBC in the list of vector data stores

Configuring an Image Mosaic JDBC data store
For a detailed description, look at the Tutorial

5.3.12 Custom JDBC Access for image data

5.3. Raster data

129

GeoServer User Manual, Release 2.15.1

Fig. 5.104: Configuring an Image Mosaic JDBC data store

Note: GeoServer does not come built-in with support for Custom JDBC Access; it must be installed through
an extension. Proceed to Image Mosaic JDBC for installation details. This extension includes the support for
Custom JDBC Access.

Adding a coverage based on Custom JDBC Access
This extension is targeted to users having a special database layout for storing their image data or use a
special data base extension concerning raster data.
Read the geotools documentation for Custom JDBC Access: http://docs.geotools.org/latest/userguide/
library/coverage/jdbc/customized.html.
After developing the custom plugin, package the classes into a jar file and copy it into the WEB-INF/lib
directory of the geoserver installation.
Create the xml config file and proceed to the section Configuring GeoServer in the Image Mosaic JDBC Tutorial
GeoServer provides extensive facilities for controlling how rasters are accessed. These are covered in the
following sections.

5.3.13 Coverage Views
Starting with GeoServer 2.6.0, You can define a new raster layer as a Coverage View. Coverage Views allow
defining a View made of different bands originally available inside coverages (either bands of the same
coverage or different coverages) of the same Coverage Store.

130

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Creating a Coverage View
In order to create a Coverage View the administrator invokes the Create new layer page. When a Coverage
store is selected, the usual list of coverages available for publication appears. A link Configure new Coverage
view. . . also appears:

Selecting the Configure new Coverage view. . . link opens a new page where you can configure the coverage
view:

The upper text box allows to specify the name to be assigned to this coverage view. (In the following picture
we want to create as example, a currents view merging together both u and v components of the currents,
which are exposed as separated 1band coverages).

Next step is defining the output bands to be put in the coverage view. It is possible to specify which input
coverage bands need to be put on the view by selecting them from the Composing coverages/bands. . . .
Once selected, they needs to be added to the output bands of the coverage view, using the add button.
Optionally, is it possible to remove the newly added bands using the remove and remove all buttons. Once
done, clicking on the save button will redirect to the standard Layer configuration page.
Scrolling down to the end of the page, is it possible to see the bands composing the coverage (and verify
they are the one previously selected).
At any moment, the Coverage View can be refined and updated by selecting the Edit Coverage view. . . link
available before the Coverage Bands details section.

5.3. Raster data

131

GeoServer User Manual, Release 2.15.1

132

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Once all the properties of the layer have been configured, by selecting the Save button, the coverage will be
saved in the catalog and it will become visible as a new layer.

Heterogeneous coverage views
In case the various coverages bound in the view have different resolution, the UI will present two extra
controls:

The coverage envelope policy defines how the bounding box of the output is calculated for metadata
purposes. Having different resolutions, the coverages are unlikely to share the same bounding box. The
possible values are:
• Intersect envelopes: Use the intersection of all input coverage envelopes
• Union envelopes: Use the union of all input coverage envelopes
The coverage resolution policy defines which target resolution is used when generating outputs:
• Best: Use the best resolution available among the chosen bands (e.g., in a set having 60m, 20m and
10m the 10m resolution will be chosen)
• Worst: Use the worst resolution available among the chosen bands (e.g., in a set having 60m, 20m and
10m the 60m resolution will be chosen)
The coverage resolution policy is context sensitive. Assume the input is a 12 bands Sentinel 2 dataset at
three different resolution, 10, 20 and 30 meters, and a false color image is generated by performing a band
selection in the SLD. If the policy is best and the SLD selects only bands at 20 and 60 meters, the output will
be at 20 meters instead of 10 meters.
Coverage View in action
A Layer preview of the newly created coverage view will show the rendering of the view. Note that clicking
on a point on the map will result into a GetFeatureInfo call which will report the values of the bands
composing the coverage view.

5.4 Databases
This section discusses the database data sources that GeoServer can access.
The standard GeoServer installation supports accessing the following databases:
5.4. Databases

133

GeoServer User Manual, Release 2.15.1

5.4.1 PostGIS
PostGIS is an open source spatial database based on PostgreSQL, and is currently one of the most popular
open source spatial databases today.
Adding a PostGIS database
As with all formats, adding a shapefile to GeoServer involves adding a new store to the existing Stores
through the Web administration interface.
Using default connection
To begin, navigate to Stores → Add a new store → PostGIS NG.

134

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.105: Adding a PostGIS database

5.4. Databases

135

GeoServer User Manual, Release 2.15.1

Option
Workspace
Data Source Name
Description
Enabled
dbtype
host
port
database
schema
user
passwd
namespace
max connections
min connections
fetch size
Connection timeout
validate connections
Loose bbox
preparedStatements

Description
Name of the workspace to contain the database. This will also be the prefix of any
layer names created from tables in the database.
Name of the database. This can be different from the name as known to PostgreSQL/PostGIS.
Description of the database/store.
Enables the store. If disabled, no data in the database will be served.
Type of database. Leave this value as the default.
Host name where the database exists.
Port number to connect to the above host.
Name of the database as known on the host.
Schema in the above database.
User name to connect to the database.
Password associated with the above user.
Namespace to be associated with the database. This field is altered by changing the
workspace name.
Maximum amount of open connections to the database.
Minimum number of pooled connections.
Number of records read with each interaction with the database.
Time (in seconds) the connection pool will wait before timing out.
Checks the connection is alive before using it.
Performs only the primary filter on the bounding box. See the section on Using
loose bounding box for details.
Enables prepared statements.

When finished, click Save.
Using JNDI
GeoServer can also connect to a PostGIS database using JNDI (Java Naming and Directory Interface).
To begin, navigate to Stores → Add a new store → PostGIS NG (JNDI).
Option
Workspace
Data Source Name
Description
Enabled
dbtype
jndiReferenceName
schema
namespace

Description
Name of the workspace to contain the store. This will also be the prefix of all of the
layer names created from the store.
Name of the database. This can be different from the name as known to PostgreSQL/PostGIS.
Description of the database/store.
Enables the store. If disabled, no data in the database will be served.
Type of database. Leave this value as the default.
JNDI path to the database.
Schema for the above database.
Namespace to be associated with the database. This field is altered by changing the
workspace name.

When finished, click Save.

136

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.106: Adding a PostGIS database (using JNDI)

5.4. Databases

137

GeoServer User Manual, Release 2.15.1

Configuring PostGIS layers
When properly loaded, all tables in the database will be visible to GeoServer, but they will need to be
individually configured before being served by GeoServer. See the section on Layers for how to add and
edit new layers.
Using loose bounding box
When the option loose bbox is enabled, only the bounding box of a geometry is used. This can result in
a significant performance gain, but at the expense of total accuracy; some geometries may be considered
inside of a bounding box when they are technically not.
If primarily connecting to this data via WMS, this flag can be set safely since a loss of some accuracy is
usually acceptable. However, if using WFS and especially if making use of BBOX filtering capabilities, this
flag should not be set.
Publishing a PostGIS view
Publishing a view follows the same process as publishing a table. The only additional step is to manually
ensure that the view has an entry in the geometry_columns table.
For example consider a table with the schema:
my_table( id int PRIMARY KEY, name VARCHAR, the_geom GEOMETRY )

Consider also the following view:
CREATE VIEW my_view as SELECT id, the_geom FROM my_table;

Before this view can be served by GeoServer, the following step is necessary to manually create the
geometry_columns entry:
INSERT INTO geometry_columns VALUES ('','public','my_view','my_geom', 2, 4326, 'POINT
,→' );

Performance considerations
GEOS
GEOS (Geometry Engine, Open Source) is an optional component of a PostGIS installation. It is recommended that GEOS be installed with any PostGIS instance used by GeoServer, as this allows GeoServer to
make use of its functionality when doing spatial operations. When GEOS is not available, these operations
are performed internally which can result in degraded performance.
Spatial indexing
It is strongly recommended to create a spatial index on tables with a spatial component (i.e. containing a
geometry column). Any table of which does not have a spatial index will likely respond slowly to queries.

138

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Common problems
Primary keys
In order to enable transactional extensions on a table (for transactional WFS), the table must have a primary
key. A table without a primary key is considered read-only to GeoServer.
GeoServer has an option to expose primary key values (to make filters easier). Please keep in mind that
these values are only exposed for your convenience - any attempted to modify these values using WFS-T
update will be silently ignored. This restriction is in place as the primary key value is used to define the
FeatureId. If you must change the FeatureId you can use WFS-T delete and add in a single Transaction
request to define a replacement feature.
Multi-line
To insert multi-line text (for use with labeling) remember to use escaped text:
INSERT INTO place VALUES (ST_GeomFromText('POINT(-71.060316 48.432044)', 4326), E
,→'Westfield\nTower');

5.4.2 H2
Note: GeoServer does not come built-in with support for H2; it must be installed through an extension.
Proceed to Installing the H2 extension for installation details.

Installing the H2 extension
1. Download the H2 extension from the GeoServer download page.
Warning: Make sure to match the version of the extension to the version of the GeoServer instance!
2. Extract the contents of the archive into the WEB-INF/lib directory of the GeoServer installation.
Adding an H2 data store
Once the extension is properly installed H2 will be an option in the Vector Data Sources list when creating a
new data store.

Fig. 5.107: H2 in the list of vector data stores

5.4. Databases

139

GeoServer User Manual, Release 2.15.1

Configuring an H2 data store

Fig. 5.108: Configuring an H2 data store

Configuring an H2 data store with JNDI
Other data sources are supplied as GeoServer extensions. Extensions are downloadable modules that add
functionality to GeoServer. Extensions are available at the GeoServer download page.
Warning: The extension version must match the version of the GeoServer instance.

5.4.3 ArcSDE
Note: ArcSDE support is not enabled by default and requires the ArcSDE extension to be installed prior to
use. Please see the section on Installing the ArcSDE extension for details.

140

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

ESRI’s ArcSDE is a spatial engine that runs on top of a relational database such as Oracle or SQL Server.
GeoServer with the ArcSDE extension supports ArcSDE versions 9.2 and 9.3. It has been tested with Oracle
10g and Microsoft SQL Server 2000 Developer Edition. The ArcSDE extension is based on the GeoTools
ArcSDE driver and uses the ESRI Java API libraries. See the GeoTools ArcSDE page for more technical
details.
There are two types of ArcSDE data that can be added to GeoServer: vector and raster.
Vector support
ArcSDE provides efficient access to vector layers, (“featureclasses” in ArcSDE jargon), over a number of
relational databases. GeoServer can set up featuretypes for registered ArcSDE featureclasses and spatial
views. For versioned ArcSDE featureclasses, GeoServer will work on the default database version, for both
read and write access.
Transactional support is enabled for featureclasses with a properly set primary key, regardless if the featureclass is managed by a user or by ArcSDE. If a featureclass has no primary key set, it will be available as
read-only.
Raster support
ArcSDE provides efficient access to multi-band rasters by storing the raw raster data as database blobs,
dividing it into tiles and creating a pyramid. It also allows a compression method to be set for the tiled blob
data and an interpolation method for the pyramid resampling.
All the bands comprising a single ArcSDE raster layer must have the same pixel depth, which can be one
of 1, 4, 8, 16, and 32 bits per sample for integral data types. For 8, 16 and 32 bit bands, they may be signed
or unsigned. 32 and 64 bit floating point sample types are also supported.
ArcSDE rasters may also be color mapped, as long as the raster has a single band of data typed 8 or 16 bit
unsigned.
Finally, ArcSDE supports raster catalogs. A raster catalog is a mosaic of rasters with the same spectral
properties but instead of the mosaic being precomputed, the rasters comprising the catalog are independent
and the mosaic work performed by the application at runtime.
Technical Detail
Compression
methods
Number of bands
Bit
depth
for
color-mapped
rasters
Raster Catalogs

Status
LZW, JPEG
Any number of bands except for 1 and 4 bit rasters (supported for single-band
only).
8 bit and 16 bit

Any pixel storage type

Installing the ArcSDE extension

Warning: Due to licensing requirements, not all files are included with the extension. To install ArcSDE
support, it is necessary to download additional files. Just installing the ArcSDE extension will have
no effect.

5.4. Databases

141

GeoServer User Manual, Release 2.15.1

GeoServer files
1. Download the ArcSDE extension from the GeoServer download page.
Warning: Make sure to match the version of the extension to the version of the GeoServer instance!
2. Extract the contents of the archive into the WEB-INF/lib directory of the GeoServer installation.
Required external files
There are two files that are required but are not packaged with the GeoServer extension:
File
jsde_sdk.jar
jpe_sdk.jar

Notes
Also known as jsde##_sdk.jar where ## is the version number, such as 92 for
ArcSDE version 9.2
Also known as jpe##_sdk.jar where ## is the version number, such as 92 for
ArcSDE version 9.2

You should always make sure the jsde_sdk.jar and jpe_sdk.jar versions match your ArcSDE server
version, including service pack, although client jar versions higher than the ArcSDE Server version usually
work just fine.
These two files are available on your installation of the ArcSDE Java SDK from the ArcSDE installation media (usually C:\Program Files\ArcGIS\ArcSDE\lib). They may also be available on ESRI’s website
if there’s a service pack containing them, but this is not guaranteed. To download these files from ESRI’s
website:
1. Navigate
to
listPatches&PID=66

http://support.esri.com/index.cfm?fa=downloads.patchesServicePacks.

2. Find the link to the latest service pack for your version of ArcSDE
3. Scroll down to Installing this Service Pack → ArcSDE SDK → UNIX (regardless of your target OS)
4. Download any of the target files (but be sure to match 32/64 bit to your OS)
5. Open the archive, and extract the appropriate JARs.
Note: The JAR files may be in a nested archive inside this archive.

Note: The icu4j##.jar may also be on your ArcSDE Java SDK installation folder, but it is already
included as part of the the GeoServer ArcSDE extension and is not necessary to install separately.
1. When downloaded, copy the two files to the WEB-INF/lib directory of the GeoServer installation.
After all GeoServer files and external files have been downloaded and copied, restart GeoServer.

142

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Adding an ArcSDE vector data store
In order to serve vector data layers, it is first necessary to register the ArcSDE instance as a data store in
GeoServer. Navigate to the New data source page, accessed from the Stores page in the Web administration
interface. and an option for ArcSDE will be in the list of Vector Data Stores.
Note: If ArcSDE is not an option in the Feature Data Set Description drop down box, the extension is not
properly installed. Please see the section on Installing the ArcSDE extension.

Fig. 5.109: ArcSDE in the list of data sources

Configuring an ArcSDE vector data store
The next page contains configuration options for the ArcSDE vector data store. Fill out the form, then click
Save.
Option
Feature Data
Set ID
Enabled
Namespace
Description
server
port
instance

Required?Description
N/A
The name of the data store as set on the previous page.

user
password

Yes
No

N/A
Yes
No
Yes
Yes
No

pool.
No
minConnections
pool.
No
maxConnections
pool.timeOut No

When this box is checked the data store will be available to GeoServer
The namespace associated with the data store.
A description of the data store.
The URL of the ArcSDE instance.
The port that the ArcSDE instance is set to listen to. Default is 5151.
The name of the specific ArcSDE instance, where applicable, depending on
the underlying database.
The username to authenticate with the ArcSDE instance.
The password associated with the above username for authentication with
the ArcSDE instance.
Connection pool configuration parameters. See the Database Connection
Pooling section for details.
Connection pool configuration parameters. See the Database Connection
Pooling section for details.
Connection pool configuration parameters. See the Database Connection
Pooling section for details.

You may now add featuretypes as you would normally do, by navigating to the New Layer page, accessed
from the Layers page in the Web administration interface.
Configuring an ArcSDE vector data store with Direct Connect
ESRI Direct Connect[ESRI DC] allows clients to directly connect to an SDE GEODB 9.2+ without a need of
an SDE server instance, and is recommended for high availability environments, as it removes the ArcSDE
gateway server as a single point of failure. ESRI DC needs additional platform dependent binary drivers
and a working Oracle Client ENVIRONMENT (if connecting to an ORACLE DB). See Properties of a direct

5.4. Databases

143

GeoServer User Manual, Release 2.15.1

Fig. 5.110: Configuring a new ArcSDE data store

144

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

connection to an ArcSDE geodatabase in the ESRI ArcSDE documentation for more information on Direct
Connect, and Setting up clients for a direct connection for information about connecting to the different
databases supported by ArcSDE.
The GeoServer configuration parameters are the same as in the Configuring an ArcSDE vector data store
section above, with a couple differences in how to format the parameters:
• server: In ESRI Direct Connect Mode a value must be given or the Direct Connect Driver will throw
an error, so just put a ‘none’ there - any String will work!
• port: In ESRI Direct Connect Mode the port has a String representation: sde:oracle10g,
sde:oracle11g:/:test, etc. For further information check ArcSDE connection syntax at the official ArcSDE
documentation from ESRI.
• instance: In ESRI Direct Connect Mode a value must be given or the Direct Connect Driver will throw
an error, so just put a ‘none’ there - any String will work!
• user: The username to authenticate with the geo database.
• password: The password associated with the above username for authentication with the geo
database.
Note: Be sure to assemble the password like: password@ for Oracle
You may now add featuretypes as you would normally do, by navigating to the New Layer page, accessed
from the Layers page in the Web Administration Interface.
Adding an ArcSDE vector data store with JNDI
Configuring an ArcSDE vector data store with JNDI
Adding an ArcSDE raster coveragestore
In order to serve raster layers (or coverages), it is first necessary to register the ArcSDE instance as a store
in GeoServer. Navigate to the Add new store page, accessed from the Stores page in the Web administration
interface and an option for ArcSDE Raster Format will be in list.
Note: If ArcSDE Raster Format is not an option in the Coverage Data Set Description drop down box,
the extension is not properly installed. Please see the section on Installing the ArcSDE extension.

Fig. 5.111: ArcSDE Raster in the list of data sources

Configuring an ArcSDE raster coveragestore
The next page contains configuration options for the ArcSDE instance. Fill out the form, then click Save.

5.4. Databases

145

GeoServer User Manual, Release 2.15.1

Fig. 5.112: Configuring a new ArcSDE coveragestore

146

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Option
Coverage
Data Set ID
Enabled
Namespace
Type
URL

Required?Description
N/A
The name of the coveragestore as set on the previous page.

Description

No

N/A
Yes
No
Yes

When this box is checked the coveragestore will be available to GeoServer.
The namespace associated with the coveragestore.
The type of coveragestore. Leave this to say ArcSDE Raster.
The URL of the raster, of the form sde://:@/
#.
A description of the coveragestore.

You may now add coverages as you would normally do, by navigating to the Add new layer page, accessed
from the Layers page in the Web administration interface.

5.4.4 DB2
Note: GeoServer does not come built-in with support for DB2; it must be installed through an extension.
Proceed to Installing the DB2 extension for installation details.
The IBM DB2 UDB database is a commercial relational database implementing ISO SQL standards and is
similar in functionality to Oracle, SQL Server, MySQL, and PostgreSQL. The DB2 Spatial Extender is a nocharge licensed feature of DB2 UDB which implements the OGC specification “Simple Features for SQL
using types and functions” and the ISO “SQL/MM Part 3 Spatial” standard.
A trial copy of DB2 UDB and Spatial Extender can be downloaded from: http://www-306.ibm.com/
software/data/db2/udb/edition-pde.html . There is also an “Express-C” version of DB2, that is free,
comes with spatial support, and has no limits on size. It can be found at: http://www-306.ibm.com/
software/data/db2/express/download.html
Installing the DB2 extension

Warning: Due to licensing requirements, not all files are included with the extension. To install DB2
support, it is necessary to download additional files. Just installing the DB2 extension will have no
effect.
GeoServer files
1. Download the DB2 extension from the GeoServer download page.
Warning: Make sure to match the version of the extension to the version of the GeoServer instance!
2. Extract the contents of the archive into the WEB-INF/lib directory of the GeoServer installation.

5.4. Databases

147

GeoServer User Manual, Release 2.15.1

Required external files
There are two files that are required but are not packaged with the GeoServer extension: db2jcc.jar
and db2jcc_license_cu.jar. These files should be available in the java subdirectory of your DB2
installation directory. Copy these files to the WEB-INF/lib directory of the GeoServer installation.
After all GeoServer files and external files have been downloaded and copied, restart GeoServer.
Adding a DB2 data store
When properly installed, DB2 will be an option in the Vector Data Sources list when creating a new data
store.

Fig. 5.113: DB2 in the list of raster data stores

Configuring a DB2 data store
Configuring a DB2 data store with JNDI
Notes on usage
DB2 schema, table, and column names are all case-sensitive when working with GeoTools/GeoServer.
When working with DB2 scripts and the DB2 command window, the default is to treat these names as
upper-case unless enclosed in double-quote characters.

5.4.5 MySQL
Note: GeoServer does not come built-in with support for MySQL; it must be installed through an extension.
Proceed to Installing the MySQL extension for installation details.

Warning: Currently the MySQL extension is unmaintained and carries unsupported status. While still
usable, do not expect the same reliability as with other extensions.
MySQL is an open source relational database with some limited spatial functionality.
Installing the MySQL extension
1. Download the MySQL extension from the GeoServer download page.
Warning: Make sure to match the version of the extension to the version of the GeoServer instance!

148

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.114: Configuring a DB2 data store

5.4. Databases

149

GeoServer User Manual, Release 2.15.1

2. Extract the contents of the archive into the WEB-INF/lib directory of the GeoServer installation.
Adding a MySQL database
Once the extension is properly installed MySQL will show up as an option when creating a new data store.

Fig. 5.115: MySQL in the list of data sources

Configuring a MySQL data store
host
port
database
user
password
max
connections
min
connections
validate
connections

The mysql server host name or ip address.
The port on which the mysql server is accepting connections.
The name of the database to connect to.
The name of the user to connect to the mysql database as.
The password to use when connecting to the database. Left blank for no password.
Connection pool configuration parameters. See the Database Connection Pooling section for details.

5.4.6 Oracle
Note: GeoServer does not come built-in with support for Oracle; it must be installed through an extension.
Proceed to Installing the Oracle extension for installation details.
Oracle Spatial and Locator are the spatial components of Oracle. Locator is provided with all Oracle versions, but has limited spatial functions. Spatial is Oracle’s full-featured spatial offering, but requires a
specific license to use.
Installing the Oracle extension

Warning: Due to licensing requirements, not all files are included with the extension. To install Oracle
support, it is necessary to download additional files.
1. Download the Oracle extension from the GeoServer download page.
Warning: Make sure to match the version of the extension to the version of the GeoServer instance!

150

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.116: Configuring a MySQL data store

5.4. Databases

151

GeoServer User Manual, Release 2.15.1

2. Extract the contents of the archive into the WEB-INF/lib directory of the GeoServer installation.
3. Get the Oracle JDBC driver from either your Oracle installation (e.g. ojdbc6.jar, ojdbc7.jar) or
download them from the Oracle JDBC driver distribution page
Consider replacing the Oracle JDBC driver
The Oracle data store zip file comes with ojdbc4.jar, an old, Oracle 10 compatible JDBC driver that normally works fine with 11g as well. However, minor glitches have been observed with 11g (issues computing
layer bounds when session initiation scripts are in use) and the driver has not been tested with 12i.
If you encounter functionality or performance issues it is advised to remove this driver and download the
latest version from the Oracle web site.
Adding an Oracle datastore
Once the extension is properly installed Oracle appears as an option in the Vector Data Sources list when
creating a new data store.

Fig. 5.117: Oracle in the list of data sources

152

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.118: Configuring an Oracle datastore

5.4. Databases

153

GeoServer User Manual, Release 2.15.1

Configuring an Oracle datastore
Option
host
port
database
schema

user
password
max
connections
min
connections
fetch size
Connection
timeout
validate
connections
Loose bbox
Metadata bbox

Description
The Oracle server host name or IP address.
The port on which the Oracle server is accepting connections (often this is port
1521).
The name of the database to connect to. By default this is interpreted as a SID name.
To connect to a Service, prefix the name with a /.
The database schema to access tables from. Setting this value greatly increases the
speed at which the data store displays its publishable tables and views, so it is
advisable to set this.
The name of the user to use when connecting to the database.
The password to use when connecting to the database. Leave blank for no password.
Connection pool configuration parameters. See Database Connection Pooling for details.

Controls how bounding box filters are made against geometries in the database.
See the Using loose bounding box section below.
Flag controlling the use of MDSYS.USER_SDO_GEOM_METADATA or
MDSYS.ALL_SDO_GEOM_METADATA table for bounding box calculations,
this brings a better performance if the views access is fast and the bounds are
configured right in the tables default is false

Connecting to an Oracle cluster
In order to connect to an Oracle RAC one can use an almost full JDBC url as the database, provided it
starts with ( it will be used verbatim and options “host” and “port” will be ignored. Here is an example
“database” value used to connect to an Oracle RAC:
(DESCRIPTION=(LOAD_BALANCE=on)(ADDRESS=(PROTOCOL=TCP)(HOST=host1)
,→(PORT=1521))(ADDRESS=(PROTOCOL=TCP)(HOST=host2) (PORT=1521))(CONNECT_DATA=(SERVICE_
,→NAME=service)))

More information about this syntax can be found in the Oracle documentation.
Connecting to a SID or a Service
Recent versions of Oracle support connecting to a database via either a SID name or a Service name. A SID
connection descriptor has the form: host:port:database, while a Service connection descriptor has the
format host:port/database. GeoServer uses the SID form by default. To connect via a Service, prefix
the database name configuration entry with a /.

154

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Connecting to database through LDAP
For instance if you want to establish a connection with the jdbc thin driver through LDAP, you
can use following connect string for the input field database ldap://[host]:[Port]/[db],
cn=OracleContext,dc=[oracle_ldap_context].
If you are using referrals, enable it by placing a jndi.properties file in geoserver’s CLASSPATH, which is in
geoserver/WEB-INF/classes. This property file contains:
java.naming.referral=follow
Using loose bounding box
When the Loose bbox option is set, only the bounding box of database geometries is used in spatial
queries. This results in a significant performance gain. The downside is that some geometries may be
reported as intersecting a BBOX when they actually do not.
If the primary use of the database is through the Web Map Service (WMS) this flag can be set safely, since
querying more geometries does not have any visible effect. However, if using the Web Feature Service (WFS)
and making use of BBOX filtering capabilities, this flag should not be set.
Using the geometry metadata table
The Oracle data store by default looks at the MDSYS.USER_SDO* and MDSYS.ALL_SDO* views to determine the geometry type and native SRID of each geometry column. Those views are automatically populated with information about the geometry columns stored in tables that the current user owns (for the
MDSYS.USER_SDO* views) or can otherwise access (for the MDSYS.ALL_SDO* views).
There are a few issues with this strategy:
• if the connection pool user cannot access the tables (because impersonation is used) the MDSYS views
will be empty, making it impossible to determine both the geometry type and the native SRID
• the geometry type can be specified only while building the spatial indexes, as an index constraint.
However such information is often not included when creating the indexes
• the views are populated dynamically based on the current user. If the database has thousands of
tables and users the views can become very slow
Starting with GeoServer 2.1.4 the administrator can address the above issues by manually creating a geometry metadata table describing each geometry column. Its presence is indicated via the Oracle datastore
connection parameter named Geometry metadata table (which may be a simple table name or a schemaqualified one). The table has the following structure (the table name is flexible, just specify the one chosen
in the data store connection parameter):
CREATE TABLE GEOMETRY_COLUMNS(
F_TABLE_SCHEMA VARCHAR(30) NOT NULL,
F_TABLE_NAME VARCHAR(30) NOT NULL,
F_GEOMETRY_COLUMN VARCHAR(30) NOT NULL,
COORD_DIMENSION INTEGER,
SRID INTEGER NOT NULL,
TYPE VARCHAR(30) NOT NULL,
UNIQUE(F_TABLE_SCHEMA, F_TABLE_NAME, F_GEOMETRY_COLUMN),
CHECK(TYPE IN ('POINT','LINE', 'POLYGON', 'COLLECTION', 'MULTIPOINT', 'MULTILINE',
,→'MULTIPOLYGON', 'GEOMETRY') ));

5.4. Databases

155

GeoServer User Manual, Release 2.15.1

When the table is present the store first searches it for information about each geometry column to be
classified, and falls back on the MDSYS views only if the table does not contain any information.
Configuring an Oracle database with JNDI
See Setting up a JNDI connection pool with Tomcat for a guide on setting up an Oracle connection using JNDI.

5.4.7 Microsoft SQL Server and SQL Azure
Note: GeoServer does not come built-in with support for SQL Server; it must be installed through an
extension. Proceed to Installing the SQL Server extension for installation details.
Microsoft’s SQL Server is a relational database with spatial functionality. SQL Azure is the database option
provided in the Azure cloud solution which is in many respects similar to SQL Server 2008.
Supported versions
The extension supports SQL Server 2008 and SQL Azure.
Installing the SQL Server extension

Warning: Due to licensing requirements, not all files are included with the extension. To install SQL
Server support, it is necessary to download additional files.
GeoServer files
1. Download the SQL Server extension from the GeoServer download page.
Warning: Make sure to match the version of the extension to the version of the GeoServer instance!
2. Extract the contents of the archive into the WEB-INF/lib directory of the GeoServer installation.
3. Restart the GeoServer to load the extension.
Microsoft files
1. Navigate to the download page for Microsoft JDBC Drivers for SQL Server.
2. Extract the contents of the archive.
3. Copy the file sqljdbc4.jar to the WEB-INF/lib directory of the GeoServer installation.
4. If GeoServer is installed on Windows, additionally copy auth\x86\sqljdbc_auth.dll and
xa\x86\sqljdbc_xa.dll to C:\Windows\System32.

156

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Adding a SQL Server database
Once the extension is properly installed SQL Server will show up as an option when creating a new data
store.

Fig. 5.119: SQL Server in the list of vector data sources

Configuring a SQL Server data store

Fig. 5.120: Configuring a SQL Server data store

5.4. Databases

157

GeoServer User Manual, Release 2.15.1

host

port
database
schema
user
password
max
connections
min
connections

The sql server instance host name or ip address, only.
Note that
server\instance notation is not accepted - specify the port below, instead, if
you have a non-default instance.
The port on which the SQL server instance is accepting connections. See the note
below.
The name of the database to connect to. Might be left blank if the user connecting
to SQL Server has a “default database” set in the user configuration
The database schema to access tables from (optional).
The name of the user to connect to the oracle database as.
The password to use when connecting to the database. Leave blank for no password.
Connection pool configuration parameters. See the Database Connection Pooling section for details. If you are connecting to SQL Azure make sure to set the validate
connections flag as SQL Azure closes inactive connections after a very short delay.

Determining the port used by the SQL Server instance
You can determine the port in use by connecting to your SQL server instance using some other software, and
then using netstat to display details on network connections. In the following example on a Windows
PC, the port is 2646
C:\>netstat -a | find "sql1"
TCP
DPI908194:1918
maittestsql1.dpi.nsw.gov.au:2646

ESTABLISHED

Using the geometry metadata table
The SQL server data store can determine the geometry type and native SRID of a particular column only
by data inspection, by looking at the first row in the table. Of course this is error prone, and works only if
there is data in the table. The administrator can address the above issue by manually creating a geometry
metadata table describing each geometry column. Its presence is indicated via the SQL Server datastore
connection parameter named Geometry metadata table (which may be a simple table name or a schemaqualified one). The table has the following structure (the table name is flexible, just specify the one chosen
in the data store connection parameter):
CREATE TABLE GEOMETRY_COLUMNS(
F_TABLE_SCHEMA VARCHAR(30) NOT NULL,
F_TABLE_NAME VARCHAR(30) NOT NULL,
F_GEOMETRY_COLUMN VARCHAR(30) NOT NULL,
COORD_DIMENSION INTEGER,
SRID INTEGER NOT NULL,
TYPE VARCHAR(30) NOT NULL,
UNIQUE(F_TABLE_SCHEMA, F_TABLE_NAME, F_GEOMETRY_COLUMN),
CHECK(TYPE IN ('POINT','LINE', 'POLYGON', 'COLLECTION', 'MULTIPOINT', 'MULTILINE',
,→'MULTIPOLYGON', 'GEOMETRY') ));

When the table is present the store first searches it for information about each geometry column to be
classified, and falls back on data inspection only if the table does not contain any information.

5.4.8 Teradata

158

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Note: Teradata database support is not enabled by default and requires the Teradata extension to be
installed prior to use. Please see the section on Installing the Teradata extension for details.
The Teradata Database is a commercial relational database (RDBMS) that specializes in parallel processing
and scalability. From version 12.0, Teradata has added geospatial support, closely following the SQL/MM
standard (SQL Multimedia and Applications Packages). Geospatial support was available through an addon in version 12.0 and became standard in version 13.0.
GeoServer connects to a Teradata database via JDBC.
For more information on Teradata and the Teradata Database system, please go to http://www.teradata.
com.
Compatibility
The GeoServer Teradata extension is compatible with GeoServer 2.1.1 and higher. GeoServer can connect
to Teradata databases version 12.0 or higher. Version 12.0 of the Teradata Database requires the optional
geospatial extension to be installed.
Read/write access
The Teradata datastore in GeoServer supports full transactional capabilities, including feature creation,
editing, and deleting.
To support editing, a table must have one of the following:
• a primary key
• a unique primary index
• an identity (sequential) column
Note: It is not recommended to solely use an identity column, as spatial index triggers are not supported
when referencing an identity column. See the section on Spatial Indexes for more details.

Query Banding
The GeoServer Teradata extension supports Query Banding. Query Banding is a feature which allows any
application to associate context information with each query it issues to the database. In practice this can
be used for purposes of workload management (i.e. request prioritization), debugging, and logging.
GeoServer sends the following information as part of a standard request:
• Name of application (i.e. GeoServer)
• Authenticated username (if set up)
• Hostname (if available)
• Type of statement (i.e. “SELECT”, “INSERT”, “DELETE”)
It is not possible to modify this information from within GeoServer.

5.4. Databases

159

GeoServer User Manual, Release 2.15.1

Spatial indexes
GeoServer will read from a spatial index if its exists. The convention for a spatial index table name is:
[TABLENAME]_[GEOMETRYCOLUMN]_idx

So for a layer called “STATES” with a geometry column called “GEOM”, the index table should be called
STATES_GEOM_idx.
Warning: Make sure to match the case of all tables and columns. If the geometry column is called
“GEOM” (upper case) and the index created is called STATES_geom_idx (lower case), the index will not
be properly linked to the table.
This index table should contain two columns:
• A column that maps to the primary key of the spatial data table
• The tessellation cell ID (cellid)
The tessellation cell ID is the ID of the cell where that feature is contained.
Geometry column
As per the SQL/MM standard, in order to make a Teradata table spatially enabled, an entry needs to be
created for that table in the geometry_columns table. This table is stored, like all other spatially-related
tables, in the SYSSPATIAL database.
Tessellation
Tessellation is the name of Teradata’s spatial index. In order to activate tessellation for a given layer, an
entry (row) needs to be placed in the SYSSPATIAL.tessellation table. This table should have the
following schema:
Table name
F_TABLE_SCHEMA

Type
varchar

F_TABLE_NAME
F_GEOMETRY_COLUMN
U_XMIN
U_YMIN
U_XMAX
U_YMAX
G_NX
G_NY
LEVELS
SCALE
SHIFT

varchar
varchar
float
float
float
float
integer
integer
integer
float
float

Description
Name of the spatial database/schema containing
the table
Name of the spatial table
Column that contains the spatial data
Minimum X value for the tessellation universe
Minimum Y value for the tessellation universe
Maximum X value for the tessellation universe
Maximum Y value for the tessellation universe
Number of X grids
Number of Y grids
Number of levels in the grid
Scale value for the grid
Shift value for the grid

Warning: The tessellation table values are case sensitive and so must match the case of the tables and
columns.

160

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Installing the Teradata extension
Teradata database support is not enabled by default and requires the GeoServer Teradata extension to be
installed prior to use. In addition to this extension, an additional artifact will need to be downloaded from
the Teradata website.
GeoServer artifacts
1. Download the Teradata extension from the download page that matches your version of GeoServer.
The extension is listed at the bottom of the download page under Extensions.
Warning: Make sure to match the version of the extension to the version of GeoServer!
2. Extract the contents of the archive into the WEB-INF/lib directory of the GeoServer installation.
Teradata artifacts
In addition to the GeoServer artifacts, it is also necessary to download the Teradata JDBC driver. This file
cannot be redistributed and so must be downloaded directly from the Teradata website.
1. Download the Teradata JDBC driver at https://downloads.teradata.com/download/connectivity/
jdbc-driver.
Note: You will need to log in to Teradata’s site in order to download this artifact.
2. Extract the contents of the archive into the WEB-INF/lib directory of the GeoServer installation.
When all files have been downloaded and extracted, restart GeoServer. To verify that the installation was
successful, see the section on Adding a Teradata datastore.
Note: The full list of files required are:
• gt-jdbc-teradata-.jar
• tdgssconfig.jar
• terajdbc4.jar

Adding a Teradata datastore
Once the extension has been added, it will now be possible to load an existing Teradata database as a store
in GeoServer. In the Web administration interface, click on Stores then go to Add a new Store. You will see a
option, under Vector Data Stores, for Teradata. Select this option.
Note: If you don’t Teradata in this list, the extension has not been installed properly. Please ensure that the
steps in the Installing the Teradata extension have been followed correctly.
On the next screen, enter in the details on how to connect to the Teradata database. You will need to include
the following information:
5.4. Databases

161

GeoServer User Manual, Release 2.15.1

Fig. 5.121: Teradata in the list of readable stores

Option
Workspace
Data Source Name
Description
Enabled
host
port
database
user
passwd
namespace
Expose
primary
keys
max connections
min connections
fetch size
Connection timeout
validate connections
Primary key metadata table
Loose bbox
tessellationTable
estimatedBounds
Max open prepared
statements
162

Description
Name of the workspace to contain the database. This will also be the prefix of any
layers server from tables in the database.
Name of the database in GeoServer. This can be different from the name of the
Teradata database, if desired.
Description of the database/store.
Enables the store. If disabled, no layers from the database will be served.
Host name where the database exists. Can be a URL or IP address.
Port number on which to connect to the above host.
Name of the Teradata database.
User name to connect to use to connect to the database.
Password associated with the above user.
Namespace to be associated with the database. This field is altered automatically
by the above Workspace field.
Exposes primary key as a standard attribute.
Maximum amount of open/pooled connections to the database.
Minimum number of open/pooled connections.
Number of records read with each interaction with the database.
Time (in seconds) the connection pool will wait before timing out.
Checks the connection is alive before using it.
Name of primary key metadata table to use if unable to determine the primary key
of a table.
If checked, performs only the primary filter on the bounding box.
The name of the database table that contains the tessellations
Enables using the geometry_columns/tessellation table bounds as an estimation
instead of manual calculation.
The maximum number of prepared statements.
Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

When finished, click Save.

Using JNDI
GeoServer can also connect to a Teradata database using JNDI (Java Naming and Directory Interface).
To begin, in the Web administration interface, click on Stores then go to Add a new Store. You will see a option,
under Vector Data Stores, for Teradata (JNDI). Select this option.
On the next screen, enter in the details on how to connect to the Teradata database. You will need to include
the following information:

5.4. Databases

163

GeoServer User Manual, Release 2.15.1

Fig. 5.122: Adding a Teradata store

Fig. 5.123: Teradata (JNDI) in the list of readable stores

164

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Option
Workspace
Data Source Name
Description
Enabled
jndiReferenceName
schema
namespace
Expose
primary
keys
Primary key metadata table
Loose bbox

Description
Name of the workspace to contain the database. This will also be the prefix of any
layers server from tables in the database.
Name of the database in GeoServer. This can be different from the name of the
Teradata database, if desired.
Description of the database/store.
Enables the store. If disabled, no layers from the database will be served.
JNDI path to the database.
Schema for the above database.
Namespace to be associated with the database. This field is altered by changing the
workspace name.
Exposes primary key as a standard attribute.
Name of primary key metadata table to use if unable to determine the primary key
of a table.
If checked, performs only the primary filter on the bounding box.

When finished, click Save.

Fig. 5.124: Adding a Teradata store with JNDI

5.4. Databases

165

GeoServer User Manual, Release 2.15.1

Adding layers
One the store has been loaded into GeoServer, the process for loading data layers from database tables is
the same as any other database source. Please see the Layers section for more information.
Note: Only those database tables that have spatial information and an entry in the SYSSPATIAL.
geometry_columns table can be served through GeoServer.
GeoServer provides extensive facilities for controlling how databases are accessed. These are covered in the
following sections.

5.4.9 Database Connection Pooling
When serving data from a spatial database connection pooling is an important aspect of achieving good performance. When GeoServer serves a request that involves loading data from a database table, a connection
must first be established with the database. This connection comes with a cost as it takes time to set up such
a connection.
The purpose served by a connection pool is to maintain connection to an underlying database between
requests. The benefit of which is that connection setup only need to occur once on the first request. Subsequent requests use existing connections and achieve a performance benefit as a result.
Whenever a data store backed by a database is added to GeoServer an internal connection pool is created.
This connection pool is configurable.

166

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Connection pool options
max connections

min connections

validate
tions

connec-

fetch size

connection timeout
Test while idle

Evictor run periodicity
Max connection
idle time
Evictor tests per
run

The maximum number of connections the pool can hold. When the maximum
number of connections is exceeded, additional requests that require a database
connection will be halted until a connection from the pool becomes available. The
maximum number of connections limits the number of concurrent requests that
can be made against the database.
The minimum number of connections the pool will hold. This number of connections is held even when there are no active requests. When this number of connections is exceeded due to serving requests additional connections are opened until
the pool reaches its maximum size (described above).
Flag indicating whether connections from the pool should be validated before they
are used. A connection in the pool can become invalid for a number of reasons
including network breakdown, database server timeout, etc.. The benefit of setting
this flag is that an invalid connection will never be used which can prevent client
errors. The downside of setting the flag is that a performance penalty is paid in
order to validate connections.
The number of records read from the database in each network exchange. If set
too low (<50) network latency will affect negatively performance, if set too high it
might consume a significant portion of GeoServer memory and push it towards an
Out Of Memory error. Defaults to 1000.
Time, in seconds, the connection pool will wait before giving up its attempt to get
a new connection from the database. Defaults to 20 seconds.
Periodically test if the connections are still valid also while idle in the pool. Sometimes performing a test query using an idle connection can make the datastore
unavailable for a while. Often the cause of this troublesome behaviour is related
to a network firewall placed between GeoServer and the Database that force the
closing of the underlying idle TCP connections.
Number of seconds between idle object evictor runs.
Number of seconds a connection needs to stay idle before the evictor starts to consider closing it.
Number of connections checked by the idle connection evictor for each of its runs.

5.4.10 JNDI
Many data stores and connections in GeoServer have the option of utilizing Java Naming and Directory
Interface on JNDI. JNDI allows for components in a Java system to look up other objects and data by a
predefined name.
A common use of JNDI is to store a JDBC data source globally in a container. This has a few benefits.
First, it can lead to a much more efficient use of database resources. Database connections in Java are
very resource-intensive objects, so usually they are pooled. If each component that requires a database
connection is responsible for creating their own connection pool, resources will stack up fast. In addition,
often those resources are under-utilized and a component may not size its connection pool accordingly. A
more efficient method is to set up a global pool at the servlet container level, and have every component
that requires a database connection use that.
Furthermore, JNDI consolidates database connection configuration, as not every component that requires a
database connection needs to know any more details than the JNDI name. This is very useful for administrators who may have to change database parameters in a running system, as it allows the change to occur
in a single place.
5.4. Databases

167

GeoServer User Manual, Release 2.15.1

5.4.11 SQL Views
The traditional way to access database data is is to configure layers against either tables or database views.
Starting with GeoServer 2.1.0, layers can also be defined as SQL Views. SQL Views allow executing a
custom SQL query on each request to the layer. This avoids the need to create a database view for complex
queries.
Even more usefully, SQL View queries can be parameterized via string substitution. Parameter values can
be supplied in both WMS and WFS requests. Default values can be supplied for parameters, and input
values can be validated by Regular Expressions to eliminate the risk of SQL injection attacks.
Note: SQL Views are read-only, and thus cannot be updated by WFS-T transactions.

Creating a SQL View
In order to create a SQL View the administrator invokes the Create new layer page. When a database store
is selected, the usual list of tables and views available for publication appears, A link Configure new SQL
view. . . also appears:

Selecting the Configure new SQL view. . . link opens a new page where the SQL view query can be specified:

168

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Note: The query can be any SQL statement that is valid as a subquery in a FROM clause (that is, select
* from () [as] vtable). This is the case for most SQL statements, but in some
databases special syntax may be needed to call stored procedures. Also, all the columns returned by the
SQL statement must have names. In some databases alias names are required for function calls.
When a valid SQL query has been entered, press the Refresh link in the Attributes table to get the list of the
attribute columns determined from the query:

GeoServer attempts to determine the geometry column type and the native SRID, but these should be
verified and corrected if necessary.
Note: Having a correct SRID (spatial reference id) is essential for spatial queries to work. In many spatial
databases the SRID is equal to the EPSG code for the specific spatial reference system, but this is not always
the case (for instance, Oracle has a number of non-EPSG SRID codes).
If stable feature ids are desired for the view’s features, one or more columns providing a unique id for the
features should be checked in the Identifier column. Always ensure these attributes generate a unique key,
or filtering and WFS requests will not work correctly.
Once the query and the attribute details are defined, press Save. The usual New Layer configuration page
will appear. If further changes to the view are required, the page has a link to the SQL View editor at the
bottom of the Data tab:

Once created, the SQL view layer is used in the same way as a conventional table-backed layer, with the
one limitation of being read-only.

5.4. Databases

169

GeoServer User Manual, Release 2.15.1

Warning: Saving the SQL view definition here is not sufficient, the layer containing it must be saved
as well for the change to have any effect. This is because the SQL view definition is actually just one
component of the layer/featuretype/coverage attributes.

Parameterizing SQL Views
A parametric SQL view is based on a SQL query containing named parameters. The values for the parameters can be provided dynamically in WMS and WFS requests using the viewparams request parameter.
Parameters can have default values specified, to handle the situation where they are not supplied in a request. Validation of supplied parameter values is supported by specifying validation regular expressions.
Parameter values are only accepted if they match the regular expression defined for them. Appropriate
parameter validation should always be used to avoid the risk of SQL injection attacks.
Warning: SQL View parameter substitution should be used with caution, since improperly validated
parameters open the risk of SQL injection attack. Where possible, consider using safer methods such as
dynamic filtering in the request, or Variable substitution in SLD.

Defining parameters
Within the SQL View query, parameter names are delimited by leading and trailing % signs. The parameters
can occur anywhere within the query text, including such uses as within SQL string constants, in place of
SQL keywords, or representing entire SQL clauses.
Here is an example of a SQL View query for a layer called popstates with two parameters, low and high:

Each parameter needs to be defined with its name, an optional default value, and a validation expression.
The Guess parameters from SQL link can be clicked to infer the query parameters automatically, or they can
be entered manually. The result is a table filled with the parameter names, default values and validation
expressions:

In this case the default values should be specified, since the query cannot be executed without values for the
parameters (because the expanded query select gid, state_name, the_geom from pgstates

170

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

where persons between and is invalid SQL). Since the use of the parameters in the SQL query requires their values to be positive integer numbers, the validation regular expressions are specified to allow
only numeric input (i.e. ^[\d]+$):

Once the parameters have been defined, the Attributes Refresh link is clicked to parse the query and retrieve the attribute columns. The computed geometry type and column identifier details can be corrected if
required. From this point on the workflow is the same as for a non-parameterized query.
Using a parametric SQL View
The SQL view parameters are specified by adding the viewparams parameter to the WMS GetMap or
the WFS GetFeature request. The viewparams argument is a list of key:value pairs, separated by
semicolons:
viewparams=p1:v1;p2:v2;...
If the values contain semicolons or commas these must be escaped with a backslash (e.g. \, and \;).
For example, the popstates SQL View layer can be displayed by invoking the Layer Preview. Initially no
parameter values are supplied, so the defaults are used and all the states are displayed,
To display all states having more than 20 million inhabitants the following parameter is added to the
GetMap request: &viewparams=low:20000000

To display all states having between 2 and 5 millions inhabitants the view parameters are:
&viewparams=low:2000000;high:5000000
Parameters can be provided for multiple layers by separating each parameter map with a comma:
&viewparams=l1p1:v1;l1p2:v2,l2p1:v1;l2p2:v2,...
The number of parameter maps must match the number of layers (featuretypes) included in the request.

5.4. Databases

171

GeoServer User Manual, Release 2.15.1

Parameters and validation
The value of a SQL View parameter can be an arbitrary string of text. The only constraint is that the attribute
names and types returned by the view query must never change. This makes it possible to create views
containing parameters representing complex SQL fragments. For example, using the view query select
* from pgstates %where% allows specifying the WHERE clause of the query dynamically. However,
this would likely require an empty validation expression. which presents a serious risk of SQL injection
attacks. This technique should only be used if access to the server is restricted to trusted clients.
In general, SQL parameters must be used with care. They should always include validation regular expressions that accept only the intended parameter values. Note that while validation expressions should
be constructed to prevent illegal values, they do not necessarily have to ensure the values are syntactically
correct, since this will be checked by the database SQL parser. For example:
• ^[\d\.\+-eE]+$ checks that a parameter value contains valid characters for floating-point numbers
(including scientific notation), but does not check that the value is actually a valid number
• [^;']+ checks that a parameter value does not contain quotes or semicolons. This prevents common
SQL injection attacks, but otherwise does not impose much limitation on the actual value
Resources for Validation Regular expressions
Defining effective validation regular expressions is important for security. Regular expressions are a complex topic that cannot be fully addressed here. The following are some resources for constructing regular
expressions:
• GeoServer uses the standard Java regular expression engine. The Pattern class Javadocs contain the
full specification of the allowed syntax.
• http://www.regular-expressions.info has many tutorials and examples of regular expressions.
• The myregexp applet can be used to test regular expressions online.
Place holder for the SQL WHERE clause
The SQL WHERE clause produced by GeoServer using the context filters, e.g. the bounding box filter of a
WMS query, will be added around the SQL view definition. This comes handy (better performance) when
we have extra operations that can be done on top of the rows filtered with the GeoServer produced filter
first.
A typical use case for this functionality is the execution of analytic functions on top of the filtered results:

172

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

SELECT STATION_NAME,
MEASUREMENT,
MEASUREMENT_TYPE,
LOCATION
FROM
(SELECT STATION_NAME,
MEASUREMENT,
MEASUREMENT_TYPE,
LOCATION,
ROW_NUMBER() OVER(PARTITION BY STATION_ID, MEASUREMENT_TYPE
ORDER BY TIME DESC) AS RANK
FROM
(SELECT st.id AS STATION_ID,
st.common_name AS STATION_NAME,
ob.value AS MEASUREMENT,
pr.param_name AS MEASUREMENT_TYPE,
ob.time AS TIME,
st.position AS LOCATION
FROM meteo.meteo_stations st
LEFT JOIN meteo.meteo_observations ob ON st.id = ob.station_id
LEFT JOIN meteo.meteo_parameters pr ON ob.parameter_id = pr.id
-- SQL WHERE clause place holder for GeoServer
WHERE 1 = 1 :where_clause:) AS stations_filtered) AS stations
WHERE RANK = 1;

A few restrictions apply when using the explicit :where_clause: place holder:
• it needs to be added in a position where all the attributes known by GeoServer are already present
• the :where_clause: can only appear once
When a WHERE clause place holder is present, GeoServer will always add an explicit AND at the beginning
of the produced WHERE clause. This allows the injection of the produced WHERE in the middle of complex
expressions if needed.

5.4.12 Controlling feature ID generation in spatial databases
Introduction
All spatial database data stores (PostGIS, Oracle, MySQL and so on) normally derive the feature ID from
the table primary key and assume certain conventions on how to locate the next value for the key in case a
new feature needs to be generated (WFS insert operation).
Common conventions rely on finding auto-increment columns (PostGIS) or finding a sequence that is
named after a specific convention such as __SEQUENCE (Oracle case).
In case none of the above is found, normally the store will fall back on generating random feature IDs at
each new request, making the table unsuitable for feature ID based searches and transactions.
Metadata table description
These defaults can be overridden manually by creating a primary key metadata table that specifies which
columns to use and what strategy to use to generate new primary key values. The (schema qualified) table

5.4. Databases

173

GeoServer User Manual, Release 2.15.1

can be created with this SQL statement (this one is valid for PostGIS and ORACLE, adapt it to your specific
database, you may remove the check at the end if you want to):
--PostGIS DDL
CREATE TABLE my_schema.gt_pk_metadata (
table_schema VARCHAR(32) NOT NULL,
table_name VARCHAR(32) NOT NULL,
pk_column VARCHAR(32) NOT NULL,
pk_column_idx INTEGER,
pk_policy VARCHAR(32),
pk_sequence VARCHAR(64),
unique (table_schema, table_name, pk_column),
check (pk_policy in ('sequence', 'assigned', 'autogenerated'))
)

--ORACLE DDL
CREATE TABLE gt_pk_metadata (
table_schema VARCHAR2(32) NOT NULL,
table_name VARCHAR2(32) NOT NULL,
pk_column VARCHAR2(32) NOT NULL,
pk_column_idx NUMBER(38),
pk_policy VARCHAR2(32),
pk_sequence VARCHAR2(64),
constraint chk_pk_policy check (pk_policy in ('sequence', 'assigned',
,→'autogenerated')));
CREATE UNIQUE INDEX gt_pk_metadata_table_idx01 ON gt_pk_metadata (table_schema, table_
,→name, pk_column);

The table can be given a different name. In that case, the (schema qualified) name of the table must be
specified in the primary key metadata table configuration parameter of the store.
The following table describes the meaning of each column in the metadata table.
Column
table_schema
table_name
pk_column
pk_column_idx
pk_policy
pk_sequence

Description
Name of the database schema in which the table is located.
Name of the table to be published
Name of a column used to form the feature IDs
Index of the column in a multi-column key. In case multi column keys are needed
multiple records with the same table schema and table name will be used.
The new value generation policy, used in case a new feature needs to be added in
the table (following a WFS-T insert operation).
The name of the database sequence to be used when generating a new value for
the pk_column.

The possible values are:
• assigned. The value of the attribute in the newly inserted feature will be used (this assumes the “expose
primary keys” flag has been enabled)
• sequence. The value of the attribute will be generated from the next value of a sequence indicated in
the “pk_sequence” column.
• autogenerated. The column is an auto-increment one, the next value in the auto-increment will be used.

174

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Using the metadata table with views
GeoServer can publish spatial views without issues, but normally results in two side effects:
• the view is treated as read only
• the feature IDs are randomly generated
The metadata table can also refer to views, just use the view name in the table_name column: this will
result in stable ids, and in databases supporting updatable views, it will also make the code treat the view
as writable (thus, enabling usage of WFS-T on it).

5.4.13 Custom SQL session start/stop scripts
Starting with version 2.1.4 GeoServer support custom SQL scripts that can be run every time GeoServer
grabs a connection from the connection pool, and every time the session is returned to the pool.
These scripts can be parametrized with the expansion of environment variables, which can be in turn set
into the OGC request parameters with the same mechanism as Variable substitution in SLD.
In addition to the parameters provided via the request the GSUSER variable is guaranteed to contain the
current GeoServer user, or be null if no authentication is available. This is useful if the SQL sessions scripts
are used to provide tight control over database access
The SQL script can expand environment variables using the ${variableName, defaultValue} syntax,
for example the following alters the current database user to be the same as the GeoServer current user, or
geoserver in case no user was authenticated
SET SESSION AUTHORIZATION ${GSUSER,geoserver}

5.4.14 Using SQL session scripts to control authorizations at the database level
GeoServer connects to a database via a connection pool, using the same rights as the user that is specified in
the connection pool setup. In a setup that provides a variety of services and tables the connection pool user
must have a rather large set of rights, such as table selection (WMS), table insert/update/delete (WFS-T)
and even table creation (data upload via RESTConfig, WPS Import process and eventual new processes
leveraging direct database connections).
What a user can do can be controlled by means of the GeoServer security subsystem, but in high security
setups this might not be considered enough, and a database level access control be preferred instead. In
these setups normally the connection pool user has limited access, such as simple read only access, while
specific users are allowed to perform more operations.
When setting up such a solution remember the following guidelines:
• The connection pool user must be able to access all table metadata regardless of whether it is able
to actually perform a select on the tables (dictionary tables/describe functionality must be always
accessible)
• The connection pool must see each and every column of tables and views, in other words, the structure
of the tables must not change as the current user changes
• the database users and the GeoServer user must be kept in synch with some external tools, GeoServer
provides no out of the box facilities
• during the GeoServer startup the code will access the database to perform some sanity checks, in that
moment there is no user authenticated in GeoServer so the code will run under whatever user was
specified as the “default value” for the GSUSER variable.

5.4. Databases

175

GeoServer User Manual, Release 2.15.1

• The user that administers GeoServer (normally admin, but it can be renamed, and other users given
the administration roles too) must also be a database user, all administrative access on the GeoServer
GUI will have that specific user controlling the session
Typical use cases:
• Give insert/update/delete rights only to users that must use WFS-T
• Only allow the administrator to create new tables
• Limit what rows of a table a user can see by using dynamic SQL views taking into account the current
user to decide what rows to return
To make a point in case, if we want the PostgreSQL session to run with the current GeoServer user credentials the following scripts will be used:

Fig. 5.125: Setting up session authorization for PostgreSQL
The first command makes the database session use either the current GeoServer user, or the geoserver
user if no authentication was available (anonymous user, or startup situation). The second command resets
the session to the rights of the connection pool user.

5.5 Cascaded service data
This section discusses how GeoServer can proxy external OGC services. This is known as cascading services.
GeoServer supports cascading the following services:

5.5.1 External Web Feature Server
GeoServer has the ability to load data from a remote Web Feature Server (WFS). This is useful if the remote
WFS lacks certain functionality that GeoServer contains. For example, if the remote WFS is not also a Web
Map Server (WMS), data from the WFS can be cascaded through GeoServer to utilize GeoServer’s WMS. If
the remote WFS has a WMS but that WMS cannot output KML, data can be cascaded through GeoServer’s
WMS to output KML.
Adding an external WFS
To connect to an external WFS, it is necessary to load it as a new datastore. To start, navigate to Stores →
Add a new store → Web Feature Server.

176

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Fig. 5.126: Adding an external WFS as a store

5.5. Cascaded service data

177

GeoServer User Manual, Release 2.15.1

Option
Workspace

Description
Name of the workspace to contain the store. This will also be the prefix of all of the
layer names created from the store.
Data Source Name
Name of the store as known to GeoServer.
Description
Description of the store.
Enabled
Enables the store. If disabled, no data from the external WFS will be served.
GET_CAPABILITIES_URL
URL to access the capabilities document of the remote WFS.
PROTOCOL
When checked, connects with POST, otherwise uses GET.
USERNAME
The user name to connect to the external WFS.
PASSWORD
The password associated with the above user name.
ENCODING
The character encoding of the XML requests sent to the server. Defaults to UTF-8.
TIMEOUT
Time (in milliseconds) before timing out. Default is 3000.
BUFFER_SIZE
Specifies a buffer size (in number of features). Default is 10 features.
TRY_GZIP
Specifies that the server should transfer data using compressed HTTP if supported
by the server.
LENIENT
When checked, will try to render features that don’t match the appropriate schema.
Errors will be logged.
MAXFEATURES
Maximum amount of features to retrieve for each featuretype. Default is no limit.
AXIS_ORDER
Axis order used in result coordinates (It applies only to WFS 1.x.0 servers). Default
is Compliant.
AXIS_ORDER_FILTER
Axis order used in filter (It applies only to WFS 1.x.0 servers). Default is Compliant.
OUTPUTFORMAT Output format to request (instead of the default remote service one).
GML_COMPLIANCE_LEVEL
OCG GML compliance level. i.e. (simple feature) 0, 1 or 2. Default is 0.
GML_COMPATIBLE_TYPENAMES
Use Gml Compatible TypeNames (replace : by _). Default is no false.
USE_HTTP_CONNECTION_POOLING
Use connection pooling to connect to the remote WFS service. Also enables digest
authentcation.
When finished, click Save.
Configuring external WFS layers
When properly loaded, all layers served by the external WFS will be available to GeoServer. Before they can
be served, however, they will need to be individually configured as new layers. See the section on Layers
for how to add and edit new layers.
Connecting to an external WFS layer via a proxy server
In a corporate environment it may be necessary to connect to an external WFS through a proxy server. To
achieve this, various java variables need to be set.
For a Windows install running GeoServer as a service, this is done by modifying the wrapper.conf file. For
a default Windows install, modify C:\Program Files\GeoServer x.x.x\wrapper\wrapper.conf
similarly to the following.
# Java Additional Parameters
wrapper.java.additional.1=-Djetty.home=.
wrapper.java.additional.2=DGEOSERVER_DATA_DIR=”%GEOSERVER_DATA_DIR%”
wrapper.java.additional.3=Dhttp.proxySet=true
wrapper.java.additional.4=-Dhttp.proxyHost=maitproxy
wrapper.java.additional.5=-Dhttp.proxyPort=8080
wrapper.java.additional.6=Dhttps.proxyHost=maitproxy
wrapper.java.additional.7=-Dhttps.proxyPort=8080
wrapper.java.additional.8=-Dhttp.nonProxyHosts=”mait*|dpi*|localhost”

178

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Note that the http.proxySet=true parameter is required. Also, the parameter numbers must be consecutive - ie. no gaps.
For a Windows install not running GeoServer as a service, modify startup.bat so that the java command runs with similar -D parameters.
For a Linux/UNIX install, modify startup.sh so that the java command runs with similar -D parameters.

5.5.2 Cascaded Web Feature Service Stored Queries
Stored query is a feature of Web Feature Services. It allows servers to serve pre-configured filter queries
or even queries that cannot be expressed as GetFeature filter queries. This feature of GeoServer allows to
create cascaded layers out of stored queries.
Stored queries are read-only, and layers derived from cascaded stored queries cannot be updated with
WFS-T.
Cascaded stored query parameters
The relationship between stored query parameters and the schema returned by the query is not well defined. For cascaded stored queries to work, the relationship between the query received by GeoServer and
the parameters passed to the stored query must be defined.
When you set up a layer based on a stored query, you have to select which stored query to cascade and
what values are passed to each parameter. Cascaded stored queries can leverage view parameters passed
to the query. This is similar to how arbitrary parameters are passed to SQL Views. GeoServer supports
multiple strategies to pass these values. See below for a full list.
Parameter type
No mapping
Blocked
Default
Static
CQL Expression

Explanation
The value of the view parameter will be passed as is to the stored query. No parameter will be passed if there is no view parameter of the same name.
This parameter will never be passed to the stored query
The specified value is used unless overwritten by a view parameter
The specified value is always used (view parameter value will be ignored)
An expression that will be evaluated on every request (see below for more details)

See Using a parametric SQL View for more details how clients pass view parameters to GeoServer.
CQL expressions
Parameter mappings configured as CQL expressions are evaluated for each request using a context derived
from the request query and the view parameters. General information on CQL expressions is available here
Expression.
The context contains the following properties that may be used in the expressions:
Property name
bboxMinX
bboxMinY
bboxMaxX
bboxMaxY
defaultSRS
viewparam:name

Explanation
Evaluates to a corner coordinate of the full extent of the query

Evaluates to the default SRS of the feature type
Evaluates to the value of the view parameter name in this query

5.5. Cascaded service data

179

GeoServer User Manual, Release 2.15.1

Configuring a cascaded stored query layer
In order to create a cascaded stored query layer the administrator invokes the Create new layer page. When
an External Web Feature Server is selected, the usual list of tables and views available for publication appears,
a link Configure Cascaded Stored Query. . . also appears:

Selecting the Configure Cascaded Stored Query. . . link opens a new page where the parameter mapping is set
up. By default all parameters are set up as No mapping.

5.5.3 External Web Map Server
GeoServer has the ability to proxy a remote Web Map Service (WMS). This process is sometimes known as
Cascading WMS. Loading a remote WMS is useful for many reasons. If you don’t manage or have access
180

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

to the remote WMS, you can now manage its output as if it were local. Even if the remote WMS is not
GeoServer, you can use GeoServer features to treat its output (watermarking, decoration, printing, etc).
To access a remote WMS, it is necessary to load it as a store in GeoServer. GeoServer must be able to access
the capabilities document of the remote WMS for the store to be successfully loaded.
Adding an external WMS
To connect to an external WMS, it is necessary to load it as a new store. To start, in the Web administration
interface, navigate to Stores → Add a new store → WMS. The option is listed under Other Data Sources.

Fig. 5.127: Adding an external WMS as a store

Fig. 5.128: Configuring a new external WMS store

5.5. Cascaded service data

181

GeoServer User Manual, Release 2.15.1

Option
Workspace

Data Source Name
Description
Enabled
Capabilities URL
User Name
Password
Max
concurrent
connections

Description
Name of the workspace to contain the store. This will also be the prefix of all of the
layer names published from the store. The workspace name on the remote WMS
is not cascaded.
Name of the store as known to GeoServer.
Description of the store.
Enables the store. If disabled, no data from the remote WMS will be served.
The full URL to access the capabilities document of the remote WMS.
If the WMS requires authentication, the user name to connect as.
If the WMS requires authentication, the password to connect with.
The maximum number of persistent connections to keep for this WMS.

When finished, click Save.
Configuring external WMS layers
When properly loaded, all layers served by the external WMS will be available to GeoServer. Before they
can be served, however, they will need to be individually configured (published) as new layers. See the
section on Layers for how to add and edit new layers. Once published, these layers will show up in the
Layer Preview and as part of the WMS capabilities document.
Features
Connecting a remote WMS allows for the following features:
• Dynamic reprojection. While the default projection for a layer is cascaded, it is possible to pass
the SRS parameter through to the remote WMS. Should that SRS not be valid on the remote server,
GeoServer will dynamically reproject the images sent to it from the remote WMS.
• GetFeatureInfo. WMS GetFeatureInfo requests will be passed to the remote WMS. If the remote WMS
supports the application/vnd.ogc.gml format the request will be successful.
• Full REST Configuration. See the REST section for more information about the GeoServer REST
interface.
Limitations
Layers served through an external WMS have some, but not all of the functionality of a local WMS.
• Layers cannot be styled with SLD.
• Alternate (local) styles cannot be used.
• Extra request parameters (time, elevation, cql_filter, etc.) cannot be used.
• GetLegendGraphic requests aren’t supported.
• Image format cannot be specified. GeoServer will attempt to request PNG images, and if that fails
will use the remote server’s default image format.

182

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

5.5.4 External Web Map Tile Server
GeoServer has the ability to proxy a remote Web Map Tile Service (WMTS). This process is sometimes
known as Cascading WMTS, even if the incoming requests follow the WMS protocol and the backing
service follows the WMTS one; the WMTS cascading functionality is more like a “protocol translator”,
where the different handled data (capabilities documents, images) are translated by the “WMTS cascading”
logic.
Loading a remote WMTS is useful for many reasons. If you don’t manage or have access to the remote
WMTS, you can now manage its output as if it were local. Even if you don’t have any control on the remote
WMTS, you can use GeoServer features to treat its output (watermarking, decoration, printing, etc).
To access a remote WMTS, it is necessary to load it as a store in GeoServer. GeoServer must be able to access
the capabilities document of the remote WMTS for the store to be successfully loaded.
Adding an external WMTS
To connect to an external WMTS, it is necessary to load it as a new store. To start, in the Web administration
interface, navigate to Stores → Add a new store → WMTS. The option is listed under Other Data Sources.

Fig. 5.129: Adding an external WMTS as a store

Option
Workspace
Data Source Name
Description
Enabled
Capabilities URL
User Name
Password
HTTP header name
HTTP header value
Max
concurrent
connections

Description
Name of the workspace to contain the store. This will also be the prefix of all of the
layer names published from the store.
Name of the store as known to GeoServer.
Description of the store.
Enables the store. If disabled, no data from the remote WMTS will be served.
The full URL to access the capabilities document of the remote WMTS.
If the WMTS requires authentication, the user name to connect as.
If the WMTS requires authentication, the password to connect with.
If the WMTS requires a custom HTTP header, the header name.
If the WMTS requires a custom HTTP header, the header value.
The maximum number of persistent connections to keep for this WMTS.

5.5. Cascaded service data

183

GeoServer User Manual, Release 2.15.1

Fig. 5.130: Configuring a new external WTMS store
When finished, click Save.
Configuring external WMTS layers
When properly loaded, all layers served by the external WMTS will be available to GeoServer. Before they
can be served, however, they will need to be individually configured (published) as new layers. See the
section on Layers for how to add and edit new layers. Once published, these layers will show up in the
Layer Preview and as part of the WMS capabilities document. If the WMTS layer has additional dimensions
(e.g. time), related info will be reported on the WMS capabilities as well.
Features
Connecting a remote WMTS allows for the following features:
• Dynamic reprojection. While the default projection for a layer is cascaded, it is possible to pass
the SRS parameter through to the remote WMS. Should that SRS not be valid on the remote server,
GeoServer will dynamically reproject the tiles sent to it from the remote WMTS.
• Full REST Configuration. See the REST section for more information about the GeoServer REST
interface.
Limitations
Layers served through an external WMTS have some, but not all of the functionality of a local layer.
• Layers cannot be styled with SLD.

184

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

• Alternate (local) styles cannot be used.
• GetFeatureInfo requests aren’t supported.
• GetLegendGraphic requests aren’t supported.
• Image format cannot be specified. GeoServer will attempt to request PNG images, and if that fails
will use the remote server’s default image format.

5.6 Application schemas
The application schema support (app-schema) extension provides support for Complex Features in
GeoServer WFS.
Note: You must install the app-schema plugin to use Application Schema Support.
GeoServer provides support for a broad selection of simple feature data stores, including property files,
shapefiles, and JDBC data stores such as PostGIS and Oracle Spatial. The app-schema module takes one or
more of these simple feature data stores and applies a mapping to convert the simple feature types into one
or more complex feature types conforming to a GML application schema.

Fig. 5.131: Three tables in a database are accessed using GeoServer simple feature support and converted into two
complex feature types.
The app-schema module looks to GeoServer just like any other data store and so can be loaded and used to
service WFS requests. In effect, the app-schema data store is a wrapper or adapter that converts a simple
feature data store into complex features for delivery via WFS. The mapping works both ways, so queries
against properties of complex features are supported.

5.6.1 Complex Features
To understand complex features, and why you would want use them, you first need to know a little about
simple features.
Simple features
A common use of GeoServer WFS is to connect to a data source such as a database and access one or more
tables, where each table is treated as a WFS simple feature type. Simple features contain a list of properties
that each have one piece of simple information such as a string or number. (Special provision is made for
geometry objects, which are treated like single items of simple data.) The Open Geospatial Consortium

5.6. Application schemas

185

GeoServer User Manual, Release 2.15.1

(OGC) defines three Simple Feature profiles; SF-0, SF-1, and SF-2. GeoServer simple features are close to
OGC SF-0, the simplest OGC profile.
GeoServer WFS simple features provide a straightforward mapping from a database table or similar structure to a “flat” XML representation, where every column of the table maps to an XML element that usually
contains no further structure. One reason why GeoServer WFS is so easy to use with simple features is that
the conversion from columns in a database table to XML elements is automatic. The name of each element
is the name of the column, in the namespace of the data store. The name of the feature type defaults to the
name of the table. GeoServer WFS can manufacture an XSD type definition for every simple feature type it
serves. Submit a DescribeFeatureType request to see it.
Benefits of simple features
• Easy to implement
• Fast
• Support queries on properties, including spatial queries on geometries
Drawbacks of simple features
• When GeoServer automatically generates an XSD, the XML format is tied to the database schema.
• To share data with GeoServer simple features, participants must either use the same database schema
or translate between different schemas.
• Even if a community could agree on a single database schema, as more data owners with different
data are added to a community, the number of columns in the table becomes unmanageable.
• Interoperability is difficult because simple features do not allow modification of only part of the
schema.
Simple feature example
For example, if we had a database table stations containing information about GPS stations:
| id | code |
name
|
location
|
+----+------+----------------+--------------------------+
| 27 | ALIC | Alice Springs | POINT(133.8855 -23.6701) |
| 4 | NORF | Norfolk Island | POINT(167.9388 -29.0434) |
| 12 | COCO | Cocos
| POINT(96.8339 -12.1883) |
| 31 | ALBY | Albany
| POINT(117.8102 -34.9502) |

GeoServer would then be able to create the following simple feature WFS response fragment:

ALIC
Alice Springs


-23.6701 133.8855




• Every row in the table is converted into a feature.
186

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

• Every column in the table is converted into an element, which contains the value for that row.
• Every element is in the namespace of the data store.
• Automatic conversions are applied to some special types like geometries, which have internal structure, and include elements defined in GML.
Complex features
Complex features contain properties that can contain further nested properties to arbitrary depth. In particular, complex features can contain properties that are other complex features. Complex features can be
used to represent information not as an XML view of a single table, but as a collection of related objects of
different types.
Simple feature
Properties are single data item, e.g. text, number, geometry
XML view of a single table
Schema automatically generated based on database
One large type
Straightforward
Interoperability relies on simplicity and customisation

Complex feature
Properties can be complex, including complex
features
Collection of related identifiable objects
Schema agreed by community
Multiple different types
Richly featured data standards
Interoperability through standardization

Benefits of complex features
• Can define information model as an object-oriented structure, an application schema.
• Information is modelled not as a single table but as a collection of related objects whose associations
and types may vary from feature to feature (polymorphism), permitting rich expression of content.
• By breaking the schema into a collection of independent types, communities need only extend those
types they need to modify. This simplifies governance and permits interoperability between related
communities who can agree on common base types but need not agree on application-specific subtypes..
Drawbacks of complex features
• More complex to implement
• Complex responses might slower if more database queries are required for each feature.
• Information modelling is required to standardize an application schema. While this is beneficial, it
requires effort from the user community.
Complex feature example
Let us return to our stations table and supplement it with a foreign key gu_id that describes the relationship between the GPS station and the geologic unit to which it is physically attached:

5.6. Application schemas

187

GeoServer User Manual, Release 2.15.1

| id | code |
name
|
location
| gu_id |
+----+------+----------------+--------------------------+-------+
| 27 | ALIC | Alice Springs | POINT(133.8855 -23.6701) | 32785 |
| 4 | NORF | Norfolk Island | POINT(167.9388 -29.0434) | 10237 |
| 12 | COCO | Cocos
| POINT(96.8339 -12.1883) | 19286 |
| 31 | ALBY | Albany
| POINT(117.8102 -34.9502) | 92774 |

The geologic unit is is stored in the table geologicunit:
| gu_id |
urn
|
text
|
+-------+---------------------------------------+---------------------+
| 32785 | urn:x-demo:feature:GeologicUnit:32785 | Metamorphic bedrock |
...

The simple features approach would be to join the stations table with the geologicunit table into one
view and then deliver “flat” XML that contained all the properties of both. The complex feature approach
is to deliver the two tables as separate feature types. This allows the relationship between the entities to be
represented while preserving their individual identity.
For example, we could map the GPS station to a sa:SamplingPoint with a gsml:GeologicUnit. The
these types are defined in the following application schemas respectively:
• http://schemas.opengis.net/sampling/1.0.0/sampling.xsd
– Documentation: OGC 07-002r3: http://portal.opengeospatial.org/files/?artifact_id=22467
• http://www.geosciml.org/geosciml/2.0/xsd/geosciml.xsd
– Documentation: http://www.geosciml.org/geosciml/2.0/doc/
The complex feature WFS response fragment could then be encoded as:
Alice Springs
ALIC


Metamorphic bedrock
urn:x,→demo:feature:GeologicUnit:32785





-23.6701 133.8855




• The property sa:sampledFeature can reference any other feature type, inline (included in the response) or by reference (an xlink:href URL or URN). This is an example of the use of polymorphism.
• The property sa:relatedObservation refers to the same GeologicUnit as sa:sampledFeature,
but by reference.
• Derivation of new types provides an extension point, allowing information models to be reused and
extended in a way that supports backwards compatibility.

188

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

• Multiple sampling points can share a single GeologicUnit. Application schemas can also define multivalued properties to support many-to-one or many-to-many associations.
• Each GeologicUnit could have further properties describing in detail the properties of the rock, such
as colour, weathering, lithology, or relevant geologic events.
• The GeologicUnit feature type can be served separately, and could be uniquely identified through its
properties as the same instance seen in the SamplingPoint.
Portrayal complex features (SF0)
Portrayal schemas are standardized schemas with flat attributes, also known as simple feature level 0 (SF0).
Because a community schema is still required (e.g. GeoSciML-Portrayal), app-schema plugin is still used to
map the database columns to the attributes.
• WFS CSV output format is supported for complex features with portrayal schemas. At the moment,
propertyName selection is not yet supported with csv outputFormat, so it always returns the full set
of attributes.
• Complex features with nesting and multi-valued properties are not supported with WFS CSV output
format.

5.6.2 Installation
Application schema support is a GeoServer extension and is downloaded separately.
• Download the app-schema plugin zip file for the same version of GeoServer.
• Unzip the app-schema plugin zip file to obtain the jar files inside. Do not unzip the jar files.
• Place the jar files in the WEB-INF/lib directory of your GeoServer installation.
• Restart GeoServer to load the extension (although you might want to configure it first [see below]).

5.6.3 WFS Service Settings
There are two GeoServer WFS service settings that are strongly recommended for interoperable complex
feature services. These can be enabled through the Services → WFS page on the GeoServer web interface or
by manually editing the wfs.xml file in the data directory,
Canonical schema location
The default GeoServer behaviour is to encode WFS responses that include a schemaLocation for the WFS
schema that is located on the GeoServer instance. A client will not know without retrieving the schema
whether it is identical to the official schema hosted at schemas.opengis.net. The solution is to encode
the schemaLocation for the WFS schema as the canonical location at schemas.opengis.net.
To enable this option, choose one of these:
1. Either: On the Service → WFS page under Conformance check Encode canonical WFS schema location.
2. Or: Insert the following line before the closing tag in wfs.xml:
true

5.6. Application schemas

189

GeoServer User Manual, Release 2.15.1

Encode using featureMember
By default GeoServer will encode WFS 1.1 responses with multiple features in a single
gml:featureMembers element. This will cause invalid output if a response includes a feature at
the top level that has already been encoded as a nested property of an earlier feature, because there is no
single element that can be used to encode this feature by reference. The solution is to encode responses
using gml:featureMember.
To enable this option, choose one of these:
1. Either: On the Service → WFS page under Encode response with select Multiple “featureMember” elements.
2. Or: Insert the following line before the closing tag in wfs.xml:
true

5.6.4 Configuration
Configuration of an app-schema complex feature type requires manual construction of a GeoServer data
directory that contains an XML mapping file and a datastore.xml that points at this mapping file. The
data directory also requires all the other ancillary configuration files used by GeoServer for simple features.
GeoServer can serve simple and complex features at the same time.
Workspace layout
The GeoServer data directory contains a folder called workspaces with the following structure:
workspaces
- gsml
- SomeDataStore
- SomeFeatureType
- featuretype.xml
- datastore.xml
- SomeFeatureType-mapping-file.xml

Note: The folder inside workspaces must have a name (the workspace name) that is the same as the
namespace prefix (gsml in this example).

Datastore
Each data store folder contains a file datastore.xml that contains the configuration parameters of
the data store. To create an app-schema feature type, the data store must be configured to load
the app-schema service module and process the mapping file. These options are contained in the
connectionParameters:
• namespace defines the XML namespace of the complex feature type.
• url is a file: URL that gives the location of the app-schema mapping file relative to the root of the
GeoServer data directory.
• dbtype must be app-schema to trigger the creation of an app-schema feature type.

190

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

5.6.5 Mapping File
An app-schema feature type is configured using a mapping file that defines the data source for the feature
and the mappings from the source data to XPaths in the output XML.
Outline
Here is an outline of a mapping file:


...
...
...
...

...


• namespaces defines all the namespace prefixes used in the mapping file.
• includedTypes (optional) defines all the included non-feature type mapping file locations that are
referred in the mapping file.
• sourceDataStores provides the configuration information for the source data stores.
• catalog is the location of the OASIS Catalog used to resolve XML Schema locations.
• targetTypes is the location of the XML Schema that defines the feature type.
• typeMappings give the relationships between the fields of the source data store and the elements of
the output complex feature.
Mapping file schema
• AppSchemaDataAccess.xsd is optional because it is not used by GeoServer. The presence of
AppSchemaDataAccess.xsd in the same folder as the mapping file enables XML editors to observe
its grammar and provide contextual help.
Settings
namespaces
The namespaces section defines all the XML namespaces used in the mapping file:

gsml
urn:cgi:xmlns:CGI:GeoSciML:2.0


gml
http://www.opengis.net/gml


5.6. Application schemas

191

GeoServer User Manual, Release 2.15.1


xlink
http://www.w3.org/1999/xlink


includedTypes (optional)
Non-feature types (eg. gsml:CompositionPart is a data type that is nested in gsml:GeologicUnit) may be
mapped separately for its reusability, but we don’t want to configure it as a feature type as we don’t want
to individually access it. Related feature types don’t need to be explicitly included here as it would have its
own workspace configuration for GeoServer to find it. The location path in Include tag is relative to the
mapping file. For an example, if gsml:CompositionPart configuration file is located in the same directory
as the gsml:GeologicUnit configuration:

gsml_CompositionPart.xml


sourceDataStores
Every mapping file requires at least one data store to provide data for features. app-schema reuses
GeoServer data stores, so there are many available types. See Data Stores for details of data store configuration. For example:


datastore

...


...


If you have more than one DataStore in a mapping file, be sure to give them each a distinct id.
catalog (optional)
The location of an OASIS XML Catalog configuration file, given as a path relative to the mapping file. See
Application Schema Resolution for more information. For example:
../../../schemas/catalog.xml

targetTypes
The targetTypes section lists all the application schemas required to define the mapping. Typically only
one is required. For example:

192

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1



http://www.geosciml.org/geosciml/2.0/xsd/geosciml.xsd



Mappings
typeMappings and FeatureTypeMapping
The typeMappings section is the heart of the app-schema module. It defines the mapping from
simple features to the the nested structure of one or more simple features. It consists of a list of
FeatureTypeMapping elements, which each define one output feature type. For example:


mappedfeature1
datastore
mappedfeature
gsml:MappedFeature
true
gsml:MappedFeature/gsml:shape/gml:Polygon


...

• mappingName is an optional tag, to identify the mapping in Feature Chaining when there are multiple
FeatureTypeMapping instances for the same type. This is solely for feature chaining purposes, and
would not work for identifying top level features.
• sourceDataStore must be an identifier you provided when you defined a source data store the
sourceDataStores section.
• sourceType is the simple feature type name. For example:
– a table or view name, lowercase for PostGIS, uppercase for Oracle.
– a property file name (without the .properties suffix)
• targetElement is the the element name in the target application schema. This is the same as the
WFS feature type name.
• isDenormalised is an optional tag (default true) to indicate whether this type contains denormalised data or not. If data is not denormalised, then app-schema will build a more efficient query to
apply the global feature limit. When combined with a low global feature limit (via Services –> WFS),
setting this option to false can prevent unnecessary processing and database lookups from taking
place.
• defaultGeometry can be used to explicitly define the attribute of the feature type that should be
used as the default geometry, this is more relevant in WMS than WFS. The default geometry XML path
can reference any attribute of the feature type, exactly the same path that would be used to reference
the desired property in a OGC filter. The path can reference a nested attribute belonging to a chained
feature having a zero or one relationship with the root feature type.

5.6. Application schemas

193

GeoServer User Manual, Release 2.15.1

attributeMappings and AttributeMapping
attributeMappings comprises a list of AttributeMapping elements:

...
...
...
...
...
...


targetAttribute
targetAttribute is the XPath to the output element, in the context of the target element. For example,
if the containing mapping is for a feature, you should be able to map a gml:name property by setting the
target attribute:
gml:name

Multivalued attributes resulting from Denormalised sources are automatically encoded. If you wish to encode
multivalued attributes from different input columns as a specific instance of an attribute, you can use a
(one-based) index. For example, you can set the third gml:name with:
gml:name[3]

The reserved name FEATURE_LINK is used to map data that is not encoded in XML but is required for use
in Feature Chaining.
idExpression (optional)
A CQL expression that is used to set the custom gml:id of the output feature type. This should be the name
of a database column on its own. Using functions would cause an exception because it is not supported
with the default joining implementation.
Note: Every feature must have a gml:id. This requirement is an implementation limitation (strictly,
gml:id is optional in GML).
• If idExpression is unspecified, gml:id will be ., e.g.
MAPPEDFEATURE.1.
• In the absence of primary keys, this will be ., e.g.
MAPPEDFEATURE.fid--46fd41b8_1407138b56f_-7fe0.
• If using property files instead of database tables, the default gml:id will be the row key found before
the equals (“=”) in the property file, e.g. the feature with row “mf1=Mudstone|POINT(1 2)|. . . ” will
have gml:id mf1.

Note: gml:id must be an NCName.

194

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

sourceExpression (optional)
Use a sourceExpression tag to set the element content from source data. For example, to set the element
content from a column called DESCRIPTION:
DESCRIPTION

If sourceExpression is not present, the generated element is empty (unless set by another mapping).
You can use CQL expressions to calculate the content of the element. This example concatenated strings
from two columns and a literal:

strConCat(FIRST , strConCat(' followed by ', SECOND))


You can also use CQL functions for vocabulary translations.
Warning: Avoid use of CQL expressions for properties that users will want to query, because the
current implementation cannot reverse these expressions to generate efficient SQL, and will instead
read all features to calculate the property to find the features that match the filter query. Falling back
to brute force search makes queries on CQL-calculated expressions very slow. If you must concatenate
strings to generate content, you may find that doing this in your database is much faster.

linkElement and linkField (optional)
The presence of linkElement and linkField change the meaning of sourceExpression to a Feature
Chaining mapping, in which the source of the mapping is the feature of type linkElement with property
linkField matching the expression. For example, the following sourceExpression uses as the result
of the mapping the (possibly multivalued) gsml:MappedFeature for which gml:name[2] is equal to
the value of URN for the source feature. This is in effect a foreign key relation:

URN
gsml:MappedFeature
gml:name[2]


The feature type gsml:MappedFeature might be defined in another mapping file. The linkField can
be FEATURE_LINK if you wish to relate the features by a property not exposed in XML. See Feature Chaining
for a comprehensive discussion.
For special cases, linkElement could be an OCQL function, and linkField could be omitted. See Polymorphism for further information.
targetAttributeNode (optional)
targetAttributeNode is required wherever a property type contains an abstract element and appschema cannot determine the type of the enclosed attribute.
In this example, om:result is of xs:anyType, which is abstract. We can use targetAttributeNode to
set the type of the property type to a type that encloses a non-abstract element:

5.6. Application schemas

195

GeoServer User Manual, Release 2.15.1


om:result
gml:MeasureType

TOPAGE


xsi:type
'gml:MeasureType'


uom
'http://www.opengis.net/def/uom/UCUM/0/Ma'



If the casting type is complex, the specific type is implicitly determined by the XPath in targetAttribute
and targetAttributeNode is not required. E.g., in this example om:result is automatically specialised as a
MappedFeatureType:

om:result/gsml:MappedFeature/gml:name

NAME



Although it is not required, we may still specify targetAttributeNode for the root node, and map the children attributes as per normal. This mapping must come before the mapping for the enclosed elements. By
doing this, app-schema will report an exception if a mapping is specified for any of the children attributes
that violates the type in targetAttributeNode. E.g.:

om:result
gsml:MappedFeatureType


om:result/gsml:MappedFeature/gml:name

NAME



Note that the GML encoding rules require that complex types are never the direct property of another complex type; they are always contained in a property type to ensure that their type is encoded in a surrounding
element. Encoded GML is always type/property/type/property. This is also known as the GML “striping” rule. The consequence of this for app-schema mapping files is that targetAttributeNode must be
applied to the property and the type must be set to the XSD property type, not to the type of the contained
attribute (gsml:CGI_TermValuePropertyType not gsml:CGI_TermValueType). Because the XPath
refers to a property type not the encoded content, targetAttributeNode appears in a mapping with
targetAttribute and no other elements when using with complex types.
The XML encoder will encode nested complex features that are mapped to a complex type that does not
respect the GML striping rule. The Java configuration property encoder.relaxed can be set to false to
disable this behavior.

196

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

encodeIfEmpty (optional)
The encodeIfEmpty element will determine if an attribute will be encoded if it contains a null or empty
value. By default encodeIfEmpty is set to false therefore any attribute that does not contain a value will
be skipped:
true

encodeIfEmpty can be used to bring up attributes that only contain client properties such as
xlink:title.
isMultiple (optional)
The isMultiple element states whether there might be multiple values for this attribute, coming from
denormalised rows. Because the default value is false and it is omitted in this case, it is most usually seen
as:
true

For example, the table below is denormalised with NAME column having multiple values:
ID
gu.25678
gu.25678

NAME
Yaugher Volcanic Group 1
Yaugher Volcanic Group 2

DESCRIPTION
Olivine basalt, tuff, microgabbro
Olivine basalt, tuff, microgabbro

The configuration file specifies isMultiple for gml:name attribute that is mapped to the NAME column:

gml:name

NAME

true

codeSpace
'urn:ietf:rfc:2141'



The output produces multiple gml:name attributes for each feature grouped by the id:

Olivine basalt, tuff, microgabbro
Yaugher Volcanic Group 1
Yaugher Volcanic Group 2
...

isList (optional)
The isList element states whether there might be multiple values for this attribute, concatenated as a list.
The usage is similar with isMultiple, except the values appear concatenated inside a single node instead
of each value encoded in a separate node. Because the default value is false and it is omitted in this case,
it is most usually seen as:

5.6. Application schemas

197

GeoServer User Manual, Release 2.15.1

true

For example, the table below has multiple POSITION for each feature:
ID
ID1.2
ID1.2
ID1.2
ID1.2
ID1.2

POSITION
1948-05
1948-06
1948-07
1948-08
1948-09

The configuration file uses isList on timePositionList attribute mapped to POSITION column:

csml:timePositionList

POSITION

true


The output produced:


1949-05 1949-06 1949-07 1949-08 1949-09



ClientProperty (optional, multivalued)
A mapping can have one or more ClientProperty elements which set XML attributes on the mapping
target. Each ClientProperty has a name and a value that is an arbitrary CQL expression. No OCQL
element is used inside value.
This example of a ClientProperty element sets the codeSpace XML attribute to the literal string
urn:ietf:rfc:2141. Note the use of single quotes around the literal string. This could be applied to
any target attribute of GML CodeType:

codeSpace
'urn:ietf:rfc:2141'


When the GML association pattern is used to encode a property by reference, the xlink:href attribute is
set and the element is empty. This ClientProperty element sets the xlink:href XML attribute to to the
value of the RELATED_FEATURE_URN field in the data source (for example, a column in an Oracle database
table). This mapping could be applied to any property type, such a gml:FeaturePropertyType, or other
type modelled on the GML association pattern:

xlink:href

198

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

RELATED_FEATURE_URN


See the discussion in Feature Chaining for the special case in which xlink:href is created for multivalued
properties by reference.
CQL
CQL functions enable data conversion and conditional behaviour to be specified in mapping files.
• See CQL functions for information on additional functions provided by the app-schema plugin.
• The uDig manual includes a list of CQL functions:
– http://udig.refractions.net/confluence/display/EN/Constraint+Query+Language
• CQL string literals are enclosed in single quotes, for example 'urn:ogc:def:nil:OGC:missing'.
Database identifiers
When referring to database table/view names or column names, use:
• lowercase for PostGIS
• UPPERCASE for Oracle Spatial and ArcSDE
Denormalised sources
Multivalued properties from denormalised sources (the same source feature ID appears more than once)
are automatically encoded. For example, a view might have a repeated id column with varying name so
that an arbitrarily large number of gml:name properties can be encoded for the output feature.
Warning: Denormalised sources must grouped so that features with duplicate IDs are provided without
any intervening features. This can be achieved by ensuring that denormalised source features are sorted
by ID. Failure to observe this restriction will result in data corruption. This restriction is however not
necessary when using Joining Support For Performance because then ordering will happen automatically.

Attributes with cardinality 1..N
Consider the following two tables, the first table contains information related to meteorological stations:
ID
st.1
st.2

NAME
Station 1
Station 2

The second table contains tags that are associated with meteorological stations:
ID
tg.1
tg.2
tg.2

5.6. Application schemas

STATION_ID
st.1
st.1
st.2

TAG
temperature
wind
pressure

CODE
X1Y
X2Y
X3Y

199

GeoServer User Manual, Release 2.15.1

A station can have multiple tags, establishing a one to many relationship between stations and tags, the
GML representation of the first station should look like this:
(...)

Station 1
temperature
wind

(...)

Mappings with a one to many relationship are supported with a custom syntax in JDBC based data stores
and Apache Solr data store.
SQL based data stores
When using JDBC based data stores attributes with a 1..N relationship can be mapped like this:
(...)

st:tag

ID
TAGS
STATION_ID
TAG


st:code
CODE


(...)

The targetValue refers to the value of the  element, the client property is mapped with the
usual syntax. Behind the scenes App-Schema will take care of associating the st:code attribute value with
the correct tag.
Apache Solr
When using Apache Solr data stores, 1..N relationships can be handled with multiValued fields and
mapped like this:
(...)

st:tag
TAG

st:code
CODE


(...)

200

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

External Apache Solr Index
Is possible to use an external Apache Solr index to speed up text based searches. Consider the following
WFS GetFeatureRequest:




st:Station/st:measurement/st:Measurement/st:description
*high*





This request will return all the stations that have at least one measurement that contains the text high in its
description. This type of text based queries are (usually) quite expensive to execute in relational data bases.
Apache Solr is a well known open source project that aims to solve those type of performance issues, it
allow us to index several fields and efficiently query those fields. Although Apache Solr allow us to index
several types of fields, e.g. numbers or even latitudes longitudes, where it really shines is when dealing
with text fields and text based queries.
The goal of external indexes is to allow App-Schema to take advantage of Apache Solr text searches performance and at the same time to take advantage of relational databases relational capabilities. In practice, this
means that the full data will be stored in the relational database and we will only need to index in Apache
Solr the fields we need to improve our text based queries.
Using the stations use case as an example, our data will be stored in a relational database, e.g. PostgreSQL,
and we will index the possible descriptions measurements values in an Apache Solr index.
Our mapping file will look like this:



gml
http://www.opengis.net/gml/3.2


st
http://www.stations.org/1.0




stations_solr
http://localhost:8983/solr/stations_index



stations_db


5.6. Application schemas

201

GeoServer User Manual, Release 2.15.1


dbtype
postgisng






./stations.xsd




stations_db
stations
st:Station

stations_solr
stations_index


st:Station

id


description_txt


FEATURE_LINK[1]

station_id







To be able to use an external Apache Solr index, we need at least to:
• declare the Solr data store and the index: this is done in the root feature type mapping, e.g. st:Station.
• map the Solr index field that matches the database primary key: this is done id mapping of the root
feature type, e.g.“id“.
• map each attribute that is indexed in Apache Solr: this is done using the indexField element, e.g
description_txt.
Is worth mentioning that if an external Solr index was defined, App-Schema will always query the external
Solr index first and then query the relational database.

5.6.6 Application Schema Resolution
To be able to encode XML responses conforming to a GML application schema, the app-schema plugin
must be able to locate the application schema files (XSDs) that define the schema. This page describes the
schema resolution process.
Schema downloading is now automatic for most users
GeoServer will automatically download and cache (see Cache below) all the schemas it needs the first time
it starts if:
1. All the application schemas you use are accessed via http/https URLs, and
2. Your GeoServer instance is deployed on a network that permits it to download them.
Note: This is the recommended way of using GeoServer app-schema for most users.
If cached downloading is used, no manual handling of schemas will be required. The rest of this page is for
those with more complicated arrangements, or who wish to clear the cache.
Resolution order
The order of sources used to resolve application schemas is:
5.6. Application schemas

203

GeoServer User Manual, Release 2.15.1

1. OASIS Catalog
2. Classpath
3. Cache
Every attempt to load a schema works down this list, so imports can be resolved from sources other than
that used for the originating document. For example, an application schema in the cache that references a
schema found in the catalog will use the version in the catalog, rather than caching it. This allows users to
supply unpublished or modified schemas sourced from, for example, the catalog, at the cost of interoperability (how do WFS clients get them?).
OASIS Catalog
An OASIS XML Catalog is a standard configuration file format that instructs an XML processing system
how to process entity references. The GeoServer app-schema resolver uses catalog URI semantics to locate
application schemas, so uri or rewriteURI entries should be present in your catalog. The optional mapping file catalog element provides the location of the OASIS XML Catalog configuration file, given as a
path relative to the mapping file, for example:
../../../schemas/catalog.xml

Earlier versions of the app-schema plugin required all schemas to be present in the catalog. This is no
longer the case. Because the catalog is searched first, existing catalog-based deployments will continue to
work as before.
To migrate an existing GeoServer app-schema deployment that uses an OASIS Catalog to instead use
cached downloads (see Cache below), remove all catalog elements from your mapping files and restart
GeoServer.
Classpath
Java applications such as GeoServer can load resources from the Java classpath. GeoServer app-schema uses
a simple mapping from an http or https URL to a classpath resource location. For example, an application
schema published at http://schemas.example.org/exampleml/exml.xsd would be found on the
classpath if it was stored either:
• at /org/example/schemas/exampleml/exml.xsd in a JAR file on the classpath (for example, a
JAR file in WEB-INF/lib) or,
• on the local filesystem at WEB-INF/classes/org/example/schemas/exampleml/exml.xsd .
The ability to load schemas from the classpath is intended to support testing, but may be useful to users
whose communities supply JAR files containing their application schemas.
Cache
If an application schema cannot be found in the catalog or on the classpath, it is downloaded from the
network and stored in a subdirectory app-schema-cache of the GeoServer data directory.
• Once schemas are downloaded into the cache, they persist indefinitely, including over GeoServer
restarts.
• No attempt will be made to retrieve new versions of cached schemas.
• To clear the cache, remove the subdirectory app-schema-cache of the GeoServer data directory and
restart GeoServer.

204

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

GeoServer app-schema uses a simple mapping from an http or https URL to local filesystem path.
For example, an application schema published at http://schemas.example.org/exampleml/exml.
xsd would be downloaded and stored as app-schema-cache/org/example/schemas/exampleml/
exml.xsd . Note that:
• Only http and https URLs are supported.
• Port numbers, queries, and fragments are ignored.
If your GeoServer instance is deployed on a network whose firewall rules prevent outgoing TCP connections on port 80 (http) or 443 (https), schema downloading will not work. (For security reasons, some
service networks [“demilitarised zones”] prohibit such outgoing connections.) If schema downloading is
not permitted on your network, there are three solutions:
1. Either: Install and configure GeoServer on another network that can make outgoing TCP connections,
start GeoServer to trigger schema download, and then manually copy the app-schema-cache directory to the production server. This is the easiest option because GeoServer automatically downloads
all the schemas it needs, including dependencies.
2. Or: Deploy JAR files containing all required schema files on the classpath (see Classpath above).
3. Or: Use a catalog (see OASIS Catalog above).
Warning: System property “schema.cache.dir” with a cache directory location is required for using a
mapping file from a remote URL with ‘http://’ or ‘https://’ protocol.

5.6.7 Supported GML Versions
GML 3.1.1
• GML 3.1.1 application schemas are supported for WFS 1.1.0.
• Clients must specify WFS 1.1.0 in requests because the GeoServer default is WFS 2.0.0.
• GET URLs must contain version=1.1.0 to set the WFS version to 1.1.0.
GML 3.2.1
• GML 3.2.1 application schemas are supported for WFS 1.1.0 and (incomplete) WFS 2.0.0.
• Some WFS 2.0.0 features not in WFS 1.1.0 such as GetFeatureById are not yet supported.
• Clients using WFS 1.1.0 must specify WFS 1.1.0 in requests and select the gml32 output format for
GML 3.2.1.
• To use WFS 1.1.0 for GML 3.2.1, GET URLs must contain version=1.1.0 to set the WFS version to
1.1.0 and outputFormat=gml32 to set the output format to GML 3.2.1.
• The default WFS version is 2.0.0, for which the default output format is GML 3.2.1.
• All GML 3.2.1 responses are contained in a WFS 2.0.0 FeatureCollection element, even for WFS
1.1.0 requests, because a WFS 1.1.0 FeatureCollection cannot contain GML 3.2.1 features.

5.6. Application schemas

205

GeoServer User Manual, Release 2.15.1

Secondary namespace for GML 3.2.1 required
GML 3.2.1 WFS responses are delivered in a WFS 2.0.0 FeatureCollection. Unlike WFS 1.1.0, WFS 2.0.0
does not depend explicitly on any GML version. As a consequence, the GML namespace is secondary and
must be defined explicitly as a secondary namespace. See Secondary Namespaces for details.
For example, to use the prefix gml for GML 3.2, create workspaces/gml/namespace.xml containing:

gml_namespace
gml
http://www.opengis.net/gml/3.2


and workspaces/gml/workspace.xml containing:

gml_workspace
gml


Failure to define the gml namespace prefix with a secondary namespace will result in errors like:
java.io.IOException: The prefix "null" for element "null:name" is not bound.

while encoding a response (in this case one containing gml:name), even if the namespace prefix is defined
in the mapping file.
GML 3.2.1 geometries require gml:id
GML 3.2.1 requires that all geometries have a gml:id. While GeoServer will happily encode WFS responses without gml:id on geometries, these will be schema-invalid. Encoding a gml:id on a geometry
can be achieved by setting an idExpression in the mapping for the geometry property. For example,
gsml:shape is a geometry property and its gml:id might be generated with:

gsml:shape

strConcat('shape.', getId())


SHAPE



In this example, getId() returns the gml:id of the containing feature, so each geometry will have a
unique gml:id formed by appending the gml:id of the containing feature to the string "shape.".
If a multigeometry (such as a MultiPoint or MultiSurface) is assigned a gml:id of (for example)
parentid, to permit GML 3.2.1 schema-validity, each geometry that the multigeometry contains will be
automatically assigned a gml:id of the form parentid.1, parentid.2, . . . in order.
GML 3.3
The proposed GML 3.3 is itself a GML 3.2.1 application schema; preliminary testing with drafts of GML 3.3
indicates that it works with app-schema as expected.
206

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

5.6.8 Secondary Namespaces
What is a secondary namespace?
A secondary namespace is one that is referenced indirectly by the main schema, that is, one schema imports
another one as shown below:
a.xsd imports b.xsd
b.xsd imports c.xsd

(using a, b and c as the respective namespace prefixes for a.xsd, b.xsd and c.xsd):
a.xsd declares b:prefix
b.xsd declares c:prefix

The GeoTools encoder does not honour these namespaces and writes out:
"a:" , "b:" but NOT "c:"

The result is c’s element being encoded as:


When to configure for secondary namespaces
If your application spans several namespaces which may be very common in application schemas.
A sure sign that calls for secondary namespace configuration is when prefixes for namespaces are printed
out as the literal string “null” or error messages like:
java.io.IOException: The prefix "null" for element "null:something" is not bound.

Note: When using secondary namespaces, requests involving complex featuretypes must be made to the
global OWS service only, not to Virtual Services. This is because virtual services are restricted to a single
namespace, and thus are not able to access secondary namespaces.
In order to allow GeoServer App-Schema to support secondary namespaces, please follow the steps outlined below:
Using the sampling namespace as an example.
Step 1:Create the Secondary Namespace folder
Create a folder to represent the secondary namespace in the data/workspaces directory, in our example
that will be the “sa” folder.
Step 2:Create files
Create two files below in the “sa” folder:
1. namespace.xml
2. workspace.xml

5.6. Application schemas

207

GeoServer User Manual, Release 2.15.1

Step 3:Edit content of files
Contents of these files are as follows:
namespace.xml(uri is a valid uri for the secondary namespace, in this case the sampling namespace uri):

sa_workspace
sa
http://www.opengis.net/sampling/1.0


workspace.xml:

sa_workspace
sa


That’s it.
Your workspace is now configured to use a Secondary Namespace.

5.6.9 CQL functions
CQL functions enable data conversion and conditional behaviour to be specified in mapping files. Some of
these functions are provided by the app-schema plugin specifically for this purpose.
• The uDig manual includes a list of CQL functions:
– http://udig.refractions.net/confluence/display/EN/Constraint%20Query%20Language.html
• CQL string literals are enclosed in single quotes, for example 'urn:ogc:def:nil:OGC:missing'.
• Single quotes are represented in CQL string literals as two single quotes, just as in SQL. For example,
'yyyy-MM-dd''T''HH:mm:ss''Z''' for the string yyyy-MM-dd'T'HH:mm:ss'Z'.
Vocabulary translation
This section describes how to serve vocabulary translations using some function expressions in application
schema mapping file. If you’re not familiar with application schema mapping file, read Mapping File.
Recode
This is similar to if_then_else function, except that there is no default clause. You have to specify a translation
value for every vocabulary key.
Syntax:
Recode(COLUMN_NAME, key1, value1, key2, value2,...)

• COLUMN_NAME: column name to get values from
Example:

208

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1


gml:name

Recode(ABBREVIATION, '1GRAV',
,→'urn:cgi:classifier:CGI:SimpleLithology:2008:gravel',
'1TILL',
,→'urn:cgi:classifier:CGI:SimpleLithology:2008:diamictite',
'6ALLU',
,→'urn:cgi:classifier:CGI:SimpleLithology:2008:sediment')




The above example will map gml:name value to urn:cgi:classifier:CGI:SimpleLithology:2008:gravel if the ABBREVIATION column value is 1GRAV.
Categorize
This is more suitable for numeric keys, where the translation value is determined by the key’s position
within the thresholds.
Syntax:
Categorize(COLUMN_NAME, default_value, threshold 1, value 1, threshold 2, value 2, ...
,→, [preceding/succeeding])

• COLUMN_NAME: data source column name
• default_value: default value to be mapped if COLUMN_NAME value is not within the threshold
• threshold(n): threshold value
• value(n): value to be mapped if the threshold is met
• preceding/succeeding:
– optional, succeeding is used by default if not specified.
– not case sensitive.
– preceding: value is within threshold if COLUMN_NAME value > threshold
– succeeding: value is within threshold if COLUMN_NAME value >= threshold
Example:

gml:description

Categorize(CGI_LOWER_RANGE, 'missing_value', 1000, 'minor', 5000,
,→'significant')



The above example means gml:description value would be significant if CGI_LOWER_RANGE column
value is >= 5000.

5.6. Application schemas

209

GeoServer User Manual, Release 2.15.1

Vocab
This function is more useful for bigger vocabulary pairs. Instead of writing a long key-to-value pairs in the
function, you can keep them in a separate properties file. The properties file serves as a lookup table to the
function. It has no header, and only contains the pairs in ”=” format.
Syntax:
Vocab(COLUMN_NAME, properties file)

• COLUMN_NAME: column name to get values from
• properties file: absolute path of the properties file
Example:
Properties file:
1GRAV=urn:cgi:classifier:CGI:SimpleLithology:2008:gravel
1TILL=urn:cgi:classifier:CGI:SimpleLithology:2008:diamictite
6ALLU=urn:cgi:classifier:CGI:SimpleLithology:2008:sediment

Mapping file:

gml:name

Vocab(ABBREVIATION, strconcat('${config.parent}', '/mapping.properties'))
,→



The above example will map gml:name to urn:cgi:classifier:CGI:SimpleLithology:2008:gravel if ABBREVIATION value is 1GRAV.
This example uses the config.parent predefined interpolation property to specify a vocabulary properties file in the same directory as the mapping file. See Property Interpolation for details.
Geometry creation
toDirectPosition
This function converts double values to DirectPosition geometry type. This is needed when the data
store doesn’t have geometry type columns. This function expects:
Literal 'SRS_NAME' (optional)
Expression expression of SRS name if 'SRS_NAME' is present as the first argument
Expression name of column pointing to first double value
Expression name of column pointing to second double value (optional, only for 2D)
ToEnvelope
ToEnvelope function can take in the following set of parameters and return as either Envelope or
ReferencedEnvelope type:

210

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Option 1 (1D Envelope):
ToEnvelope(minx,maxx)

Option 2 (1D Envelope with crsname):
ToEnvelope(minx,maxx,crsname)

Option 3 (2D Envelope):
ToEnvelope(minx,maxx,miny,maxy)

Option 4 (2D Envelope with crsname):
ToEnvelope(minx,maxx,miny,maxy,crsname)

toPoint
This function converts double values to a 2D Point geometry type. This is needed when the data store
doesn’t have geometry type columns. This function expects:
Literal 'SRS_NAME' (optional)
Expression expression of SRS name if 'SRS_NAME' is present as the first argument
Expression name of column pointing to first double value
Expression name of column pointing to second double value
Expression expression of gml:id (optional)
toLineString
This function converts double values to 1D LineString geometry type. This is needed to express 1D borehole
intervals with custom (non EPSG) CRS.
Literal 'SRS_NAME' (EPSG code or custom SRS)
Expression name of column pointing to first double value
Expression name of column pointing to second double value
Reference
toXlinkHref
This function redirects an attribute to be encoded as xlink:href, instead of being encoded as a full attribute.
This is useful in polymorphism, where static client property cannot be used when the encoding is conditional. This function expects:
Expression REFERENCE_VALUE (could be another function or literal)

5.6. Application schemas

211

GeoServer User Manual, Release 2.15.1

Date/time formatting
FormatDateTimezone
A function to format a date/time using a SimpleDateFormat pattern in a time zone supported by Java. This
function improves on dateFormat, which formats date/time in the server time zone and can produce
unintended results. Note that the term “date” is derived from a Java class name; this class represents a
date/time, not just a single day.
Syntax:
FormatDateTimezone(pattern, date, timezone)

pattern formatting pattern supported by SimpleDateFormat, for example 'yyyy-MM-dd'.
Use
two single quotes to include a literal single quote in a CQL string literal, for example
'yyyy-MM-dd''T''HH:mm:ss''Z'''.
date the date/time to be formatted or its string representation, for example '1948-01-01T00:00:00Z'.
An exception will be returned if the date is malformed (and not null). Database types with time zone
information are recommended.
timezone the name of a time zone supported by Java, for example 'UTC' or 'Canada/Mountain'. Note
that unrecognised timezones will silently be converted to UTC.
This function returns null if any parameter is null.
This example formats date/times from a column POSITION in UTC for inclusion in a csml:TimeSeries:

csml:timePositionList

FormatDateTimezone('yyyy-MM-dd''T''HH:mm:ss''Z''', POSITION, 'UTC')

true


5.6.10 Property Interpolation
Interpolation in this context means the substitution of variables into strings. GeoServer app-schema supports the interpolation of properties (the Java equivalent of environment variables) into app-schema mapping files. This can be used, for example, to simplify the management of database connection parameters
that would otherwise be hardcoded in a particular mapping file. This enables data directories to be given to
third parties without inapplicable authentication or system configuration information. Externalising these
parameters make management easier.
Defining properties
• If the system property app-schema.properties is not set, properties are loaded from WEB-INF/
classes/app-schema.properties (or another resource /app-schema.properties on the
classpath).
• If the system property app-schema.properties is set, properties are loaded from the file named
as the value of the property. This is principally intended for debugging, and is designed to be used in
an Eclipse launch configuration.

212

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

– For example, if the JVM is started with -Dapp-schema.properties=/path/to/some/
local.properties, properties are loaded from /path/to/some/local.properties.
• System properties override properties defined in a configuration file, so if you define -Dsome.
property at the java command line, it will override a value specified in the app-schema.
properties file. This is intended for debugging, so you can set a property file in an Eclipse launch
configuration, but override some of the properties contained in the file by setting them explicitly as
system properties.
• All system properties are available for interpolation in mapping files.
Predefined properties
If not set elsewhere, the following properties are set for each mapping file:
• config.file is set to the name of the mapping file
• config.parent is set to the name of the directory containing the mapping file
Using properties
• Using ${some.property} anywhere in the mapping file will cause it to be replaced by the value of
the property some.property.
• It is an error for a property that has not been set to be used for interpolation.
• Interpolation is performed repeatedly, so values can contain new interpolations. Use this behaviour
with caution because it may cause an infinite loop.
• Interpolation is performed before XML parsing, so can be used to include arbitrary chunks of XML.
Example of property interpolation
This example defines an Oracle data store, where the connection parameter are interpolated from properties:


datastore


dbtype
Oracle


host
${example.host}


port
1521


database
${example.database}



5.6. Application schemas

213

GeoServer User Manual, Release 2.15.1

user
${example.user}


passwd
${example.passwd}





Example property file
This sample property file gives the property values that are interpolated into the mapping file fragment
above. These properties can be installed in WEB-INF/classes/app-schema.properties in your
GeoServer installation:
example.host = database.example.com
example.database = example
example.user = dbuser
example.passwd = s3cr3t

5.6.11 Data Stores
The app-schema Mapping File requires you to specify your data sources in the sourceDataStores section.
For GeoServer simple features, these are configured using the web interface, but because app-schema lacks
a web configuration interface, data stores must be configured by editing the mapping file.
Many configuration options may be externalised through the use of Property Interpolation.
The DataStore element
A DataStore configuration consists of
• an id, which is an opaque identifier used to refer to the data store elsewhere in a mapping file, and
• one or more Parameter elements, which each contain the name and value of one parameter, and
are used to configure the data store.
An outline of the DataStore element:

datastore


...
...

...



Parameter order is not significant.

214

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Database options
Databases such as PostGIS, Oracle, and ArcSDE share some common or similar configuration options.
name
dbtype
host
port
database
instance
schema
user
passwd
Expose
primary keys

Meaning
Database type
Host name or IP address of
database server
TCP port on database server
PostGIS/Oracle database
ArcSDE instance
The database schema
The user name used to login to the
database server
The password used to login to the
database server
Columns with primary keys available for mapping

value examples
postgisng, Oracle, arcsde
database.example.org, 192.168.3.12
Default if omitted: 1521 (Oracle), 5432 (PostGIS), 5151 (ArcSDE)

Default is false, set to true to use primary
key columns in mapping

PostGIS
Set the parameter dbtype to postgisng to use the PostGIS NG (New Generation) driver bundled with
GeoServer 2.0 and later.
Example:

datastore


dbtype
postgisng


host
postgresql.example.org


port
5432


database
test


user
test


passwd
test


5.6. Application schemas

215

GeoServer User Manual, Release 2.15.1




Note: PostGIS support is included in the main GeoServer bundle, so a separate plugin is not required.

Oracle
Set the parameter dbtype to Oracle to use the Oracle Spatial NG (New Generation) driver compatible
with GeoServer 2.0 and later.
Example:

datastore


dbtype
Oracle


host
oracle.example.org


port
1521


database
demodb


user
orauser


passwd
s3cr3t




Note: You must install the Oracle plugin to connect to Oracle Spatial databases.

ArcSDE
This example connects to an ArcSDE database:

datastore



216

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

dbtype
arcsde


server
arcsde.example.org


port
5151


instance
sde


user
demo


password
s3cr3t


datastore.allowNonSpatialTables
true




The use of non-spatial tables aids delivery of application schemas that use non-spatial properties.
Note: You must install the ArcSDE plugin to connect to ArcSDE databases.

Shapefile
Shapefile data sources are identified by the presence of a parameter url, whose value should be the file
URL for the .shp file.
In this example, only the url parameter is required. The others are optional:

shapefile


url
file:/D:/Workspace/shapefiles/VerdeRiverBuffer.shp


memory mapped buffer
false


create spatial index
true

5.6. Application schemas

217

GeoServer User Manual, Release 2.15.1



charset
ISO-8859-1




Note: The url in this case is an example of a Windows filesystem path translated to URL notation.

Note: Shapefile support is included in the main GeoServer bundle, so a separate plugin is not required.

Property file
Property files are configured by specifying a directory that is a file: URI.
• If the directory starts with file:./ it is relative to the mapping file directory. (This is an invalid URI,
but it works.)
For example, the following data store is used to access property files in the same directory as the mapping
file:

propertyfile


directory
file:./




A property file data store contains all the feature types stored in .properties files in the directory. For
example, if the directory contained River.properties and station.properties, the data store would be able
to serve them as the feature types River and station. Other file extensions are ignored.
Note: Property file support is included in the main GeoServer bundle, so a separate plugin is not required.

JNDI
Defining a JDBC data store with a jndiReferenceName allows you to use a connection pool provided
by your servlet container. This allows detailed configuration of connection pool parameters and sharing of
connections between data sources, and even between servlets.
To use a JNDI connection provider:
1. Specify a dbtype parameter to to indicate the database type. These values are the same as for the
non-JNDI examples above.
2. Give the jndiReferenceName you set in your servlet container. Both the abbreviated form jdbc/
oracle form, as in Tomcat, and the canonical form java:comp/env/jdbc/oracle are supported.
218

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

This example uses JNDI to obtain Oracle connections:

datastore


dbtype
Oracle


jndiReferenceName
jdbc/oracle




Your servlet container my require you to add a resource-ref section at the end of your geoserver/
WEB-INF/web.xml. (Tomcat requires this, Jetty does not.) For example:

Oracle Spatial Datasource
jdbc/oracle
javax.sql.DataSource
Container


Here is an example of a Tomcat 6 context in /etc/tomcat6/server.xml that includes an Oracle connection pool:




Firewall timeouts can silently sever idle connections to the database and cause GeoServer to hang. If there is
a firewall between GeoServer and the database, a connection pool configured to shut down idle connections
before the firewall can drop them will prevent GeoServer from hanging. This JNDI connection pool is

5.6. Application schemas

219

GeoServer User Manual, Release 2.15.1

configured to shut down idle connections after 5 to 10 minutes.
See also Setting up a JNDI connection pool with Tomcat.
Expose primary keys
By default, GeoServer conceals the existence of database columns with a primary key. To make such
columns available for use in app-schema mapping files, set the data store parameter Expose primary
keys to true:

Expose primary keys
true


This is known to work with PostGIS, Oracle, and JNDI data stores.
MongoDB
The data store configuration for a MongoDB data base will look like this:


data_source


data_store
MONGO_DB_URL


namespace
NAME_SPACE


schema_store
SCHEMA_STORE


data_store_type
complex





Check MongoDB Tutorial for a more detailed description about how to use MongoDB with app-schema.
Note: You must install the MongoDB plugin to connect to MongoDB databases.

220

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

5.6.12 Feature Chaining
Scope
This page describes the use of “Feature Chaining” to compose complex features from simpler components,
and in particular to address some requirements that have proven significant in practice.
• Handling multiple cases of multi-valued properties within a single Feature Type
• Handing nesting of multi-valued properties within other multi-valued properties
• Linking related (through association) Feature Types, and in particular allowing re-use of the related
features types (for example the O&M pattern has relatedObservation from a samplingFeature, but
Observation may be useful in its own right)
• Encoding the same referenced property object as links when it appears in multiple containing features
• Eliminating the need for large denormalized data store views of top level features and their related
features. Denormalized views would still be needed for special cases, such as many-to-many relationships, but won’t be as large.
For non-application schema configurations, please refer to Data Access Integration.
Mapping steps
Create a mapping file for every complex type
We need one mapping file per complex type that is going to be nested, including non features, e.g.
gsml:CompositionPart.
Non-feature types that cannot be individually accessed (eg. CompositionPart as a Data Type) can still be
mapped separately for its reusability. For this case, the containing feature type has to include these types in
its mapping file. The include tag should contain the nested mapping file path relative to the location of the
containing type mapping file. In GeologicUnit_MappingFile.xml:

CGITermValue_MappingFile.xml
CompositionPart_MappingFile.xml


Feature types that can be individually accessed don’t need to be explicitly included in the mapping file, as
they would be configured for GeoServer to find. Such types would have their mapping file associated with
a corresponding datastore.xml file, which means that it can be found from the data store registry. In other
words, if the type is associated with a datastore.xml file, it doesn’t need to be explicitly included if referred
from another mapping file.
Example:
For this output: MappedFeature_Output.xml, here are the mapping files:
• MappedFeature_MappingFile.xml
• GeologicUnit_MappingFile.xml
• CompositionPart_MappingFile.xml
• GeologicEvent_MappingFile.xml
• CGITermValue_MappingFile.xml

5.6. Application schemas

221

GeoServer User Manual, Release 2.15.1

GeologicUnit type
You can see within GeologicUnit features, both gml:composition (CompositionPart type) and
gsml:geologicHistory (GeologicEvent type) are multi-valued properties. It shows how multiple cases of
multi-valued properties can be configured within a single Feature Type. This also proves that you can
“chain” non-feature type, as CompositionPart is a Data Type.
GeologicEvent type
Both gsml:eventEnvironment (CGI_TermValue type) and gsml:eventProcess (also of CGI_TermValue type)
are multi-valued properties. This also shows that “chaining” can be done on many levels, as GeologicEvent
is nested inside GeologicUnit. Note that gsml:eventAge properties are configured as inline attributes, as
there can only be one event age per geologic event, thus eliminating the need for feature chaining.
Configure nesting on the nested feature type
In the nested feature type, make sure we have a field that can be referenced by the parent feature. If there
isn’t any existing field that can be referred to, the system field FEATURE_LINK can be mapped to hold the
foreign key value. This is a multi-valued field, so more than one instances can be mapped in the same
feature type, for features that can be nested by different parent types. Since this field doesn’t exist in the
schema, it wouldn’t appear in the output document.
In the source expression tag:
• OCQL: the value of this should correspond to the OCQL part of the parent feature
Example One: Using FEATURE_LINK in CGI TermValue type, which is referred by GeologicEvent as
gsml:eventProcess and gsml:eventEnvironment.
In GeologicEvent (the container feature) mapping:

gsml:eventEnvironment

id
gsml:CGI_TermValue
FEATURE_LINK[1]

true


gsml:eventProcess

id
gsml:CGI_TermValue
FEATURE_LINK[2]

true


In CGI_TermValue (the nested feature) mapping:


FEATURE_LINK[1]

ENVIRONMENT_OWNER



222

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1



FEATURE_LINK[2]
<
PROCESS_OWNER



The ENVIRONMENT_OWNER column in CGI_TermValue view corresponds to the ID column in GeologicEvent view.
Geologic Event property file:
id
ge.26931120
ge.26930473
ge.26930960
ge.26932959

GEOLOGIC_UNIT_ID:String
ghminage:String
ghmaxage:String
ghage_cdspace:String
gu.25699
Oligocene
Paleocene
urn:cgi:classifierScheme:ICS:StratChart:2008
gu.25678
Holocene
Pleistocene urn:cgi:classifierScheme:ICS:StratChart:2008
gu.25678
Pliocene
Miocene
urn:cgi:classifierScheme:ICS:StratChart:2008
gu.25678
LowerOrdovician
LowerOrdovician
urn:cgi:classifierScheme:ICS:StratChart:2008

CGI Term Value property file:
id
3
4
5
6
7
8
9
10
11

VALUE:String
fluvial
swamp/marsh/bog
marine
submarine fan
hemipelagic
detrital deposition still water
water [process]
channelled stream flow
turbidity current

PROCESS_OWNER:String
NULL
NULL
NULL
NULL
NULL
ge.26930473
ge.26932959
ge.26931120
ge.26932959

ENVIRONMENT_OWNER:String
ge.26931120
ge.26930473
ge.26930960
ge.26932959
ge.26932959
NULL
NULL
NULL
NULL

The system field FEATURE_LINK doesn’t get encoded in the output:

gu.25699





,→Oligocene





,→Paleocene







5.6. Application schemas

223

GeoServer User Manual, Release 2.15.1

fluvial




channelled stream flow



Example Two:
Using existing
MappedFeature_MappingFile.xml:

field

(gml:name)

to

hold

the

foreign

key,

see

gsml:specification links to gml:name in GeologicUnit:

gsml:specification

GEOLOGIC_UNIT_ID
gsml:GeologicUnit
gml:name[3]



In GeologicUnit_MappingFile.xml:
GeologicUnit has 3 gml:name properties in the mapping file, so each has a code space to clarify them:

gml:name[1]

ABBREVIATION


codeSpace
'urn:cgi:classifierScheme:GSV:GeologicalUnitCode'



gml:name[2]

NAME


codeSpace
'urn:cgi:classifierScheme:GSV:GeologicalUnitName'



gml:name[3]

id


codeSpace
'urn:cgi:classifierScheme:GSV:MappedFeatureReference'



The output with multiple gml:name properties and their code spaces:
224

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1



Olivine basalt, tuff, microgabbro, minor sedimentary rocks
-Py
Yaugher
,→Volcanic Group
gu.
,→25678

If this is the “one” side of a one-to-many or many-to-one database relationship, we can use the feature id as
the source expression field, as you can see in above examples. See one_to_many_relationship.JPG as
an illustration.
If we have a many-to-many relationship, we have to use one denormalized view for either side of the
nesting. This means we can either use the feature id as the referenced field, or assign a column to serve this
purpose. See many_to_many_relationship.JPG as an illustration.
Note:
• For many-to-many relationships, we can’t use the same denormalized view for both sides of the nesting.
Test this configuration by running a getFeature request for the nested feature type on its own.
Configure nesting on the “containing” feature type
When nesting another complex type, you need to specify in your source expression:
• OCQL: OGC’s Common Query Language expression of the data store column
• linkElement:
– the nested element name, which is normally the targetElement or mappingName of the corresponding type.
– on some cases, it has to be an OCQL function (see Polymorphism)
• linkField: the indexed XPath attribute on the nested element that OCQL corresponds to
Example: Nesting composition part in geologic unit feature.
In Geologic Unit mapping file:

gsml:composition

id
gsml:CompositionPart
FEATURE_LINK

true


• OCQL: id is the geologic unit id
• linkElement: links to gsml:CompositionPart type

5.6. Application schemas

225

GeoServer User Manual, Release 2.15.1

• linkField: FEATURE_LINK, the linking field mapped in gsml:CompositionPart type that also stores
the geologic unit id. If there are more than one of these attributes in the nested feature type, make
sure the index is included, e.g. FEATURE_LINK[2].
Geologic Unit property file:
id
gu.25699
gu.25678

ABBREVIATAION:String
NAME:String
TEXTDESCRIPTION:String
Yaugher Volcanic Olivine basalt, tuff, microgabbro, minor sedimentary rocks
Py Group
Yaugher Volcanic Olivine basalt, tuff, microgabbro, minor sedimentary rocks
Py Group

Composition Part property file:
id
cp.167775491936278812
cp.167775491936278856
cp.167775491936278844

COMPONENT_ROLE:String
interbedded component
interbedded component
sole component

PROPORTION:String
GEOLOGIC_UNIT_ID:String
significant
gu.25699
minor
gu.25678
major
gu.25678

Run the getFeature request to test this configuration. Check that the nested features returned in Step 2 are
appropriately lined inside the containing features. If they are not there, or exceptions are thrown, scroll
down and read the “Trouble Shooting” section.
Multiple mappings of the same type
At times, you may find the need to have different FeatureTypeMapping instances for the same
type. You may have two different attributes of the same type that need to be nested. For example, in gsml:GeologicUnit, you have gsml:exposureColor and gsml:outcropCharacter that are both of
gsml:CGI_TermValue type.
This is when the optional mappingName tag mentioned in Mapping File comes in. Instead of passing in
the nested feature type’s targetElement in the containing type’s linkElement, specify the corresponding
mappingName.
Note:
• The mappingName is namespace aware and case sensitive.
• When the referred mappingName contains special characters such as ‘-‘, it must be enclosed with
single quotes in the linkElement. E.g. ’observation-method’.
• Each mappingName must be unique against other mappingName and targetElement tags across the
application.
• The mappingName is only to be used to identify the chained type from the nesting type. It is not a
solution for multiple FeatureTypeMapping instances where > 1 of them can be queried as top level
features.
• When queried as a top level feature, the normal targetElement is to be used. Filters involving the
nested type should still use the targetElement in the PropertyName part of the query.
• You can’t have more than 1 FeatureTypeMapping of the same type in the same mapping file if one
of them is a top level feature. This is because featuretype.xml would look for the targetElement and
wouldn’t know which one to get.

226

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

The solution for the last point above is to break them up into separate files and locations with only 1
featuretype.xml in the intended top level feature location. E.g.
• You can have 2 FeatureTypeMapping instances in the same file for gsml:CGI_TermValue type since
it’s not a feature type.
• You can have 2 FeatureTypeMapping instances for gsml:MappedFeature, but they have to be broken
up into separate files. The one that can be queried as top level feature type would have featuretype.xml in its location.
Nesting simple properties
You don’t need to chain multi-valued simple properties and map them separately. The original configuration would still work.
Filtering nested attributes on chained features
Filters would work as usual. You can supply the full XPath of the attribute, and the code would handle
this. E.g. You can run the following filter on gsml:MappedFeatureUseCase2A:



gsml:specification/gsml:GeologicUnit/gml:description
Olivine basalt, tuff, microgabbro, minor sedimentary rocks
,→

1



Multi-valued properties by reference (xlink:href )
You may want to use feature chaining to set multi-valued properties by reference. This is particularly handy
to avoid endless loop in circular relationships. For example, you may have a circular relationship between
gsml:MappedFeature and gsml:GeologicUnit. E.g.
• gsml:MappedFeature has gsml:GeologicUnit as gsml:specification
• gsml:GeologicUnit has gsml:MappedFeature as gsml:occurrence
Obviously you can only encode one side of the relationship, or you’ll end up with an endless loop. You
would need to pick one side to “chain” and use xlink:href for the other side of the relationship.
For this example, we are nesting gsml:GeologicUnit in gsml:MappedFeature as gsml:specification.
• Set up nesting on the container feature type mapping as usual:

gsml:specification

GEOLOGIC_UNIT_ID
gsml:GeologicUnit
gml:name[2]

5.6. Application schemas

227

GeoServer User Manual, Release 2.15.1




• Set up xlink:href as client property on the other mapping file:

gsml:occurrence

id
gsml:MappedFeature
gsml:specification

true

xlink:href
strConcat('urn:cgi:feature:MappedFeature:', ID)



As we are getting the client property value from a nested feature, we have to set it as if we are chaining the
feature; but we also add the client property containing xlink:href in the attribute mapping. The code will
detect the xlink:href setting, and will not proceed to build the nested feature’s attributes, and we will end
up with empty attributes with xlink:href client properties.
This would be the encoded result for gsml:GeologicUnit:




Note:
• Don’t forget to add XLink in your mapping file namespaces section, or you could end up with a StackOverflowException as the xlink:href client property won’t be recognized and the mappings would
chain endlessly.
• Resolving may be used to force app-schema to do full feature chaining up to a certain level, even if an
xlink reference is specified.

5.6.13 Polymorphism
Polymorphism in this context refers to the ability of an attribute to have different forms. Depending on the
source value, it could be encoded with a specific structure, type, as an xlink:href reference, or not encoded
at all. To achieve this, we reuse feature chaining syntax and allow OCQL functions in the linkElement tag.
Read more about Feature Chaining, if you’re not familiar with the syntax.
Data-type polymorphism
You can use normal feature chaining to get an attribute to be encoded as a certain type. For example:

ex:someAttribute


228

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

VALUE_ID
NumericType
FEATURE_LINK



ex:someAttribute

VALUE_ID
gsml:CGI_TermValue
FEATURE_LINK



Note: NumericType here is a mappingName, whereas gsml:CGI_TermValue is a targetElement.
In the above example, ex:someAttribute would be encoded with the configuration in NumericType if the
foreign key matches the linkField. Both instances would be encoded if the foreign key matches the candidate keys in both linked configurations. Therefore this would only work for 0 to many relationships.
Functions can be used for single attribute instances. See useful functions for a list of commonly used functions. Specify the function in the linkElement, and it would map it to the first matching FeatureTypeMapping. For example:

ex:someAttribute

VALUE_ID

Recode(CLASS_TEXT, 'numeric', 'NumericType', 'literal', 'gsml:CGI_
,→TermValue')

FEATURE_LINK

true


The above example means, if the CLASS_TEXT value is ‘numeric’, it would link to ‘NumericType’ FeatureTypeMapping, with VALUE_ID as foreign key to the linked type. It would require all the potential
matching types to have a common attribute that is specified in linkField. In this example, the linkField is
FEATURE_LINK, which is a fake attribute used only for feature chaining. You can omit the linkField and
OCQL if the FeatureTypeMapping being linked to has the same sourceType with the container type. This
would save us from unnecessary extra queries, which would affect performance. For example:
FeatureTypeMapping of the container type:

PropertyFiles
PolymorphicFeature

FeatureTypeMapping of NumericType points to the same table:

NumericType
PropertyFiles
PolymorphicFeature

FeatureTypeMapping of gsml:CGI_TermValue also points to the same table:

5.6. Application schemas

229

GeoServer User Manual, Release 2.15.1


PropertyFiles
PolymorphicFeature
gsml:CGI_TermValue

In this case, we can omit linkField in the polymorphic attribute mapping:

ex:someAttribute


Recode(CLASS_TEXT, 'numeric', 'NumericType', 'literal', 'gsml:CGI_
,→TermValue')


true


Referential polymorphism
This is when an attribute is set to be encoded as an xlink:href reference on the top level. When the scenario
only has reference cases in it, setting a function in Client Property will do the job. E.g.:

ex:someAttribute

xlink:href
if_then_else(isNull(NUMERIC_VALUE), 'urn:ogc:def:nil:OGC:1.
,→0:missing', strConcat('#', NUMERIC_VALUE))



The above example means, if NUMERIC_VALUE is null, the attribute should be encoded as:


Otherwise, it would be encoded as:

where NUMERIC_VALUE = '123'

However, this is not possible when we have cases where a fully structured attribute is also a possibility.
The toxlinkhref function can be used for this scenario. E.g.:

ex:someAttribute


if_then_else(isNull(NUMERIC_VALUE), toXlinkHref('urn:ogc:def:nil:OGC:1.
,→0:missing'),
if_then_else(lessEqualThan(NUMERIC_VALUE, 1000), 'numeric_value',
,→toXlinkHref('urn:ogc:def:nil:OGC:1.0:missing')))




230

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

The above example means, if NUMERIC_VALUE is null, the output would be encoded as:


Otherwise, if NUMERIC_VALUE is less or equal than 1000, it would be encoded with attributes from
FeatureTypeMapping with ‘numeric_value’ mappingName. If NUMERIC_VALUE is greater than 1000,
it would be encoded as the first scenario.
Useful functions
if_then_else function
Syntax:
if_then_else(BOOLEAN_EXPRESSION, value, default value)

• BOOLEAN_EXPRESSION: could be a Boolean column value, or a Boolean function
• value: the value to map to, if BOOLEAN_EXPRESSION is true
• default value: the value to map to, if BOOLEAN_EXPRESSION is false
Recode function
Syntax:
Recode(EXPRESSION, key1, value1, key2, value2,...)

• EXPRESSION: column name to get values from, or another function
• key-n:
– key expression to map to value-n
– if the evaluated value of EXPRESSION doesn’t match any key, nothing would be encoded
for the attribute.
• value-n: value expression which translates to a mappingName or targetElement
lessEqualThan
Returns true if ATTRIBUTE_EXPRESSION evaluates to less or equal than LIMIT_EXPRESSION.
Syntax:
lessEqualThan(ATTRIBUTE_EXPRESSION, LIMIT_EXPRESSION)

• ATTRIBUTE_EXPRESSION: expression of the attribute being evaluated.
• LIMIT_EXPRESSION: expression of the numeric value to be compared against.

5.6. Application schemas

231

GeoServer User Manual, Release 2.15.1

lessThan
Returns true if ATTRIBUTE_EXPRESSION evaluates to less than LIMIT_EXPRESSION.
Syntax:
lessThan(ATTRIBUTE_EXPRESSION, LIMIT_EXPRESSION)

• ATTRIBUTE_EXPRESSION: expression of the attribute being evaluated.
• LIMIT_EXPRESSION: expression of the numeric value to be compared against.
equalTo
Compares two expressions and returns true if they’re equal.
Syntax:
equalTo(LHS_EXPRESSION, RHS_EXPRESSION)

isNull
Returns a Boolean that is true if the expression evaluates to null.
Syntax:
isNull(EXPRESSION)

• EXPRESSION: expression to be evaluated.
toXlinkHref
Special function written for referential polymorphism and feature chaining, not to be used outside of
linkElement. It infers that the attribute should be encoded as xlink:href.
Syntax:
toXlinkHref(XLINK_HREF_EXPRESSION)

• XLINK_HREF_EXPRESSION:
– could be a function or a literal
– has to be wrapped in single quotes if it’s a literal
Note:
• To get toXlinkHref function working, you need to declare xlink URI in the namespaces.

Other functions
Please refer to Filter Function Reference.

232

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Combinations
You can combine functions, but it might affect performance. E.g.:
if_then_else(isNull(NUMERIC_VALUE), toXlinkHref('urn:ogc:def:nil:OGC:1.0:missing'),
if_then_else(lessEqualThan(NUMERIC_VALUE, 1000), 'numeric_value', toXlinkHref(
,→'urn:ogc:def:nil:OGC:1.0:missing')))

Note:
• When specifying a mappingName or targetElement as a value in functions, make sure they’re enclosed in single quotes.
• Some functions have no null checking, and will fail when they encounter null.
• The workaround for this is to wrap the expression with isNull() function if null is known to exist in
the data set.

Null or missing value
To skip the attribute for a specific case, you can use Expression.NIL as a value in if_then_else or not include
the key in Recode function . E.g.:
if_then_else(isNull(VALUE), Expression.NIL, 'gsml:CGI_TermValue')
means the attribute would not be encoded if VALUE is null.
Recode(VALUE, 'term_value', 'gsml:CGI_TermValue')
means the attribute would not be encoded if VALUE is anything but 'term_value'.

To encode an attribute as xlink:href that represents missing value on the top level, see Referential Polymorphism.
Any type
Having xs:anyType as the attribute type itself infers that it is polymorphic, since they can be encoded as
any type.
If the type is pre-determined and would always be the same, we might need to specify targetAttributeNode
(optional). E.g.:

om:result
gml:MeasureType

TOPAGE


xsi:type
'gml:MeasureType'


uom
'http://www.opengis.net/def/uom/UCUM/0/Ma'



5.6. Application schemas

233

GeoServer User Manual, Release 2.15.1

If the casting type is complex, this is not a requirement as app-schema is able to automatically determine
the type from the XPath in targetAttribute. E.g., in this example om:result is automatically specialised as
a MappedFeatureType:

om:result/gsml:MappedFeature/gml:name

NAME



Alternatively, we can use feature chaining. For the same example above, the mapping would be:

om:result

LEX_D
gsml:MappedFeature
gml:name



If the type is conditional, the mapping style for such attributes is the same as any other polymorphic attributes. E.g.:

om:result


Recode(NAME, Expression.Nil, toXlinkHref('urn:ogc:def:nil:OGC::missing
,→'),'numeric',
toXlinkHref(strConcat('urn:numeric-value::', NUMERIC_VALUE)), 'literal
,→', 'TermValue2')




Filters
Filters should work as usual, as long as the users know what they want to filter. For example, when an
attribute could be encoded as gsml:CGI_TermValue or gsml:CGI_NumericValue, users can run filters with
property names of:
• ex:someAttribute/gsml:CGI_TermValue/gsml:value to return matching attributes that are encoded
as gsml:CGI_TermValue and satisfy the filter.
• likewise, ex:someAttribute/gsml:CGI_NumericValue/gsml:principalValue should return matching
gsml:CGI_NumericValue attributes.
Another limitation is filtering attributes of an xlink:href attribute pointing to an instance outside of the
document.

234

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

5.6.14 Data Access Integration
This page assumes prior knowledge of Application schemas and Feature Chaining. To use feature chaining,
the nested features can come from any complex feature data access, as long as:
• it has valid data referred by the “container” feature type,
• the data access is registered via DataAccessRegistry,
• if FEATURE_LINK is used as the link field, the feature types were created via ComplexFeatureTypeFactoryImpl
However, the “container” features must come from an application schema data access. The rest of this
article describes how we can create an application data access from an existing non-application schema
data access, in order to “chain” features. The input data access referred in this article is assumed to be the
non-application schema data access.
How to connect to the input data access
Configure the data store connection in “sourceDataStores” tag as usual, but also specify the additional “isDataAccess” tag. This flag marks that we want to get the registered complex feature source of the specified
“sourceType”, when processing the source data store. This assumes that the input data access is registered
in DataAccessRegistry upon creation, for the system to find it.
Example:


EarthResource


directory
file:./


true


...


EarthResource
EarthResource
...

How to configure the mapping
Use “inputAttribute” in place of “OCQL” tag inside “sourceExpression”, to specify the input XPath expressions.
Example:

gsml:classifier/gsml:ControlledConcept/gsml:preferredName

mo:classification/mo:MineralDepositModel/mo:mineralDepositGroup
,→

5.6. Application schemas

235

GeoServer User Manual, Release 2.15.1




How to chain features
Feature chaining works both ways for the re-mapped complex features. You can chain other features inside
these features, and vice-versa. The only difference is to use “inputAttribute” for the input XPath expressions, instead of “OCQL” as mentioned above.
Example:

gsml:occurence

mo:commodityDescription
gsml:MappedFeature
gml:name[2]

true


How to use filters
From the user point of view, filters are configured as per normal, using the mapped/output target attribute
XPath expressions. However, when one or more attributes in the expression is a multi-valued property,
we need to specify a function such as “contains_text” in the filter. This is because when multiple values
are returned, comparing them to a single value would only return true if there is only one value returned,
and it is the same value. Please note that the “contains_text” function used in the following example is not
available in GeoServer API, but defined in the database.
Example:
Composition is a multi-valued property:



gsml:composition/gsml:CompositionPart/gsml:proportion/
,→gsml:CGI_TermValue/gsml:value
Olivine basalt, tuff, microgabbro, minor sedimentary rocks

1



5.6.15 WMS Support
App-schema supports WMS requests as well as WFS requests. This page provides some useful examples
for configuring the WMS service to work with complex features.
Note that the rendering performance of WMS can be significantly slower when using app-schema data
stores. We strongly recommend employing Joining Support For Performance when using WMS with feature
chaining, which can make response time for large data requests several orders of magnitude faster.
236

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

Configuration
For WMS to be applicable to complex feature data, it is necessary that the complex feature types are
recognised by GeoServer as layers. This must be configured by adding an extra configuration file named
‘layer.xml’ in the data directory of each feature type that we want to use as a WMS layer.
This will expand the structure of the workspaces folder in the GeoServer data directory as follows
(workspaces) (see Configuration):
workspaces
- gsml
- SomeDataStore
- SomeFeatureType
- featuretype.xml
- layer.xml
- datastore.xml
- SomeFeatureType-mapping-file.xml

The file layer.xml must have the following contents:

[mylayerid]
[mylayername]
/
VECTOR

[mydefaultstyle]


[myfeaturetypeid]

true

0
0



Replace the fields in between brackets with the following values:
• [mylayerid] must be a custom id for the layer.
• [mylayername] must be a custom name for the layer.
• [mydefaultstyle] the default style used for this layer (when a style is not specified in the wms request).
The style must exist in the GeoServer configuration.
• [myfeaturetypeid] is the id of the feature type. This must the same as the id specified in the file
featuretype.xml of the same directory.
GetMap
Read GetMap for general information on the GetMap request. Read Styling for general information on how
to style WMS maps with SLD files. When styling complex features, you can use XPaths to specify nested
properties in your filters, as explained in Filtering nested attributes on chained features. However, in WMS
styling filters X-paths do not support handling referenced features (see Multi-valued properties by reference
(xlink:href)) as if they were actual nested features (because the filters are applied after building the features

5.6. Application schemas

237

GeoServer User Manual, Release 2.15.1

rather than before.) The prefix/namespace context that is used in the XPath expression is defined locally in
the XML tags of the style file. This is an example of a Style file for complex features:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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




geology-lithology

geology-lithology
Geological Unit Lithology Theme
The colour has been creatively adapted from Moyer,Hasting
and Raines, 2005 (http://pubs.usgs.gov/of/2005/1314/of2005-1314.pdf)
which provides xls spreadsheets for various color schemes.
plus some creative entries to fill missing entries.

1


acidic igneous material
Igneous material with more than 63 percent SiO2.
(after LeMaitre et al. 2002)



gsml:specification/gsml:GeologicUnit/gsml:composition/
gsml:CompositionPart/gsml:lithology/@xlink:href
urn:cgi:classifier:CGI:SimpleLithology:200811:
acidic_igneous_material




#FFCCB3




acidic igneous rock
Igneous rock with more than 63 percent SiO2.
(after LeMaitre et al. 2002)



gsml:specification/gsml:GeologicUnit/gsml:composition/
gsml:CompositionPart/gsml:lithology/@xlink:href
urn:cgi:classifier:CGI:SimpleLithology:200811:
acidic_igneous_rock




#FECDB2

238

Chapter 5. Data management

GeoServer User Manual, Release 2.15.1

57
58
59
60
61
62
63
64




...





GetFeatureInfo
Read GetFeatureInfo for general information on the GetFeatureInfo request. Read the tutorial on GetFeatureInfo Templates for information on how to template the html output. If you want to store a separate
standard template for complex feature collections, save it under the filename complex_content.ftl in
the template directory.
Read the tutorial on Freemarker Templates for more information on how to use the freemarker templates.
Freemarker templates support recursive calls, which can be useful for templating complex content. For
example, the following freemarker template creates a table of features with a column for each property, and
will create another table inside each cell that contains a feature as property:
<#-Macro's used for content
-->
<#macro property node>
<#if !node.isGeometry>
<#if node.isComplex>

<#else>

<#macro header typenode>

<#list typenode.attributes as attribute>
<#if !attribute.isGeometry>
<#if attribute.prefix == "">

<#else>

<#macro feature node type>
<@feature node=node.rawValue type=node.type /> ${node.value?string}
${typenode.name}
fid${attribute.name}${attribute.prefix}:${attribute.name}
<@header typenode=type /> 5.6. Application schemas 239 GeoServer User Manual, Release 2.15.1 <#list node.attributes as attribute> <@property node=attribute />
${node.fid}
<#-Body section of the GetFeatureInfo template, it's provided with one feature ,→collection, and will be called multiple times if there are various feature collections --> <@header typenode=type /> <#assign odd = false> <#list features as feature> <#if odd> <#else> <#assign odd = !odd> <#list feature.attributes as attribute> <@property node=attribute />
${feature.fid}

5.6.16 WFS 2.0 Support Resolving Local resolve is supported in app-schema. This can be done by setting the ‘resolve’ parameter to either ‘local’ or ‘all’. (Remote Resolving is not supported.) The parameter ‘resolveDepth’ specifies how many levels of references will be resolved. The parameter ‘resolveTimeOut’ may be used to specify, in seconds, an upper limit to how long app-schema should search for the feature needed for resolving. If the time out limit is reached, the feature is not resolved. When resolving without Feature Chaining (see below), a GML ID is extracted from the x-link reference and a brute force is done on all feature types to find a feature with this GML ID. The extraction of this GML ID from the Xlink Reference is done using the following rules: • In case of a URN: The GML ID comes after last colon in the URN. Make sure that the full GML ID is included after the last colon (including a possible feature type prefix). • In case of a URL: The GML ID comes after the # symbol. Failing to respect one of these rules will result in failure of resolve. 240 Chapter 5. Data management GeoServer User Manual, Release 2.15.1 Resolving and Feature Chaining By Reference The ‘resolve’ and ‘resolveDepth’ parameters may also be used in the case of Multi-valued properties by reference (xlink:href). In this case, no brute force will take place, but resolving will instruct App-Schema to do full feature chaining rather than inserting a reference. The URI will not be used to find the feature, but the feature chaining parameters specified in the mapping, as with normal feature chaining. Because of this, the parameter ‘resolveTimeOut’ will be ignored in this case. However, be aware that every feature can only appear once in a response. If resolving would break this rule, for example with circular references, the encoder will change the resolved feature back to an (internal) x-link reference. GetPropertyValue The GetPropertyValue request is now fully supported. Resolving is also possible in this request, following the same rules as described above. Paging Paging is now supported in App-Schema. There are a few exceptions: • Paging is only supported for data stores with JDBC back ends and will not work for data stores with property files. It has been tested with Oracle and PostGIS databases. • Paging with filters involving attributes that are mapped to functions will not be supported, as this cannot be translated into SQL. For more efficient SQL queries generation, please set isDenormalised to false where applicable (when a one to one database table is used). See Mapping File. 5.6.17 Joining Support For Performance App-schema joining is a optional configuration parameter that tells app-schema to use a different implementation for Feature Chaining, which in many cases can improve performance considerably, by reducing the amount of SQL queries sent to the DBMS. Conditions In order to use App-schema Joining, the following configuration conditions must be met: • All feature mappings used must be mapped to JDBC datastores. • All feature mappings that are chained to each other must map to the same physical database. • In your mappings, there are restrictions on the CQL expressions specified in the of both the referencing field in the parent feature as well as the referenced field in the nested feature (like FEATURE_LINK). Any operators or functions used in this expression must be supported by the filter capibilities, i.e. geotools must be able to translate them directly to SQL code. This can be different for each DBMS, though as a general rule it can assumed that comparison operators, logical operators and arithmetic operators are all supported but functions are not. Using simple field names for feature chaining is guaranteed to always work. Failing to comply with any of these three restrictions when turning on Joining will result in exceptions thrown at run-time. 5.6. Application schemas 241 GeoServer User Manual, Release 2.15.1 When using app-schema with Joining turned on, the following restrictions exist with respect to normal behaviour: • XPaths specified inside Filters do not support handling referenced features (see Multi-valued properties by reference (xlink:href)) as if they were actual nested features, i.e. XPaths can only be evaluated when they can be evaluated against the actual XML code produced by WFS according to the XPath standard. Configuration Joining is turned on by default. It is disabled by adding this simple line to your app-schema.properties file (see Property Interpolation) app-schema.joining = false Or, alternatively, by setting the value of the Java System Property “app-schema.joining” to “false”, for example java -DGEOSERVER_DATA_DIR=... -Dapp-schema.joining=false Start Not specifying “app-schema.joining” parameter will enable joining by default. Database Design Guidelines • Databases should be optimised for fast on-the-fly joining and ordering. • Make sure to put indexes on all fields used as identifiers and for feature chaining, unique indexes where possible. Lack of indices may result in data being encoded in the wrong order or corrupted output when feature chaining is involved. • Map your features preferably to normalised tables. • It is recommended to apply feature chaining to regular one-to-many relationships, i.e. there should be a unique constraint defined on one of the fields used for the chaining, and if possible a foreign key constraint defined on the other field. Effects on Performance Typical curves of response time for configurations with and without joining against the amount of features produced will be shaped like this: In the default implementation, response time increases rapidly with respect to the amount of produced features. This is because feature chaining is implemented by sending multiple SQL requests to the DBMS per feature, so the amount of requests increases with the amount of features produced. When Joining is turned on, response time will be almost constant with respect to the number of features. This is because 242 Chapter 5. Data management GeoServer User Manual, Release 2.15.1 in this implementation a small amount of larger queries is sent to the DBMS, independant of the amount of features produced. In summary, difference in performance becomes greater as the amount of features requested gets bigger. General performance of joining will be dependant on database and mapping design (see above) and database size. Using joining is strongly recommended when a large number of features need to be produced, for example when producing maps with WMS (see WMS Support). Optimising the performance of the database will maximise the benefit of using joining, including for small queries. Native Encoding of Filters on Nested Attributes When App-Schema Joining is active, filters operating on nested attributes (i.e. attributes of features that are joined to the queried type via Feature Chaining) are translated to SQL and executed directly in the database backend, rather than being evaluated in memory after all features have been loaded (which was standard behavior in earlier versions of GeoServer). Native encoding can yield significant performance improvements, especially when the total number of features in the database is high (several thousands or more), but only a few of them would satisfy the filter. There are, however, a few limitations in the current implementation: 1. Joining support must not have been explicitly disabled and all its pre-conditions must be met (see above) 2. Only binary comparison operators (e.g. PropertyIsEqualTo, PropertyIsGreaterThan, etc. . . ), PropertyIsLike and PropertyIsNull filters are translated to SQL 3. Filters involving conditional polymorphic mappings are evaluated in memory 4. Filters comparing two or more different nested attributes are evaluated in memory 5. Filters matching multiple nested attribute mappings are evaluated in memory Much like joining support, native encoding of nested filters is turned on by default, and it is disabled by adding to your app-schema.properties file the line app-schema.encodeNestedFilters = false Or, alternatively, by setting the value of the Java System Property “app-schema.encodeNestedFilters” to “false”, for example java -DGEOSERVER_DATA_DIR=... -Dapp-schema.encodeNestedFilters=false Start UNION performance improvement for OR conditions OR conditions are difficult to optimize for postgresql and are usually slow. App-Schema improves OR condition performance using UNION clauses instead OR for nested filter subqueries. With UNION improvement enabled main OR binary operator on nested filter subquery will rebuild normal OR query like: SELECT id, name FROM table WHERE name = "A" OR name = "B" to: SELECT id, name FROM table WHERE name = "A" UNION SELECT id, name FROM table WHERE ,→name = "B" 5.6. Application schemas 243 GeoServer User Manual, Release 2.15.1 UNION improvement is enabled by default, and it is disabled by adding to your app-schema.properties file the line app-schema.orUnionReplace = false Or, alternatively, by setting the value of the Java System Property “app-schema.orUnionReplace” to “false”, for example java -DGEOSERVER_DATA_DIR=... -Dapp-schema.orUnionReplace=false Start Note: This optimization will only be applied when a PostgresSQL database is being used. 5.6.18 Tutorial This tutorial demonstrates how to configure two complex feature types using the app-schema plugin and data from two property files. GeoSciML This example uses Geoscience Markup Language (GeoSciML) 2.0, a GML 3.1 application schema: “GeoSciML is an application schema that specifies a set of feature-types and supporting structures for information used in the solid-earth geosciences.” The tutorial defines two feature types: 1. gsml:GeologicUnit, which describes “a body of material in the Earth”. 2. gsml:MappedFeature, which describes the representation on a map of a feature, in this case gsml:GeologicUnit. Because a single gsml:GeologicUnit can be observed at several distinct locations on the Earth’s surface, it can have a multivalued gsml:occurrence property, each being a gsml:MappedFeature. Installation • Install GeoServer as usual. • Install the app-schema plugin geoserver-*-app-schema-plugin.zip: – Place the jar files in WEB-INF/lib. – The tutorial folder contains the GeoServer configuraration (data directory) used for this tutorial. * Either replace your existing data directory with the tutorial data directory, * Or edit WEB-INF/web.xml to set GEOSERVER_DATA_DIR to point to the tutorial data directory. (Be sure to uncomment the section that sets GEOSERVER_DATA_DIR.) • Perform any configuration required by your servlet container, and then start the servlet. For example, if you are using Tomcat, configure a new context in server.xml and then restart Tomcat. • The first time GeoServer starts with the tutorial configuration, it will download all the schema (XSD) files it needs and store them in the app-schema-cache folder in the data directory. You must be connected to the internet for this to work. 244 Chapter 5. Data management GeoServer User Manual, Release 2.15.1 datastore.xml Each data store configuration file datastore.xml specifies the location of a mapping file and triggers its loading as an app-schema data source. This file should not be confused with the source data store, which is specified inside the mapping file. For gsml_GeologicUnit the file is workspaces/gsml/gsml_GeologicUnit/datastore.xml: gsml_GeologicUnit_datastore gsml_GeologicUnit true gsml_workspace urn:cgi:xmlns:CGI:GeoSciML:2.0 file:workspaces/gsml/gsml_GeologicUnit/gsml_GeologicUnit.xml ,→ app-schema For gsml:MappedFeature the file is workspaces/gsml/gsml_MappedFeature/datastore.xml: gsml_MappedFeature_datastore gsml_MappedFeature true gsml_workspace urn:cgi:xmlns:CGI:GeoSciML:2.0 file:workspaces/gsml/gsml_MappedFeature/gsml_MappedFeature. ,→xml app-schema Note: Ensure that there is no whitespace inside an entry element. Mapping files Configuration of app-schema feature types is performed in mapping files: • workspaces/gsml/gsml_GeologicUnit/gsml_GeologicUnit.xml • workspaces/gsml/gsml_MappedFeature/gsml_MappedFeature.xml Namespaces Each mapping file contains namespace prefix definitions: 5.6. Application schemas 245 GeoServer User Manual, Release 2.15.1 gml http://www.opengis.net/gml gsml urn:cgi:xmlns:CGI:GeoSciML:2.0 xlink http://www.w3.org/1999/xlink Only those namespace prefixes used in the mapping file need to be declared, so the mapping file for gsml:GeologicUnit has less. Source data store The data for this tutorial is contained in two property files: • workspaces/gsml/gsml_GeologicUnit/gsml_GeologicUnit.properties • workspaces/gsml/gsml_MappedFeature/gsml_MappedFeature.properties Java Properties describes the format of property files. For this example, each feature type uses an identical source data store configuration. This directory parameter indicates that the source data is contained in property files named by their feature type, in the same directory as the corresponding mapping file: datastore directory file:./ See Data Stores for a description of how to use other types of data stores such as databases. Target types Both feature types are defined by the same XML Schema, the top-level schema for GeoSciML 2.0. This is specified in the targetTypes section. The type of the output feature is defined in targetElement in the typeMapping section below: http://www.geosciml.org/geosciml/2.0/xsd/geosciml.xsd 246 Chapter 5. Data management GeoServer User Manual, Release 2.15.1 In this case the schema is published, but because the OASIS XML Catalog is used for schema resolution, a private or modified schema in the catalog can be used if desired. Mappings The typeMappings element begins with configuration elements. gsml:GeologicUnit: From the mapping file for datastore gsml_GeologicUnit gsml:GeologicUnit • The mapping starts with sourceDataStore, which gives the arbitrary identifier used above to name the source of the input data in the sourceDataStores section. • sourceType gives the name of the source simple feature type. In this case it is the simple feature type gsml_GeologicUnit, sourced from the rows of the file gsml_GeologicUnit.properties in the same directory as the mapping file. • When working with databases sourceType is the name of a table or view. Database identifiers must be lowercase for PostGIS or uppercase for Oracle Spatial. • targetElement is the name of the output complex feature type. gml:id mapping The first mapping sets the gml:id to be the feature id specified in the source property file: gsml:GeologicUnit ID • targetAttribute is the XPath to the element for which the mapping applies, in this case, the toplevel feature type. • idExpression is a special form that can only be used to set the gml:id on a feature. Any field or CQL expression can be used, if it evaluates to an NCName. Ordinary mapping Most mappings consist of a target and source. Here is one from gsml:GeologicUnit: gml:description DESCRIPTION 5.6. Application schemas 247 GeoServer User Manual, Release 2.15.1 • In this case, the value of gml:description is just the value of the DESCRIPTION field in the property file. • For a database, the field name is the name of the column (the table/view is set in sourceType above). Database identifiers must be lowercase for PostGIS or uppercase for Oracle Spatial. • CQL expressions can be used to calculate content. Use caution because queries on CQL-calculated values prevent the construction of efficient SQL queries. • Source expressions can be CQL literals, which are single-quoted. Client properties In addition to the element content, a mapping can set one or more “client properties” (XML attributes). Here is one from gsml:MappedFeature: gsml:specification xlink:href GU_URN • This mapping leaves the content of the gsml:specification element empty but sets an xlink:href attribute to the value of the GU_URN field. • Multiple ClientProperty mappings can be set. In this example from the mapping for gsml:GeologicUnit both element content and an XML attribute are provided: gml:name[1] NAME codeSpace 'urn:x-test:classifierScheme:TestAuthority:GeologicUnitName' • The codespace XML attribute is set to a fixed value by providing a CQL literal. • There are multiple mappings for gml:name, and the index [1] means that this mapping targets the first. 248 Chapter 5. Data management GeoServer User Manual, Release 2.15.1 targetAttributeNode If the type of a property is abstract, a targetAttributeNode mapping must be used to specify a concrete type. This mapping must occur before the mapping for the content of the property. Here is an example from the mapping file for gsml:MappedFeature: gsml:positionalAccuracy gsml:CGI_TermValuePropertyType gsml:positionalAccuracy/gsml:CGI_TermValue/gsml:value 'urn:ogc:def:nil:OGC:missing' codeSpace 'urn:ietf:rfc:2141' • gsml:positionalAccuracy is of type gsml:CGI_TermValuePropertyType, which is abstract, so must be mapped to its concrete subtype gsml:CGI_TermValuePropertyType with a targetAttributeNode mapping before its contents can be mapped. • This example also demonstrates that mapping can be applied to nested properties to arbitrary depth. This becomes unmanageable for deep nesting, where feature chaining is preferred. Feature chaining In feature chaining, one feature type is used as a property of an enclosing feature type, by value or by reference: gsml:occurrence URN gsml:MappedFeature gml:name[2] true • In this case from the mapping for gsml:GeologicUnit, we specify a mapping for its gsml:occurrence. • The URN field of the source gsml_GeologicUnit simple feature is use as the “foreign key”, which maps to the second gml:name in each gsml:MappedFeature. • Every gsml:MappedFeature with gml:name[2] equal to the URN of the gsml:GeologicUnit under construction is included as a gsml:occurrence property of the gsml:GeologicUnit (by value). 5.6. Application schemas 249 GeoServer User Manual, Release 2.15.1 WFS response When GeoServer is running, test app-schema WFS in a web browser. localhost:8080 you can query the two feature types using these links: If GeoServer is listening on • http://localhost:8080/geoserver/wfs?request=GetFeature&version=1.1.0&typeName=gsml: GeologicUnit • http://localhost:8080/geoserver/wfs?request=GetFeature&version=1.1.0&typeName=gsml: MappedFeature gsml:GeologicUnit Feature chaining has been used to construct the multivalued property gsml:occurrence of gsml:GeologicUnit. This property is a gsml:MappedFeature. The WFS response for gsml:GeologicUnit combines the output of both feature types into a single response. The first gsml:GeologicUnit has two gsml:occurrence properties, while the second has one. The relationships between the feature instances are data driven. Because the mapping files in the tutorial configuration do not contain attribute mappings for all mandatory properties of these feature types, the WFS response is not schema-valid against the GeoSciML 2.0 schemas. Schema-validity can be achieved by adding more attribute mappings to the mapping files. Note: These feature types are defined in terms of GML 3.1 (the default for WFS 1.1.0); other GML versions will not work. Warning: The web interface does not yet support app-schema store or layer administration. Acknowledgements gsml_GeologicUnit.properties and gsml_MappedFeature.properties are derived from data provided by the Department of Primary Industries, Victoria, Australia. For the purposes of this tutorial, this data has been modified to the extent that it has no real-world meaning. 5.6.19 MongoDB Tutorial This tutorial demonstrates how to use app-schema plugin with a MongoDB data store. This tutorial will focus on the MongoDB data store specificities is highly recommended to read the app-schema documentation before. Use Case The use case for this tutorial will be to serve through app-schema the information about some meteorological stations stored in a MongoDB database. Note that this use case is completely fictional and only used to demonstrate the MongoDB and app-schema integration. First of all let’s insert some test data in a MongoDB data store: 250 Chapter 5. Data management GeoServer User Manual, Release 2.15.1 db.stations.insert({ "id": "1", "name": "station 1", "contact": { "mail": "station1@mail.com" }, "geometry": { "coordinates": [ 50, 60 ], "type": "Point" }, "measurements": [ { "name": "temp", "unit": "c", "values": [ { "time": 1482146800, "value": 20 } ] }, { "name": "wind", "unit": "km/h", "values": [ { "time": 1482146833, "value": 155 } ] } ] }) db.stations.insert({ "id": "2", "name": "station 2", "contact": { "mail": "station2@mail.com" }, "geometry": { "coordinates": [ 100, -50 ], "type": "Point" }, "measurements": [ { "name": "temp", "unit": "c", "values": [ { "time": 1482146911, "value": 35 5.6. Application schemas 251 GeoServer User Manual, Release 2.15.1 }, { "time": 1482146935, "value": 25 } ] }, { "name": "wind", "unit": "km/h", "values": [ { "time": 1482146964, "value": 80 } ] }, { "name": "pression", "unit": "pa", "values": [ { "time": 1482147026, "value": 1019 }, { "time": 1482147051, "value": 1015 } ] } ] }) db.stations.createIndex({ "geometry": "2dsphere" }) This is the schema that will be used to do the mappings in app-schema: 252 Chapter 5. Data management GeoServer User Manual, Release 2.15.1 ,→ Mappings MongoDB objects may contain nested elements and nested collections. The following three functions make possible to select nested elements and link nested collections using a JSON path: 5.6. Application schemas 253 GeoServer User Manual, Release 2.15.1 Function jsonSelect Example jsonSelect(‘contact.mail’) Description Used to retrieve the value for the mapping from a MongoDB object. collectionLink collectionLink(‘measurements.values’) Used when chaining entities with a nested collection. collectionId collectionId() Instructs the mapper to generate a ID for the nested collection. nestedCollectionLinknestedCollectionLink() Used on the nested collection to create a link with the parent feature. A station data is composed of some meta-information about the station and a list of measurements. Each measurement as some meta-information and contains a list of values. The mappings will contain three top entities: the station, the measurements and the values. Follows a the complete mappings file: st http://www.stations.org/1.0 gml http://www.opengis.net/gml data_source data_store mongodb://{mongoHost}:{mongoPort}/{dataBaseName} namespace http://www.stations.org/1.0 schema_store file:{schemaStore} data_store_type complex 254 Chapter 5. Data management GeoServer User Manual, Release 2.15.1 stations.xsd data_source {collectionName} st:StationFeature st:StationFeature jsonSelect('id') st:name jsonSelect('name') st:contact/st:mail jsonSelect('contact.mail') st:measurement collectionLink('measurements') aaa FEATURE_LINK[1] true st:geometry jsonSelect('geometry') data_source {collectionName} aaa st:Measurement st:Measurement collectionId() 5.6. Application schemas 255 GeoServer User Manual, Release 2.15.1 st:name jsonSelect('name') st:unit jsonSelect('unit') st:values collectionLink('values') st:Value FEATURE_LINK[2] true FEATURE_LINK[1] nestedCollectionLink() data_source {collectionName} st:Value st:Value collectionId() st:timestamp jsonSelect('time') st:value jsonSelect('value') FEATURE_LINK[2] nestedCollectionLink() 256 Chapter 5. Data management GeoServer User Manual, Release 2.15.1 The mappings for the attributes are straightforward, for example the following mapping: st:contact/st:mail jsonSelect('contact.mail') The mapping above defines that the contact mail for a station will be available at the JSON path contact. mail and that the correspondent XML schema element is the XPATH st:contact/st:mail. The feature chaining is a little bit more complex. Let’s take as an example the chaining between StationFeature and Measurement features. In the StationFeature feature type the link to the Measurement entity is defined with the following mapping: st:measurement collectionLink('measurements') st:Measurement FEATURE_LINK[1] true and in the Measurement feature type the link to the parent feature is defined with the following mapping: FEATURE_LINK[1] nestedCollectionLink() With the two mapping above we tie the two features types together. When working with a MongoDB data store this mappings will always be petty much the same, only the nested collection path and the feature link index need to be updated. Note that the JSON path of the nested collections attributes are relative to the parent. Querying To create an MongoDB app-schema layer in GeoServer, the app-schema extension and the mongo-complex extension needs to be installed. A workspace for each name space declared in the mappings file needs to be created, in this case the workspace st with URI http://www.stations.org/1.0 needs to be created. No need to create a gml workspace. Creating a MongoDB app-schema layer is similar to any other app-schema layer, just create an app-schema store pointing to the correct mappings file and select the layer correspondent to the top entity, in this case 5.6. Application schemas 257 GeoServer User Manual, Release 2.15.1 st:StationFeature. Is possible to query with WFS complex features encoded in GML and GeoJson using complex features filtering capabilities. For example, querying all the stations that have a measurement value with a time stamp superior to 1482146964: st:StationFeature/st:measurement/st:values/st:timestamp 1482146964 5.6.20 Apache Solr Tutorial This tutorial demonstrates how to use the App-Schema plugin with a Apache Solr data store. This tutorial will focus on the Apache Solr data store specific aspects, and the App-Schema documentation should be read first. The use case for this tutorial will be to serve through App-Schema the information about some meteorological stations index in an Apache Solr core. Note that this use case is completely fictional and only used to demonstrate the Apache Solr and App-Schema integration. A station data is composed of some meta-information about the station, e.g. it’s name and position. The only extra different configuration we need to provide when using Apache Solr as a data source is the configuration of the data store itself. Apache Solr data source configuration as a specific syntax and allow us to specify geometry attributes and to explicitly set the default geometry: stations http://localhost:8983/solr/stations location 4326 POINT In this particular case the the location attribute contains a point geometry and will be the default geometry. The complete mapping file is: 258 Chapter 5. Data management GeoServer User Manual, Release 2.15.1 st http://www.stations.org/1.0 gml http://www.opengis.net/gml/3.2 stations http://localhost:8983/solr/stations location 4326 POINT stations.xsd stations_solr stations stations st:Station st:Station station_id st:stationName station_name st:position station_location 5.6. Application schemas 259 GeoServer User Manual, Release 2.15.1 The mappings for the attributes are straightforward and follow the normal App-Schema attributes mappings syntax. Currently multi valued fields are not supported. 260 Chapter 5. Data management CHAPTER 6 Styling This section discusses the styling of geospatial data served through GeoServer. 6.1 Styles This section will detail how to work with the styles pages in the Web administration interface. For more information on styles and syntax, please see the main section on Styling. Styles are used to control the appearance of geospatial data. Styles for GeoServer are written in a number of different formats: • Styled Layer Descriptor (SLD): An OGC standard for geospatial styling. Available by default. • Cascading Style Sheets (CSS): A CSS-like syntax. Available via an extension. • YSLD: An SLD-equivalent based on YAML for improved authoring. Available via the ysld extension . • MBStyle: A syntax based on JSON for improved interoperability. Available via the mbstyle extension . 6.1.1 Styles page On the Styles page, you can add a new style, remove a style, or view or edit an existing style. Add a Style The buttons for adding and removing a style can be found at the top of the Styles page. To add a new style, click Add a new style button. You will be redirected to the new style page, which is the same as the Style Editor Data tab. The editor page provides several options for submitting a new style: • Type the style definition directly into the editor. 261 GeoServer User Manual, Release 2.15.1 Fig. 6.1: Styles page Fig. 6.2: Adding or removing a style Fig. 6.3: Generating a new default style. 262 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 • Generate a new default style based on an internal template: • Copy the contents of an existing style into the editor: Fig. 6.4: Copying an existing Style from GeoServer • Upload a local file that contains the style: Fig. 6.5: Uploading an file from the local system When creating a style, only the Data tab will be available. Click Apply on the new style to stay on the Style Editor page and gain access to all tabs. Remove a Style To remove a style, click the check box next to the style. Multiple styles can be selected at the same time. Click the Remove selected style(s) link at the top of the page. You will be asked for confirmation: Fig. 6.6: Confirmation prompt for removing styles Click OK to remove the selected style(s). 6.1.2 Style Editor On the Styles page, click a style name to open the Style Editor. 6.1. Styles 263 GeoServer User Manual, Release 2.15.1 The Style Editor page presents the style definition. The page contains four tabs with many configuration options: • Data: Includes basic style information, the ability to generate a style, and legend details • Publishing: Displays which layers are using this style • Layer Preview: Previews the style with an associated layer while editing • Layer Attributes: Displays a list of attributes for the associated layer Fig. 6.7: Style Editor tabs At the bottom of the Style Editor page is a number of options: Option Validate Apply Submit Cancel Description Will test the current style for correctness according to the Format option selected Makes the changes to the style and remain on the Style Editor page. This is useful to update the Layer Preview tab. Makes the changes to the style and returns to the Styles page Cancels all changes to the style and returns to the Styles page Fig. 6.8: Style Editor options Style definition On all tabs, the Style Editor will display the style definition at the bottom, allowing for direct editing of the style. Switch between the tabs in order to facilitate style creation and editing. The style editor supports line numbering, automatic indentation, and real-time syntax highlighting. You can also increase or decrease the font size of the editor. Button Description Undo Redo Go to line Auto-format the editor contents Change the font size in the editor Insert image into style (choose existing or upload) Change height of style editor (disabled in full screen mode) During editing and especially after editing is complete, you will want to check validation of the syntax. This can be done by clicking the Validate button at the bottom. 264 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.9: Style editor If no errors are found, you will see this message: Fig. 6.10: No validation errors If any validation errors are found, they will be displayed: Fig. 6.11: Validation error message Style Editor: Data tab The Data tab includes basic style information, the ability to generate a style, and legend details. The Style Data area has mandatory basic style information: Option Name Workspace Format Description Name of the style Workspace in which the style is contained. Styles can be inside workspaces, but can also be “global” (no workspace). Format of the style. Options are SLD, CSS, and YSLD, MBStyle depending on availability. The Style Content area allows you to generate a style, copy an existing style, or upload an existing style: 6.1. Styles 265 GeoServer User Manual, Release 2.15.1 Fig. 6.12: Style Data area Option Generate a default style Copy from existing style Upload a style file Description Selects a generic style based on geometry. Options are Point, Line, Polygon, Raster, and Generic. Click Generate when selected. Selects an existing style in GeoServer and copy its contents to this style. Any style in GeoServer is available as an option. Not all styles will work with all layers. Click Copy when selected. Selects a plain text file on your local system to add as the style. Click Upload when selected. Fig. 6.13: Style Content area The Legend area allows you to add, modify, or delete a custom style, and preview the legend for the style. By default GeoServer will generate a legend based on your style file, but this can be customized here: Option Add legend Online Resource Auto-detect image size and type Width Height Format Discard legend Preview legend Description Allows you to use a custom legend Path to the custom legend graphic to use. Can be a URL or a local path (relative to the style file path). See Structure of the data directory for a description of the styles directory. Populates the Width, Height, and Format options for the Online Resource Width of the custom legend graphic Height of the custom legend graphic Mime type of the custom legend graphic Will remove the settings for the custom legend graphic and will instead use the default generated legend. Previews the legend based on the current settings Style Editor: Publishing tab The Publishing tab displays a list of all layers on the server, with the purpose of showing which layers are associated with the current style. Layers can set a single default style and have any number of additional 266 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.14: Legend area styles. If this style is set to be either of these options for a layer, it will be shown with a check box in the table. Option Workspace Layer Default Associated Description Workspace of the layer Name of the layer Shows whether the style being edited is the default for a given layer Shows whether the style being edited is an additional style for a given layer Fig. 6.15: Publishing tab Style Editor: Layer Preview tab It is very common to have to iterate your styles and test how the visualization changes over time. The Layer Preview tab allows you to make changes to the style and see them without having to navigate away from the page. The Layer Preview tab shows a single image. GeoServer tries to identify which layer should be shown (for example, a layer for which this style is the default), but if the layer being previewed is not the desired one, click the layer name above the preview box and select a layer. Style Editor: Layer Attributes tab Most styles utilize the specific values of certain attributes of the associated layer in order to create more detailed and useful styles. (For example: styling all large cities different from small cities based on a particular attribute.) The Layer Attributes tab will display a list of attributes for the given associated layer. GeoServer tries to identify which layer should be shown (for example, a layer for which this style is the default), but if the layer being previewed is not the desired one, click the layer name above the table and select a layer. 6.1. Styles 267 GeoServer User Manual, Release 2.15.1 Fig. 6.16: Layer Preview tab Option name type sample min max computeStats Description Name of the attribute Type of the attribute. Can be a numeric (such as “Long”), a string (“String”), or a geometry (such as “Point”). Sample value of the attribute taken from the data Minimum value of the attribute in the data set, if applicable Minimum value of the attribute in the data set, if applicable Click Compute to calculate the min and max values for that attribute, if applicable Fig. 6.17: Layer Attributes tab Style Editor: full screen side by side mode The style editor page has now a “outwards arrows” button on the top right side of the window: Pressing it will cause the editor and preview to go side by side and use the entire browser window space: The button turns into a “inwards arrows” icon, pressing it resumes the original editing mode. 6.2 SLD Styling This section discusses styling of geospatial data using “Style Layer Descriptor” XML files. 268 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.18: The new fullscreen functionality Fig. 6.19: Side by side style editing 6.2. SLD Styling 269 GeoServer User Manual, Release 2.15.1 6.2.1 Introduction to SLD Geospatial data has no intrinsic visual component. In order to see data, it must be styled. Styling specifies color, thickness, and other visible attributes used to render data on a map. In GeoServer, styling is accomplished using a markup language called Styled Layer Descriptor, or SLD for short. SLD is an XML-based markup language and is very powerful, although somewhat complex. This page gives an introduction to the capabilities of SLD and how it works within GeoServer. Note: Since GeoServer uses SLD exclusively for styling, the terms “SLD” and “style” will often be used interchangeably. SLD Concepts In GeoServer styling is most often specified using XML SLD style documents. Style documents are associated with GeoServer layers (featuretypes) to specify how they should be rendered. A style document specifies a single named layer and a user style for it. The layer and style can have metadata elements such as a name identifying them, a title for displaying them, and an abstract describing them in detail. Within the top-level style are one or more feature type styles, which act as “virtual layers” to provide control over rendering order (allowing styling effects such as cased lines for roads). Each feature type style contains one or more rules, which control how styling is applied based on feature attributes and zoom level. Rules select applicable features by using filters, which are logical conditions containing predicates, expressions and filter functions. To specify the details of styling for individual features, rules contain any number of symbolizers. Symbolizers specify styling for points, lines and polygons, as well as rasters and text labels. For more information refer to the SLD Reference. Types of styling Vector data that GeoServer can serve consists of three classes of shapes: Points, lines, and polygons. Lines (one dimensional shapes) are the simplest, as they have only the edge to style (also known as “stroke”). Polygons, two dimensional shapes, have an edge and an inside (also known as a “fill”), both of which can be styled differently. Points, even though they lack dimension, have both an edge and a fill (not to mention a size) that can be styled. For fills, color can be specified; for strokes, color and thickness can be specified. GeoServer also serves raster data. This can be styled with a wide variety of control over color palette, opacity, contrast and other parameters. More advanced styling is possible as well. Points can be specified with well-known shapes like circles, squares, stars, and even custom graphics or text. Lines can be styled with a dash styles and hashes. Polygons can be filled with a custom tiled graphics. Styling can be based on attributes in the data, so that certain features are styled differently. Text labels on features are possible as well. Styling can also be determined by zoom level, so that features are displayed in a way appropriate to their apparent size. The possibilities are vast. A basic style example A good way to learn about SLD is to study styling examples. The following is a simple SLD that can be applied to a layer that contains points, to style them as red circles with a size of 6 pixels. (This is the first example in the Points section of the SLD Cookbook.) 270 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 Simple point GeoServer SLD Cook Book: Simple point circle #FF0000 6 Although the example looks long, only a few lines are really important to understand. Line 14 states that a “PointSymbolizer” is to be used to style data as points. Lines 15-17 state that points are to be styled using a graphic shape specified by a “well known name”, in this case a circle. SLD provides names for many shapes such as “square”, “star”, “triangle”, etc. Lines 18-20 specify the shape should be filled with a color of #FF0000 (red). This is an RGB color code, written in hexadecimal, in the form of #RRGGBB. Finally, line 22 specifies that the size of the shape is 6 pixels in width. The rest of the structure contains metadata about the style, such as a name identifying the style and a title for use in legends. Note: In SLD documents some tags have prefixes, such as ogc:. This is because they are defined in XML namespaces. The top-level StyledLayerDescriptor tag (lines 2-7) specifies two XML namespaces, one called xmlns, and one called xmlns:ogc. The first namespace is the default for the document, so tags belonging to it do not need a prefix. Tags belonging to the second require the prefix ogc:. In fact, the namespace prefixes can be any identifier. The first namespace could be called xmlns:sld (as it often is) and then all the tags in this example would require an sld: prefix. The key point is that tags need to have the prefix for the namespace they belong to. See the SLD Cookbook for more examples of styling with SLD. 6.2.2 Working with SLD This section describes how to create, view and troubleshoot SLD styling in GeoServer. 6.2. SLD Styling 271 GeoServer User Manual, Release 2.15.1 Creating GeoServer comes with some basic styles defined in its catalog. Any number of new styles can be added to the catalog. Styles can also be specified externally to the server, either to define a complete map, or to extend the server style catalog using library mode. Catalog Styles Styles in the catalog can be viewed, edited and validated via the Styles page menu of the Web administration interface. They may also be created and accessed via the REST Styles API. There are two types of Catalog Styles: Symbology Encoding styles (the default) and Style Layer Descriptor styles. Symbology Encoding Styles A Symbology Encoding style consists of a Symbology Encoding document used to specify the styling of a single layer. In GeoServer, this is more commonly referred to as a style. GeoServer supports the use of a StyledLayerDescriptor document containing a single element, which contains a single element to specify the styling. • When used in this fashion the layer name is ignored, since the style may be applied to many different layers. • When using an an StyledLayerDescriptor generated by another application keep in mind only the first is used, any subsequent content is ignored. Every layer (featuretype) registered with GeoServer must have at least one symbology encoding style associated with it, which is the default style for rendering the layer. Any number of additional styles can be associated with a layer. This allows layers to have appropriate styles advertised in the WMS GetCapabilities document. A layer’s styles can be changed using the Layers page of the Web administration interface. Note: When adding a layer and a style for it to GeoServer at the same time, the style should be added first, so that the new layer can be associated with the style immediately. Style Layer Descriptor Styles A Style Layer Descriptor is a StyledLayerDescriptor document containing any number of and elements, each of which may contain any number of or elements. Within a Style Layer Descriptor document, the name of any elements should match a layer (or layer group) in the catalog. Likewise, any elements should refer to a style in the catalog. Style Layer Descriptor styles can define new layers of styled data, by using the InlineFeature element to provide feature data. Within GeoServer, when Style Layer Descriptor styles are used they are typically in the form of style groups. Style groups can be added to layer groups as an alternative way of defining a collection of styled layers, using either the Web Administration interface or the REST API. 272 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Style Layer Descriptor styles can still be assigned to layers and used like a layer style, in which case only the first will be used. Style Layer Descriptor styles can also be used as an External Style, via the geoserver styles endpoint (/geoserver/styles) or the geoserver REST api. External Styles Styling can be defined externally to the server in a number of ways: • An internet-accessible SLD document can be provided via the SLD=url parameter in a WMS GetMap GET request • An SLD document can be provided directly in a WMS GetMap GET request using the SLD_BODY=style parameter. The SLD XML must be URL-encoded. • A StyledLayerDescriptor element can be included in a WMS GetMap POST request XML document. In all of these cases, if the WMS layers parameter is not supplied then the map content is defined completely by the layers and styles present in the external SLD. If the layers parameter is present, then styling operates in Library Mode. The structure of an external style is the same as a Style Layer Descriptor style, as described above. External styles can define new layers of styled data, by using the SLD InlineFeature element to provide feature data. This can be used to implement dynamic feature highlighting, for example. External styling may be generated dynamically by client applications, This provides a powerful way for clients to control styling effects. Library Mode In library mode externally-defined styles are treated as a style library, which acts as an extension to the server style catalog. Library mode occurs when map layers and styles are specified using the layers and styles WMS parameters, and additional styling is supplied externally using one of the methods described in the previous section. The styles in the external style document take precedence over the catalog styles during rendering. Style lookup in library mode operates as follows: • For each layer in the layers list, the applied style is either a named style specified in the styles list (if present), or the layer default style • For a named style, if the external style document has a ... with matching layer name and style name, then it is used. Otherwise, the style name is searched for in the catalog. If it is not found there, an error occurs. • For a default style, the external style document is searched to find a element with the layer name. If it contains a with the element having the value 1 then that style is used. Otherwise, the default server style for the layer (which must exist) is used. Generally it is simpler and more performant to use styles from the server catalog. However, library mode can be useful if it is required to style a map containing many layers and where only a few of them need to have their styling defined externally. Viewing Once a style has been associated with a layer, the resulting rendering of the layer data can be viewed by using the Layer Preview. The most convenient output format to use is the built-in OpenLayers viewer. 6.2. SLD Styling 273 GeoServer User Manual, Release 2.15.1 Styles can be modified while the view is open, and their effect is visible as soon as the map view is panned or zoomed. Alternate styles can be viewed by specifying them in the styles WMS request parameter. To view the effect of compositing multiple styled layers, several approaches are available: • Create a layer group for the desired layers using the Layer Groups page, and preview it. Non-default styles can be specified for layers if required. • Submit a WMS GetMap GET request specifying multiple layers in the layers parameter, and the corresponding styles in the styles parameter (if non-default styles are required). • Submit a WMS GetMap POST request containing a StyledLayerDescriptor element specifying server layers, optional layers of inline data, and either named catalog styles or user-defined styling for each layer. Troubleshooting SLD is a type of programming language, not unlike creating a web page or building a script. As such, problems may arise that may require troubleshooting. Syntax Errors To minimize syntax errors when creating the SLD, it is recommended to use a text editor that is designed to work with XML (such as the Style Editor provided in the GeoServer UI). XML editors can make finding syntax errors easier by providing syntax highlighting and (sometimes) built-in error checking. The GeoServer Style Editor allows validating a document against the SLD XML schema. This is not mandatory, but is recommended to do before saving styles. Semantic Errors Semantic errors cannot be caught by SLD validation, but show up when a style is applied during map rendering. Most of the time this will result in a map displaying no features (a blank map), but some errors will prevent the map from rendering at all. The easiest way to fix semantic errors in an SLD is to try to isolate the error. If the SLD is long with many rules and filters, try temporarily removing some of them to see if the errors go away. In some cases the server will produce a WMS Exception document which may help to identify the error. It is also worth checking the server log to see if any error messages have been recorded. 6.2.3 SLD Cookbook The SLD Cookbook is a collection of SLD “recipes” for creating various types of map styles. Wherever possible, each example is designed to show off a single SLD feature so that code can be copied from the examples and adapted when creating SLDs of your own. While not an exhaustive reference like the SLD Reference or the OGC SLD 1.0 specification the SLD Cookbook is designed to be a practical reference, showing common style templates that are easy to understand. The SLD Cookbook is divided into four sections: the first three for each of the vector types (points, lines, and polygons) and the fourth section for rasters. Each example in every section contains a screenshot showing actual GeoServer WMS output, a snippet of the SLD code for reference, and a link to download the full SLD. 274 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Each section uses data created especially for the SLD Cookbook, with shapefiles for vector data and GeoTIFFs for raster data. The projection for data is EPSG:4326. All files can be easily loaded into GeoServer in order to recreate the examples. Data Type Point Line Polygon Raster Shapefile sld_cookbook_point.zip sld_cookbook_line.zip sld_cookbook_polygon.zip sld_cookbook_raster.zip Points While points are seemingly the simplest type of shape, possessing only position and no other dimensions, there are many different ways that a point can be styled in SLD. Warning: The code examples shown on this page are not the full SLD code, as they omit the SLD header and footer information for the sake of brevity. Please use the links to download the full SLD for each example. Example points layer The points layer used for the examples below contains name and population information for the major cities of a fictional country. For reference, the attribute table for the points in this layer is included below. fid (Feature ID) point.1 point.2 point.3 point.4 point.5 point.6 point.7 name (City name) Borfin Supox City Ruckis Thisland Synopolis San Glissando Detrania pop (Population) 157860 578231 98159 34879 24567 76024 205609 Download the points shapefile Simple point This example specifies points be styled as red circles with a diameter of 6 pixels. Code View and download the full "Simple point" SLD 1 2 3 4 5 6.2. SLD Styling 275 GeoServer User Manual, Release 2.15.1 Fig. 6.20: Simple point 6 7 8 9 10 11 12 13 14 15 circle #FF0000 6 Details There is one in one for this SLD, which is the simplest possible situation. (All subsequent examples will contain one and one unless otherwise specified.) Styling points is accomplished via the (lines 3-13). Line 6 specifies the shape of the symbol to be a circle, with line 8 determining the fill color to be red (#FF0000). Line 11 sets the size (diameter) of the graphic to be 6 pixels. Simple point with stroke This example adds a stroke (or border) around the Simple point, with the stroke colored black and given a thickness of 2 pixels. Code View and download the full "Simple point with stroke" SLD 1 2 3 4 5 6 7 circle 276 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.21: Simple point with stroke 8 9 10 11 12 13 14 15 16 17 18 19 #FF0000 #000000 2 6 Details This example is similar to the Simple point example. Lines 10-13 specify the stroke, with line 11 setting the color to black (#000000) and line 12 setting the width to 2 pixels. Rotated square This example creates a square instead of a circle, colors it green, sizes it to 12 pixels, and rotates it by 45 degrees. Code View and download the full "Rotated square" SLD 1 2 3 4 5 6 7 8 square #009900 6.2. SLD Styling 277 GeoServer User Manual, Release 2.15.1 Fig. 6.22: Rotated square 9 10 11 12 13 14 15 16 12 45 Details In this example, line 6 sets the shape to be a square, with line 8 setting the color to a dark green (#009900). Line 11 sets the size of the square to be 12 pixels, and line 12 set the rotation is to 45 degrees. Transparent triangle This example draws a triangle, creates a black stroke identical to the Simple point with stroke example, and sets the fill of the triangle to 20% opacity (mostly transparent). Fig. 6.23: Transparent triangle 278 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Code View and download the full "Transparent triangle" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 triangle #009900 0.2 #000000 2 12 Details In this example, line 6 once again sets the shape, in this case to a triangle. Line 8 sets the fill color to a dark green (#009900) and line 9 sets the opacity to 0.2 (20% opaque). An opacity value of 1 means that the shape is drawn 100% opaque, while an opacity value of 0 means that the shape is drawn 0% opaque, or completely transparent. The value of 0.2 (20% opaque) means that the fill of the points partially takes on the color and style of whatever is drawn beneath it. In this example, since the background is white, the dark green looks lighter. Were the points imposed on a dark background, the resulting color would be darker. Lines 12-13 set the stroke color to black (#000000) and width to 2 pixels. Finally, line 16 sets the size of the point to be 12 pixels in diameter. Point as graphic This example styles each point as a graphic instead of as a simple shape. Code View and download the full "Point as graphic" SLD 1 2 3 4 5 6 7 8 9 image/png 6.2. SLD Styling 279 GeoServer User Manual, Release 2.15.1 Fig. 6.24: Point as graphic 10 11 12 13 14 15 32 Details This style uses a graphic instead of a simple shape to render the points. In SLD, this is known as an , to distinguish it from the commonly-used shapes such as squares and circles that are “internal” to the renderer. Lines 5-10 specify the details of this graphic. Line 8 sets the path and file name of the graphic, while line 9 indicates the format (MIME type) of the graphic (image/png). In this example, the graphic is contained in the same directory as the SLD, so no path information is necessary in line 8, although a full URL could be used if desired. Line 11 determines the size of the displayed graphic; this can be set independently of the dimensions of the graphic itself, although in this case they are the same (32 pixels). Should a graphic be rectangular, the value will apply to the height of the graphic only, with the width scaled proportionally. Fig. 6.25: Graphic used for points Point with default label This example shows a text label on the Simple point that displays the “name” attribute of the point. This is how a label will be displayed in the absence of any other customization. Code View and download the full "Point with default label" SLD 280 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.26: Point with default label 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 circle #FF0000 6 #000000 Details Lines 3-13, which contain the , are identical to the Simple point example above. The label is set in the on lines 14-27. Lines 15-17 determine what text to display in the label, which in this case is the value of the “name” attribute. (Refer to the attribute table in the Example points layer section if necessary.) Line 19 sets the text color. All other details about the label are set to the renderer default, which here is Times New Roman font, font color black, and font size of 10 pixels. The bottom left of the label is aligned with the center of the point. Point with styled label This example improves the label style from the Point with default label example by centering the label above the point and providing a different font name and size. 6.2. SLD Styling 281 GeoServer User Manual, Release 2.15.1 Fig. 6.27: Point with styled label Code View and download the full "Point with styled label" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 circle #FF0000 6 Arial 12 normal bold 0.5 0.0 0 5 282 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 37 38 39 40 41 #000000 Details In this example, lines 3-13 are identical to the Simple point example above. The on lines 14-39 contains many more details about the label styling than the previous example, Point with default label. Lines 15-17 once again specify the “name” attribute as text to display. Lines 18-23 set the font information: line 19 sets the font family to be “Arial”, line 20 sets the font size to 12, line 21 sets the font style to “normal” (as opposed to “italic” or “oblique”), and line 22 sets the font weight to “bold” (as opposed to “normal”). Lines 24-35 () determine the placement of the label relative to the point. The (lines 26-29) sets the point of intersection between the label and point, which here (line 27-28) sets the point to be centered (0.5) horizontally axis and bottom aligned (0.0) vertically with the label. There is also (lines 30-33), which sets the offset of the label relative to the line, which in this case is 0 pixels horizontally (line 31) and 5 pixels vertically (line 32). Finally, line 37 sets the font color of the label to black (#000000). The result is a centered bold label placed slightly above each point. Point with rotated label This example builds on the previous example, Point with styled label, by rotating the label by 45 degrees, positioning the labels farther away from the points, and changing the color of the label to purple. Fig. 6.28: Point with rotated label Code View and download the full "Point with rotated label" SLD 1 2 3 4 6.2. SLD Styling 283 GeoServer User Manual, Release 2.15.1 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 circle #FF0000 6 Arial 12 normal bold 0.5 0.0 0 25 -45 #990099 Details This example is similar to the Point with styled label, but there are three important differences. Line 32 specifies 25 pixels of vertical displacement. Line 34 specifies a rotation of “-45” or 45 degrees counterclockwise. (Rotation values increase clockwise, which is why the value is negative.) Finally, line 38 sets the font color to be a shade of purple (#99099). Note that the displacement takes effect before the rotation during rendering, so in this example, the 25 pixel vertical displacement is itself rotated 45 degrees. Attribute-based point This example alters the size of the symbol based on the value of the population (“pop”) attribute. 284 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.29: Attribute-based point Code View and download the full "Attribute-based point" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 SmallPop 1 to 50000 pop 50000 circle #0033CC 8 MediumPop 50000 to 100000 pop 50000 pop 100000 6.2. SLD Styling 285 GeoServer User Manual, Release 2.15.1 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 67 68 69 70 71 circle #0033CC 12 LargePop Greater than 100000 pop 100000 circle #0033CC 16 Details Note: Refer to the Example points layer to see the attributes for this data. This example has eschewed labels in order to simplify the style, but you can refer to the example Point with styled label to see which attributes correspond to which points. This style contains three rules. Each varies the style based on the value of the population (“pop”) attribute for each point, with smaller values yielding a smaller circle, and larger values yielding a larger circle. The three rules are designed as follows: Rule order 1 2 3 286 Rule name SmallPop MediumPop LargePop Population (“pop”) Less than 50,000 50,000 to 100,000 Greater than 100,000 Size 8 12 16 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 The order of the rules does not matter in this case, since each shape is only rendered by a single rule. The first rule, on lines 2-22, specifies the styling of those points whose population attribute is less than 50,000. Lines 5-10 set this filter, with lines 6-9 setting the “less than” filter, line 7 denoting the attribute (“pop”), and line 8 the value of 50,000. The symbol is a circle (line 14), the color is dark blue (#0033CC, on line 16), and the size is 8 pixels in diameter (line 19). The second rule, on lines 23-49, specifies a style for points whose population attribute is greater than or equal to 50,000 and less than 100,000. The population filter is set on lines 26-37. This filter is longer than in the first rule because two criteria need to be specified instead of one: a “greater than or equal to” and a “less than” filter. Notice the And on line 27 and line 36. This mandates that both filters need to be true for the rule to be applicable. The size of the graphic is set to 12 pixels on line 46. All other styling directives are identical to the first rule. The third rule, on lines 50-70, specifies a style for points whose population attribute is greater than or equal to 100,000. The population filter is set on lines 53-58, and the only other difference is the size of the circle, which in this rule (line 67) is 16 pixels. The result of this style is that cities with larger populations have larger points. Zoom-based point This example alters the style of the points at different zoom levels. Fig. 6.30: Zoom-based point: Zoomed in Code View and download the full "Zoom-based point" SLD 6.2. SLD Styling 287 GeoServer User Manual, Release 2.15.1 Fig. 6.31: Zoom-based point: Partially zoomed Fig. 6.32: Zoom-based point: Zoomed out 288 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 Large 160000000 circle #CC3300 12 Medium 160000000 320000000 circle #CC3300 8 Small 320000000 circle #CC3300 4 Details It is often desirable to make shapes larger at higher zoom levels when creating a natural-looking map. This example styles the points to vary in size based on the zoom level (or more accurately, scale denominator). Scale denominators refer to the scale of the map. A scale denominator of 10,000 means the map has a scale of 1:10,000 in the units of the map projection. 6.2. SLD Styling 289 GeoServer User Manual, Release 2.15.1 Note: Determining the appropriate scale denominators (zoom levels) to use is beyond the scope of this example. This style contains three rules. The three rules are designed as follows: Rule order 1 2 Rule name Large Medium 3 Small Scale denominator 1:160,000,000 or less 1:160,000,000 to 1:320,000,000 Greater than 1:320,000,000 Point size 12 8 4 The order of these rules does not matter since the scales denominated in each rule do not overlap. The first rule (lines 2-16) is for the smallest scale denominator, corresponding to when the view is “zoomed in”. The scale rule is set on line 4, so that the rule will apply to any map with a scale denominator of 160,000,000 or less. The rule draws a circle (line 8), colored red (#CC3300 on line 10) with a size of 12 pixels (line 13). The second rule (lines 17-32) is the intermediate scale denominator, corresponding to when the view is “partially zoomed”. The scale rules are set on lines 19-20, so that the rule will apply to any map with a scale denominator between 160,000,000 and 320,000,000. (The is inclusive and the is exclusive, so a zoom level of exactly 320,000,000 would not apply here.) Aside from the scale, the only difference between this rule and the first is the size of the symbol, which is set to 8 pixels on line 29. The third rule (lines 33-47) is the largest scale denominator, corresponding to when the map is “zoomed out”. The scale rule is set on line 35, so that the rule will apply to any map with a scale denominator of 320,000,000 or more. Again, the only other difference between this rule and the others is the size of the symbol, which is set to 4 pixels on line 44. The result of this style is that points are drawn larger as one zooms in and smaller as one zooms out. Lines While lines can also seem to be simple shapes, having length but no width, there are many options and tricks for making lines display nicely. Warning: The code examples shown on this page are not the full SLD code, as they omit the SLD header and footer information for the sake of brevity. Please use the links to download the full SLD for each example. Example lines layer The lines layer used in the examples below contains road information for a fictional country. For reference, the attribute table for the points in this layer is included below. 290 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 fid (Feature ID) line.1 line.2 line.3 line.4 line.5 line.6 line.7 line.8 line.9 line.10 line.11 line.12 line.13 line.14 line.15 line.16 line.17 line.18 line.19 line.20 line.21 line.22 line.23 line.24 line.25 name (Road name) Latway Crescent Avenue Forest Avenue Longway Saxer Avenue Ridge Avenue Holly Lane Mulberry Street Nathan Lane Central Street Lois Lane Rocky Road Fleet Street Diane Court Cedar Trail Victory Road Highland Road Easy Street Hill Street Country Road Main Street Jani Lane Shinbone Alley State Street River Road type (Road class) highway secondary secondary highway secondary secondary local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road Download the lines shapefile Simple line This example specifies lines be colored black with a thickness of 3 pixels. Code View and download the full "Simple line" SLD 1 2 3 4 5 6 7 8 9 10 #000000 3 6.2. SLD Styling 291 GeoServer User Manual, Release 2.15.1 Fig. 6.33: Simple line Details There is one in one for this SLD, which is the simplest possible situation. (All subsequent examples will contain one and one unless otherwise specified.) Styling lines is accomplished via the (lines 3-8). Line 5 specifies the color of the line to be black (#000000), while line 6 specifies the width of the lines to be 3 pixels. Line with border This example shows how to draw lines with borders (sometimes called “cased lines”). In this case the lines are drawn with a 3 pixel blue center and a 1 pixel wide gray border. Code View and download the full "Line with border" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 #333333 5 round 292 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.34: Line with border 15 16 17 18 19 20 21 22 #6699FF 3 round Details Lines in SLD have no notion of a “fill”, only “stroke”. Thus, unlike points or polygons, it is not possible to style the “edge” of the line geometry. It is, however, possible to achieve this effect by drawing each line twice: once with a certain width and again with a slightly smaller width. This gives the illusion of fill and stroke by obscuring the larger lines everywhere except along the edges of the smaller lines. Since every line is drawn twice, the order of the rendering is very important. GeoServer renders s in the order that they are presented in the SLD. In this style, the gray border lines are drawn first via the first , followed by the blue center lines in a second . This ensures that the blue lines are not obscured by the gray lines, and also ensures proper rendering at intersections, so that the blue lines “connect”. In this example, lines 1-11 comprise the first , which is the outer line (or “stroke”). Line 5 specifies the color of the line to be dark gray (#333333), line 6 specifies the width of this line to be 5 pixels, and in line 7 a stroke-linecap parameter of round renders the ends of the line as rounded instead of flat. (When working with bordered lines using a round line cap ensures that the border connects properly at the ends of the lines.) Lines 12-22 comprise the second , which is the the inner line (or “fill”). Line 16 specifies the color of the line to be a medium blue (#6699FF), line 17 specifies the width of this line to be 3 pixels, and line 18 again renders the edges of the line to be rounded instead of flat. 6.2. SLD Styling 293 GeoServer User Manual, Release 2.15.1 The result is a 3 pixel blue line with a 1 pixel gray border, since the 5 pixel gray line will display 1 pixel on each side of the 3 pixel blue line. Dashed line This example alters the Simple line to create a dashed line consisting of 5 pixels of drawn line alternating with 2 pixels of blank space. Fig. 6.35: Dashed line Code View and download the full "Dashed line" SLD 1 2 3 4 5 6 7 8 9 10 11 #0000FF 3 5 2 Details In this example, line 5 sets the color of the lines to be blue (#0000FF) and line 6 sets the width of the lines to be 3 pixels. Line 7 determines the composition of the line dashes. The value of 5 2 creates a repeating pattern of 5 pixels of drawn line, followed by 2 pixels of omitted line. 294 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Offset line This example alters the Simple line to add a perpendicular offset line on the left side of the line, at five pixels distance. Fig. 6.36: Offset line Code View and download the full "Dashed line" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #000000 #FF0000 5 2 5 Details In this example, the first line symbolizer just paints the lines black. line 8 begines a second lines symbolizer, sets the color of the lines to be red (#FF0000) at line 10 and determines the composition of the line dashes 6.2. SLD Styling 295 GeoServer User Manual, Release 2.15.1 at Line 11. Line 13 finally specifies a perpendicular offset of 5 pixels (positive, thus on the left side). Railroad (hatching) This example uses hatching to create a railroad style. Both the line and the hatches are black, with a 2 pixel thickness for the main line and a 1 pixel width for the perpendicular hatches. Note: This example leverages an SLD extension in GeoServer. Hatching is not part of the standard SLD 1.0 specification. Fig. 6.37: Railroad (hatching) Code View and download the full "Railroad (hatching)" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #333333 3 shape://vertline 296 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 16 17 18 19 20 21 22 23 24 25 26 #333333 1 12 Details In this example there are two s. The first symbolizer, on lines 3-8, draws a standard line, with line 5 drawing the lines as dark gray (#333333) and line 6 setting the width of the lines to be 2 pixels. The hatching is invoked in the second symbolizer, on lines 9-24. Line 14 specifies that the symbolizer draw a vertical line hatch (shape://vertline) perpendicular to the line geometry. Lines 16-17 set the hatch color to dark gray (#333333) and width to 1 pixel. Finally, line 20 specifies both the length of the hatch and the distance between each hatch to both be 12 pixels. Spaced graphic symbols This example uses a graphic stroke along with dash arrays to create a “dot and space” line type. Adding the dash array specification allows to control the amount of space between one symbol and the next one. Without using the dash array the lines would be densely populated with dots, each one touching the previous one. Note: This example may not work in other systems using SLD, since they may not support combining the use of stroke-dasharray and GraphicStroke. While the SLD is spec-compliant, the SLD specification does not state what this combination is supposed to produce. Code View and download the full "Spaced symbols" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 circle #666666 #333333 6.2. SLD Styling 297 GeoServer User Manual, Release 2.15.1 Fig. 6.38: Spaced symbols along a line 14 15 16 17 18 19 20 21 22 23 24 1 4 4 6 Details This example, like others before, uses a GraphicStroke to place a graphic symbol along a line. The symbol, defined at lines 7-16 is a 4 pixel gray circle with a dark gray outline. The spacing between symbols is controlled with the stroke-dasharray at line 20, which specifies 4 pixels of pen-down (just enough to draw the circle) and 6 pixels of pen-up, to provide the spacing. Alternating symbols with dash offsets This example shows how to create a complex line style which alternates a dashed line and a graphic symbol. The code builds on features shown in the previous examples: • stroke-dasharray controls pen-down/pen-up behavior to generate dashed lines • GraphicStroke places symbols along a line • combining the two allows control of symbol spacing This also shows the usage of a dash offset, which controls where rendering starts in the dash array. For example, with a dash array of 5 10 and a dash offset of 7 the renderer starts drawing the pattern 7 pixels from the beginning. It skips the 5 pixels pen-down section and 2 pixels of the pen-up section, then draws the remaining 8 pixels of pen-up, then 5 down, 10 up, and so on. 298 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 The example shows how to use these features to create two synchronized sequences of dash arrays, one drawing line segments and the other symbols. Note: This example may not work in other systems using SLD, since they may not support combining the use of stroke-dasharray and GraphicStroke. While the SLD is spec-compliant, the SLD specification does not state what this combination is supposed to produce. Fig. 6.39: Alternating dash and symbol Code View and download the full "Spaced symbols" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 #0000FF 1 10 10 circle #000033 1 5 5 15 6.2. SLD Styling 299 GeoServer User Manual, Release 2.15.1 25 26 27 28 29 7.5 Details In this example two LineSymbolizers use stroke-dasharray and different symbology to produce a sequence of alternating dashes and symbols. The first symbolizer (lines 3-9) is a simple dashed line alternating 10 pixels of pen-down with 10 pixels of pen-up. The second symbolizer (lines 10-27) alternates a 5 pixel empty circle with 15 pixels of white space. The circle symbol is produced by a Mark element, with its symbology specified by stroke parameters (lines 17-18). The spacing between symbols is controlled with the stroke-dasharray (line 24), which specifies 5 pixels of pen-down (just enough to draw the circle) and 15 pixels of pen-up. In order to have the two sequences positioned correctly the second one uses a stroke-dashoffset of 7.5 (line 25). This makes the sequence start with 12.5 pixels of white space, then a circle (which is then centered between the two line segments of the other pattern), then 15 pixels of white space, and so on. Line with default label This example shows a text label on the simple line. This is how a label will be displayed in the absence of any other customization. Fig. 6.40: Line with default label Code View and download the full "Line with default label" SLD 300 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #FF0000 #000000 Details In this example, there is one rule with a and a . The (lines 3-7) draws red lines (#FF0000). Since no width is specified, the default is set to 1 pixel. The (lines 8-15) determines the labeling of the lines. Lines 9-11 specify that the text of the label will be determined by the value of the “name” attribute for each line. (Refer to the attribute table in the Example lines layer section if necessary.) Line 13 sets the text color to black. All other details about the label are set to the renderer default, which here is Times New Roman font, font color black, and font size of 10 pixels. Label following line This example renders the text label to follow the contour of the lines. Note: Labels following lines is an SLD extension specific to GeoServer. It is not part of the SLD 1.0 specification. Code View and download the full "Label following line" SLD 1 2 3 4 5 6 7 8 9 #FF0000 #000000 true Details As the Alternating symbols with dash offsets example showed, the default label behavior isn’t optimal. The label is displayed at a tangent to the line itself, leading to uncertainty as to which label corresponds to which line. This example is similar to the Alternating symbols with dash offsets example with the exception of lines 12-18. Line 18 sets the option to have the label follow the line, while lines 12-14 specify that the label is placed along a line. If is not specified in an SLD, then is assumed, which isn’t compatible with line-specific rendering options. Note: Not all labels are shown due to label conflict resolution. See the next section on Optimized label placement for an example of how to maximize label display. 302 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Optimized label placement This example optimizes label placement for lines such that the maximum number of labels are displayed. Note: This example uses options that are specific to GeoServer and are not part of the SLD 1.0 specification. Fig. 6.42: Optimized label Code View and download the full "Optimized label" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #FF0000 #000000 true 90 400 150 6.2. SLD Styling 303 GeoServer User Manual, Release 2.15.1 22 23 24 Details GeoServer uses “conflict resolution” to ensure that labels aren’t drawn on top of other labels, obscuring them both. This accounts for the reason why many lines don’t have labels in the previous example, Label following line. While this setting can be toggled, it is usually a good idea to leave it on and use other label placement options to ensure that labels are drawn as often as desired and in the correct places. This example does just that. This example is similar to the previous example, Label following line. The only differences are contained in lines 18-21. Line 19 sets the maximum angle that the label will follow. This sets the label to never bend more than 90 degrees to prevent the label from becoming illegible due to a pronounced curve or angle. Line 20 sets the maximum displacement of the label to be 400 pixels. In order to resolve conflicts with overlapping labels, GeoServer will attempt to move the labels such that they are no longer overlapping. This value sets how far the label can be moved relative to its original placement. Finally, line 21 sets the labels to be repeated every 150 pixels. A feature will typically receive only one label, but this can cause confusion for long lines. Setting the label to repeat ensures that the line is always labeled locally. Optimized and styled label This example improves the style of the labels from the Optimized label placement example. Fig. 6.43: Optimized and styled label Code View and download the full "Optimized and styled label" SLD 304 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 #FF0000 #000000 Arial 10 normal bold true 90 400 150 Details This example is similar to the Optimized label placement. The only difference is in the font information, which is contained in lines 18-23. Line 19 sets the font family to be “Arial”, line 20 sets the font size to 10, line 21 sets the font style to “normal” (as opposed to “italic” or “oblique”), and line 22 sets the font weight to “bold” (as opposed to “normal”). Attribute-based line This example styles the lines differently based on the “type” (Road class) attribute. Code View and download the full "Attribute-based line" SLD 1 2 3 4 5 6 7 local-road type local-road 6.2. SLD Styling 305 GeoServer User Manual, Release 2.15.1 Fig. 6.44: Attribute-based line 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 #009933 2 secondary type secondary #0055CC 3 highway type 306 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 41 42 43 44 45 46 47 48 49 50 51 highway #FF0000 6 Details Note: Refer to the Example lines layer to see the attributes for the layer. This example has eschewed labels in order to simplify the style, but you can refer to the example Optimized and styled label to see which attributes correspond to which points. There are three types of road classes in our fictional country, ranging from back roads to high-speed freeways: “highway”, “secondary”, and “local-road”. In order to handle each case separately, there is more than one , each containing a single rule. This ensures that each road type is rendered in order, as each is drawn based on the order in which it appears in the SLD. The three rules are designed as follows: Rule order 1 2 3 Rule name / type local-road secondary highway Color #009933 (green) #0055CC (blue) #FF0000 (red) Size 2 3 6 Lines 2-16 comprise the first . Lines 4-9 set the filter for this rule, such that the “type” attribute has a value of “local-road”. If this condition is true for a particular line, the rule is rendered according to the which is on lines 10-15. Lines 12-13 set the color of the line to be a dark green (#009933) and the width to be 2 pixels. Lines 19-33 comprise the second . Lines 21-26 set the filter for this rule, such that the “type” attribute has a value of “secondary”. If this condition is true for a particular line, the rule is rendered according to the which is on lines 27-32. Lines 29-30 set the color of the line to be a dark blue (#0055CC) and the width to be 3 pixels, making the lines slightly thicker than the “local-road” lines and also a different color. Lines 36-50 comprise the third and final . Lines 38-43 set the filter for this rule, such that the “type” attribute has a value of “primary”. If this condition is true for a particular line, the rule is rendered according to the which is on lines 44-49. Lines 46-47 set the color of the line to be a bright red (#FF0000) and the width to be 6 pixels, so that these lines are rendered on top of and thicker than the other two road classes. In this way, the “primary” roads are given priority in the map rendering. Zoom-based line This example alters the Simple line style at different zoom levels. 6.2. SLD Styling 307 GeoServer User Manual, Release 2.15.1 Fig. 6.45: Zoom-based line: Zoomed in Fig. 6.46: Zoom-based line: Partially zoomed 308 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.47: Zoom-based line: Zoomed out Code View and download the full "Zoom-based line" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Large 180000000 #009933 6 Medium 180000000 360000000 #009933 4 Small 360000000 #009933 2 6.2. SLD Styling 309 GeoServer User Manual, Release 2.15.1 31 32 33 Details It is often desirable to make shapes larger at higher zoom levels when creating a natural-looking map. This example varies the thickness of the lines according to the zoom level (or more accurately, scale denominator). Scale denominators refer to the scale of the map. A scale denominator of 10,000 means the map has a scale of 1:10,000 in the units of the map projection. Note: Determining the appropriate scale denominators (zoom levels) to use is beyond the scope of this example. This style contains three rules. The three rules are designed as follows: Rule order 1 2 3 Rule name Large Medium Small Scale denominator 1:180,000,000 or less 1:180,000,000 to 1:360,000,000 Greater than 1:360,000,000 Line width 6 4 2 The order of these rules does not matter since the scales denominated in each rule do not overlap. The first rule (lines 2-11) is the smallest scale denominator, corresponding to when the view is “zoomed in”. The scale rule is set on line 4, so that the rule will apply to any map with a scale denominator of 180,000,000 or less. Line 7-8 draws the line to be dark green (#009933) with a width of 6 pixels. The second rule (lines 12-22) is the intermediate scale denominator, corresponding to when the view is “partially zoomed”. Lines 14-15 set the scale such that the rule will apply to any map with scale denominators between 180,000,000 and 360,000,000. (The is inclusive and the is exclusive, so a zoom level of exactly 360,000,000 would not apply here.) Aside from the scale, the only difference between this rule and the previous is the width of the lines, which is set to 4 pixels on line 19. The third rule (lines 23-32) is the largest scale denominator, corresponding to when the map is “zoomed out”. The scale rule is set on line 25, so that the rule will apply to any map with a scale denominator of 360,000,000 or greater. Again, the only other difference between this rule and the others is the width of the lines, which is set to 2 pixels on line 29. The result of this style is that lines are drawn with larger widths as one zooms in and smaller widths as one zooms out. Polygons Polygons are two dimensional shapes that contain both an outer edge (or “stroke”) and an inside (or “fill”). A polygon can be thought of as an irregularly-shaped point and is styled in similar ways to points. Warning: The code examples shown on this page are not the full SLD code, as they omit the SLD header and footer information for the sake of brevity. Please use the links to download the full SLD for each example. 310 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Example polygons layer The polygons layer used below contains county information for a fictional country. For reference, the attribute table for the polygons is included below. fid (Feature ID) polygon.1 polygon.2 polygon.3 polygon.4 polygon.5 polygon.6 polygon.7 polygon.8 name (County name) Irony County Tracker County Dracula County Poly County Bearing County Monte Cristo County Massive County Rhombus County pop (Population) 412234 235421 135022 1567879 201989 152734 67123 198029 Download the polygons shapefile Simple polygon This example shows a polygon filled in blue. Fig. 6.48: Simple polygon Code View and download the full "Simple polygon" SLD 1 2 3 6.2. SLD Styling 311 GeoServer User Manual, Release 2.15.1 4 5 6 7 8 9 #000080 Details There is one in one for this style, which is the simplest possible situation. (All subsequent examples will share this characteristic unless otherwise specified.) Styling polygons is accomplished via the (lines 3-7). Line 5 specifies dark blue (#000080) as the polygon’s fill color. Note: The light-colored borders around the polygons in the figure are artifacts of the renderer caused by the polygons being adjacent. There is no border in this style. Simple polygon with stroke This example adds a 2 pixel white stroke to the Simple polygon example. Fig. 6.49: Simple polygon with stroke Code View and download the full "Simple polygon with stroke" SLD 312 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 1 2 3 4 5 6 7 8 9 10 11 12 13 #000080 #FFFFFF 2 Details This example is similar to the Simple polygon example above, with the addition of the tag (lines 7-10). Line 8 sets the color of stroke to white (#FFFFFF) and line 9 sets the width of the stroke to 2 pixels. Transparent polygon This example builds on the Simple polygon with stroke example and makes the fill partially transparent by setting the opacity to 50%. Fig. 6.50: Transparent polygon Code View and download the full "Transparent polygon" SLD 6.2. SLD Styling 313 GeoServer User Manual, Release 2.15.1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 #000080 0.5 #FFFFFF 2 Details This example is similar to the Simple polygon with stroke example, save for defining the fill’s opacity in line 6. The value of 0.5 results in partially transparent fill that is 50% opaque. An opacity value of 1 would draw the fill as 100% opaque, while an opacity value of 0 would result in a completely transparent (0% opaque) fill. In this example, since the background is white, the dark blue looks lighter. Were the points imposed on a dark background, the resulting color would be darker. Offset inner lines Shows how to draw inner buffer lines inside a polygon. Fig. 6.51: Offset buffer 314 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Code View and download the full "Inner offset lines" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #000000 2 #AAAAAA 3 -2 Details This example is similar to the Simple polygon with stroke example, save for defining adding a > at line 9, where a light gray (line 11) 3 pixels wide (line 12) line is drawn as a inner buffer inside the polygon. Line 14 controls the buffering distance, setting a inner buffer of 2 pixels. Graphic fill This example fills the polygons with a tiled graphic. Fig. 6.52: Graphic fill 6.2. SLD Styling 315 GeoServer User Manual, Release 2.15.1 Code View and download the full "Graphic fill" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 image/png 93 Details This style fills the polygon with a tiled graphic. This is known as an in SLD, to distinguish it from commonly-used shapes such as squares and circles that are “internal” to the renderer. Lines 7-12 specify details for the graphic, with line 10 setting the path and file name of the graphic and line 11 indicating the file format (MIME type) of the graphic (image/png). Although a full URL could be specified if desired, no path information is necessary in line 11 because this graphic is contained in the same directory as the SLD. Line 13 determines the height of the displayed graphic in pixels; if the value differs from the height of the graphic then it will be scaled accordingly while preserving the aspect ratio. Fig. 6.53: Graphic used for fill Hatching fill This example fills the polygons with a hatching pattern. Note: This example leverages an SLD extension in GeoServer. Hatching is not part of the standard SLD 1.0 specification. 316 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.54: Hatching fill Code View and download the full "Hatching fill" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 shape://times #990099 1 16 Details In this example, there is a tag as in the Graphic fill example, but a (lines 7-13) is used instead of an . Line 8 specifies a “times” symbol (an “x”) be tiled throughout the polygon. Line 10 sets the color to purple (#990099), line 11 sets the width of the hatches to 1 pixel, and line 14 sets the size of the tile to 16 pixels. Because hatch tiles are always square, the sets both the 6.2. SLD Styling 317 GeoServer User Manual, Release 2.15.1 width and the height. Polygon with default label This example shows a text label on the polygon. In the absence of any other customization, this is how a label will be displayed. Fig. 6.55: Polygon with default label Code View and download the full "Polygon with default label" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #40FF40 #FFFFFF 2 318 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Details In this example there is a and a . Lines 3-11 comprise the . The fill of the polygon is set on line 5 to a light green (#40FF40) while the stroke of the polygon is set on lines 8-9 to white (#FFFFFF) with a thickness of 2 pixels. The label is set in the on lines 12-16, with line 14 determining what text to display, in this case the value of the “name” attribute. (Refer to the attribute table in the Example polygons layer section if necessary.) All other details about the label are set to the renderer default, which here is Times New Roman font, font color black, and font size of 10 pixels. Label halo This example alters the look of the Polygon with default label by adding a white halo to the label. Fig. 6.56: Label halo Code View and download the full "Label halo" SLD 1 2 3 4 5 6 7 8 9 10 11 12 #40FF40 #FFFFFF 2 6.2. SLD Styling 319 GeoServer User Manual, Release 2.15.1 13 14 15 16 17 18 19 20 21 22 23 24 3 #FFFFFF Details This example is similar to the Polygon with default label, with the addition of a halo around the labels on lines 16-21. A halo creates a color buffer around the label to improve label legibility. Line 17 sets the radius of the halo, extending the halo 3 pixels around the edge of the label, and line 19 sets the color of the halo to white (#FFFFFF). Since halos are most useful when set to a sharp contrast relative to the text color, this example uses a white halo around black text to ensure optimum readability. Polygon with styled label This example improves the label style from the Polygon with default label example by centering the label on the polygon, specifying a different font name and size, and setting additional label placement optimizations. Note: The label placement optimizations discussed below (the tags) are SLD extensions that are custom to GeoServer. They are not part of the SLD 1.0 specification. Code View and download the full "Polygon with styled label" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #40FF40 #FFFFFF 2 Arial 320 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.57: Polygon with styled label 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 11 normal bold 0.5 0.5 #000000 60 150 Details This example is similar to the Polygon with default label example, with additional styling options within the on lines 12-35. Lines 16-21 set the font styling. Line 17 sets the font family to be Arial, line 18 sets the font size to 11 pixels, line 19 sets the font style to “normal” (as opposed to “italic” or “oblique”), and line 20 sets the font weight to “bold” (as opposed to “normal”). The tag on lines 22-29 affects where the label is placed relative to the centroid of the polygon. Line 21 centers the label by positioning it 50% (or 0.5) of the way horizontally along the centroid of the polygon. Line 22 centers the label vertically in exactly the same way. 6.2. SLD Styling 321 GeoServer User Manual, Release 2.15.1 Finally, there are two added touches for label placement optimization: line 33 ensures that long labels are split across multiple lines by setting line wrapping on the labels to 60 pixels, and line 34 allows the label to be displaced by up to 150 pixels. This ensures that labels are compacted and less likely to spill over polygon boundaries. Notice little Massive County in the corner, whose label is now displayed.” Attribute-based polygon This example styles the polygons differently based on the “pop” (Population) attribute. Fig. 6.58: Attribute-based polygon Code View and download the full "Attribute-based polygon" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 SmallPop Less Than 200,000 pop 200000 #66FF66 MediumPop 322 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 19 20 21 22 23 24 25 26 27 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 200,000 to 500,000 pop 200000 pop 500000 #33CC33 LargePop Greater Than 500,000 pop 500000 #009900 Details Note: Refer to the Example polygons layer to see the attributes for the layer. This example has eschewed labels in order to simplify the style, but you can refer to the example Polygon with styled label to see which attributes correspond to which polygons. Each polygon in our fictional country has a population that is represented by the population (“pop”) attribute. This style contains three rules that alter the fill based on the value of “pop” attribute, with smaller values yielding a lighter color and larger values yielding a darker color. The three rules are designed as follows: Rule order 1 2 3 6.2. SLD Styling Rule name SmallPop MediumPop LargePop Population (“pop”) Less than 200,000 200,000 to 500,000 Greater than 500,000 Color #66FF66 #33CC33 #009900 323 GeoServer User Manual, Release 2.15.1 The order of the rules does not matter in this case, since each shape is only rendered by a single rule. The first rule, on lines 2-16, specifies the styling of polygons whose population attribute is less than 200,000. Lines 5-10 set this filter, with lines 6-9 setting the “less than” filter, line 7 denoting the attribute (“pop”), and line 8 the value of 200,000. The color of the polygon fill is set to a light green (#66FF66) on line 13. The second rule, on lines 17-37, is similar, specifying a style for polygons whose population attribute is greater than or equal to 200,000 but less than 500,000. The filter is set on lines 20-31. This filter is longer than in the first rule because two criteria need to be specified instead of one: a “greater than or equal to” and a “less than” filter. Notice the And on line 21 and line 30. This mandates that both filters need to be true for the rule to be applicable. The color of the polygon fill is set to a medium green on (#33CC33) on line 34. The third rule, on lines 38-52, specifies a style for polygons whose population attribute is greater than or equal to 500,000. The filter is set on lines 41-46. The color of the polygon fill is the only other difference in this rule, which is set to a dark green (#009900) on line 49. Zoom-based polygon This example alters the style of the polygon at different zoom levels. Fig. 6.59: Zoom-based polygon: Zoomed in Code View and download the full "Zoom-based polygon" SLD 1 2 3 4 5 6 Large 100000000 324 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.60: Zoom-based polygon: Partially zoomed Fig. 6.61: Zoom-based polygon: Zoomed out 6.2. SLD Styling 325 GeoServer User Manual, Release 2.15.1 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 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 #0000CC #000000 7 Arial 14 normal bold 0.5 0.5 #FFFFFF Medium 100000000 200000000 #0000CC #000000 4 Small 200000000 #0000CC #000000 1 326 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Details It is often desirable to make shapes larger at higher zoom levels when creating a natural-looking map. This example varies the thickness of the lines according to the zoom level. Polygons already do this by nature of being two dimensional, but another way to adjust styling of polygons based on zoom level is to adjust the thickness of the stroke (to be larger as the map is zoomed in) or to limit labels to only certain zoom levels. This is ensures that the size and quantity of strokes and labels remains legible and doesn’t overshadow the polygons themselves. Zoom levels (or more accurately, scale denominators) refer to the scale of the map. A scale denominator of 10,000 means the map has a scale of 1:10,000 in the units of the map projection. Note: Determining the appropriate scale denominators (zoom levels) to use is beyond the scope of this example. This style contains three rules, defined as follows: Rule order Rule name Scale denominator 1 2 3 Large Medium Small 1:100,000,000 or less 1:100,000,000 to 1:200,000,000 Greater than 1:200,000,000 Stroke width 7 4 2 Label play? Yes No No dis- The first rule, on lines 2-36, is for the smallest scale denominator, corresponding to when the view is “zoomed in”. The scale rule is set on line 40 such that the rule will apply only where the scale denominator is 100,000,000 or less. Line 7 defines the fill as blue (#0000CC). Note that the fill is kept constant across all rules regardless of the scale denominator. As in the Polygon with default label or Polygon with styled label examples, the rule also contains a at lines 14-35 for drawing a text label on top of the polygon. Lines 19-22 set the font information to be Arial, 14 pixels, and bold with no italics. The label is centered both horizontally and vertically along the centroid of the polygon on by setting and to both be 0.5 (or 50%) on lines 27-28. Finally, the color of the font is set to white (#FFFFFF) in line 33. The second rule, on lines 37-50, is for the intermediate scale denominators, corresponding to when the view is “partially zoomed”. The scale rules on lines 39-40 set the rule such that it will apply to any map with a scale denominator between 100,000,000 and 200,000,000. (The is inclusive and the is exclusive, so a zoom level of exactly 200,000,000 would not apply here.) Aside from the scale, there are two differences between this rule and the first: the width of the stroke is set to 4 pixels on line 47 and a is not present so that no labels will be displayed. The third rule, on lines 51-63, is for the largest scale denominator, corresponding to when the map is “zoomed out”. The scale rule is set on line 53 such that the rule will apply to any map with a scale denominator of 200,000,000 or greater. Again, the only differences between this rule and the others are the width of the lines, which is set to 1 pixel on line 60, and the absence of a so that no labels will be displayed. The resulting style produces a polygon stroke that gets larger as one zooms in and labels that only display when zoomed in to a sufficient level. Rasters Rasters are geographic data displayed in a grid. They are similar to image files such as PNG files, except that instead of each point containing visual information, each point contains geographic information in 6.2. SLD Styling 327 GeoServer User Manual, Release 2.15.1 numerical form. Rasters can be thought of as a georeferenced table of numerical values. One example of a raster is a Digital Elevation Model (DEM) layer, which has elevation data encoded numerically at each georeferenced data point. Warning: The code examples shown on this page are not the full SLD code, as they omit the SLD header and footer information for the sake of brevity. Please use the links to download the full SLD for each example. Example raster The raster layer that is used in the examples below contains elevation data for a fictional world. The data is stored in EPSG:4326 (longitude/latitude) and has a data range from 70 to 256. If rendered in grayscale, where minimum values are colored black and maximum values are colored white, the raster would look like this: Fig. 6.62: Raster file as rendered in grayscale Download the raster shapefile Two-color gradient This example shows a two-color style with green at lower elevations and brown at higher elevations. Fig. 6.63: Two-color gradient 328 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Code View and download the full "Two-color gradient" SLD 1 2 3 4 5 6 7 8 9 10 Details There is one in one for this example, which is the simplest possible situation. All subsequent examples will share this characteristic. Styling of rasters is done via the tag (lines 3-8). This example creates a smooth gradient between two colors corresponding to two elevation values. The gradient is created via the on lines 4-7. Each entry in the represents one entry or anchor in the gradient. Line 5 sets the lower value of 70 via the quantity parameter, which is styled a dark green (#008000). Line 6 sets the upper value of 256 via the quantity parameter again, which is styled a dark brown (#663333). All data values in between these two quantities will be linearly interpolated: a value of 163 (the midpoint between 70 and 256) will be colored as the midpoint between the two colors (in this case approximately #335717, a muddy green). Transparent gradient This example creates the same two-color gradient as in the Two-color gradient as in the example above but makes the entire layer mostly transparent by setting a 30% opacity. Fig. 6.64: Transparent gradient Code View and download the full "Transparent gradient" SLD 6.2. SLD Styling 329 GeoServer User Manual, Release 2.15.1 1 2 3 4 5 6 7 8 9 10 11 0.3 Details This example is similar to the Two-color gradient example save for the addition of line 4, which sets the opacity of the layer to 0.3 (or 30% opaque). An opacity value of 1 means that the shape is drawn 100% opaque, while an opacity value of 0 means that the shape is rendered as completely transparent. The value of 0.3 means that the the raster partially takes on the color and style of whatever is drawn beneath it. Since the background is white in this example, the colors generated from the look lighter, but were the raster imposed on a dark background the resulting colors would be darker. Brightness and contrast This example normalizes the color output and then increases the brightness by a factor of 2. Fig. 6.65: Brightness and contrast Code View and download the full "Brightness and contrast" SLD 1 2 3 4 5 6 7 8 0.5 330 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 9 10 11 12 13 14 Details This example is similar to the Two-color gradient, save for the addition of the tag on lines 4-7. Line 5 normalizes the output by increasing the contrast to its maximum extent. Line 6 then adjusts the brightness by a factor of 0.5. Since values less than 1 make the output brighter, a value of 0.5 makes the output twice as bright. As with previous examples, lines 8-11 determine the , with line 9 setting the lower bound (70) to be colored dark green (#008000) and line 10 setting the upper bound (256) to be colored dark brown (#663333). Three-color gradient This example creates a three-color gradient in primary colors. Fig. 6.66: Three-color gradient Code View and download the full "Three-color gradient" SLD 1 2 3 4 5 6 7 8 9 10 11 Details This example creates a three-color gradient based on a with three entries on lines 4-8: line 5 specifies the lower bound (150) be styled in blue (#0000FF), line 6 specifies an intermediate point (200) be 6.2. SLD Styling 331 GeoServer User Manual, Release 2.15.1 styled in yellow (#FFFF00), and line 7 specifies the upper bound (250) be styled in red (#FF0000). Since our data values run between 70 and 256, some data points are not accounted for in this style. Those values below the lowest entry in the color map (the range from 70 to 149) are styled the same color as the lower bound, in this case blue. Values above the upper bound in the color map (the range from 251 to 256) are styled the same color as the upper bound, in this case red. Alpha channel This example creates an “alpha channel” effect such that higher values are increasingly transparent. Fig. 6.67: Alpha channel Code View and download the full "Alpha channel" SLD 1 2 3 4 5 6 7 8 9 10 Details An alpha channel is another way of referring to variable transparency. Much like how a gradient maps values to colors, each entry in a can have a value for opacity (with the default being 1.0 or completely opaque). In this example, there is a with two entries: line 5 specifies the lower bound of 70 be colored dark green (#008000), while line 6 specifies the upper bound of 256 also be colored dark green but with an opacity value of 0. This means that values of 256 will be rendered at 0% opacity (entirely transparent). Just like the gradient color, the opacity is also linearly interpolated such that a value of 163 (the midpoint between 70 and 256) is rendered at 50% opacity. 332 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Discrete colors This example shows a gradient that is not linearly interpolated but instead has values mapped precisely to one of three specific colors. Note: This example leverages an SLD extension in GeoServer. Discrete colors are not part of the standard SLD 1.0 specification. Fig. 6.68: Discrete colors Code View and download the full "Discrete colors" SLD 1 2 3 4 5 6 7 8 9 10 Details Sometimes color bands in discrete steps are more appropriate than a color gradient. The type="intervals" parameter added to the on line 4 sets the display to output discrete colors instead of a gradient. The values in each entry correspond to the upper bound for the color band such that colors are mapped to values less than the value of one entry but greater than or equal to the next lower entry. For example, line 5 colors all values less than 150 to dark green (#008000) and line 6 colors all values less than 256 but greater than or equal to 150 to dark brown (#663333). Many color gradient This example shows a gradient interpolated across eight different colors. 6.2. SLD Styling 333 GeoServer User Manual, Release 2.15.1 Fig. 6.69: Many color gradient Code View and download the full "Many color gradient" SLD 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 quantity="95" /> quantity="110" /> quantity="135" /> quantity="160" /> quantity="185" /> quantity="210" /> quantity="235" /> quantity="256" /> Details A can include up to 255 elements. This example has eight entries (lines 4-13): Entry number 1 2 3 4 5 6 7 8 334 Value Color RGB code 95 110 135 160 185 210 235 256 Black Blue Green Red Purple Yellow Cyan White #000000 #0000FF #00FF00 #FF0000 #FF00FF #FFFF00 #00FFFF #FFFFFF Chapter 6. Styling GeoServer User Manual, Release 2.15.1 6.2.4 SLD Reference The OGC Styled Layer Descriptor (SLD) standard defines a language for expressing styling of geospatial data. GeoServer uses SLD as its primary styling language. SLD 1.0.0 is defined in the following specification: • OGC Styled Layer Descriptor Implementation Specification, Version 1.0.0 Subsequently the functionality of SLD has been split into two specifications: • OGC Symbology Encoding Implementation Specification, Version 1.1.0 • OGC Styled Layer Descriptor profile of the Web Map Service Implementation Specification, Version 1.1.0 GeoServer implements the SLD 1.0.0 standard, as well as some parts of the SE 1.1.0 and WMS-SLD 1.1.0 standards. Elements of SLD The following sections describe the SLD elements implemented in GeoServer. The root element for an SLD is . It contains a Layers and Styles elements which describe how a map is to be composed and styled. StyledLayerDescriptor The root element for an SLD is . It contains a sequence of Layers defining the styled map content. The element contains the following elements: Tag Required? 0..N 0..N Description A reference to a named layer in the server catalog A layer defined in the style itself Layers An SLD document contains a sequence of layer definitions indicating the layers to be styled. Each layer definition is either a NamedLayer reference or a supplied UserLayer. NamedLayer A NamedLayer specifies an existing layer to be styled, and the styling to apply to it. The styling may be any combination of catalog styles and explicitly-defined styles. If no style is specified, the default style for the layer is used. The element contains the following elements: Tag 6.2. SLD Styling Required? Yes No 0..N 0..N Description The name of the layer to be styled. (Ignored in catalog styles.) The description for the layer. The name of a catalog style to apply to the layer. The definition of a style to apply to the layer. See Styles 335 GeoServer User Manual, Release 2.15.1 UserLayer A UserLayer defines a new layer to be styled, and the styling to apply to it. The data for the layer is provided directly in the layer definition using the element. Since the layer is not known to the server, the styling must be explicitly specified as well. The element contains the following elements: Tag Required? No No No 1..N Description The name for the layer being defined The description for the layer One or more feature collections providing the layer data, specified using GML. The definition of the style(s) to use for the layer. See Styles A common use is to define a geometry to be rendered to indicate an Area Of Interest. InlineFeature An InlineFeature element contains data defining a layer to be styled. The element contains one or more elements defining the data. Each Feature Collection can contain any number of elements, each containing a feature specified using GML markup. The features can contain any type of geometry (point, line or polygon, and collections of these). They may also contain scalar-valued attributes, which can be useful for labelling. Example The following style specifies a named layer using the default style, and a user-defined layer with inline data and styling. It displays the US States layer, with a labelled red box surrounding the Pacific NW. usa:states Inline -127.0,51.0 -110.0,51.0 -110.0,41.0 -127.0,41.0 -127.0,51.0 336 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Pacific NW #FF0000 2 title #FF0000 Styles The style elements specify the styling to be applied to a layer. UserStyle The UserStyle element defines styling for a layer. The element contains the following elements: Tag Required? No <Abstract> <IsDefault> No No No <FeatureTypeStyle> 1..N Description The name of the style, used to reference it externally. (Ignored for catalog styles.) The title of the style. The description for the style. Whether the style is the default one for a named layer. Used in SLD Library Mode. Values are 1 or 0 (default). Defines the symbology for rendering a single feature type. FeatureTypeStyle The FeatureTypeStyle element specifies the styling that is applied to a single feature type of a layer. It contains a list of rules which determine the symbology to be applied to each feature of a layer. 6.2. SLD Styling 337 GeoServer User Manual, Release 2.15.1 The <FeatureTypeStyle> element contains the following elements: Tag <Name> <Title> <Abstract> <FeatureTypeName> Required? No No No No <Rule> 1..N Description Not used at present The title for the style. The description for the style. Identifies the feature type the style is to be applied to. Omitted if the style applies to all features in a layer. A styling rule to be evaluated. See Rules Usually a layer contains only a single feature type, so the <FeatureTypeName> is omitted. Any number of <FeatureTypeStyle> elements can be specified in a style. In GeoServer each one is rendered into a separate image buffer. After all features are rendered the buffers are composited to form the final layer image. The compositing is done in the order the FeatureTypeStyles are given in the SLD, with the first one on the bottom (the “Painter’s Model”). This effectively creates “virtual layers”, which can be used to achieve styling effects such as cased lines. Styles contain Rules and Filters to determine sets of features to be styled with specific symbology. Rules may also specify the scale range in which the feature styling is visible. Rules Styling rules define the portrayal of features. A rule combines a filter with any number of symbolizers. Features for which the filter condition evaluates as true are rendered using the the symbolizers in the rule. Syntax The <Rule> element contains the following elements: Tag <Name> <Title> Required? No No <Abstract> <Filter> No No <MinScaleDenominator> No <MaxScaleDenominator> No <PointSymbolizer> <LineSymbolizer> <PolygonSymbolizer> <TextSymbolizer> <RasterSymbolizer> 338 0..N 0..N 0..N 0..N 0..N Description Specifies a name for the rule. Specifies a title for the rule. The title is used in display lists and legends. Specifies an abstract describing the rule. Specifies a filter controlling when the rule is applied. See Filters Specifies the minimum scale denominator (inclusive) for the scale range in which this rule applies. If present, the rule applies at the given scale and all smaller scales. Specifies the maximum scale denominator (exclusive) for the scale range in which this rule applies. If present, the rule applies at scales larger than the given scale. Specifies styling as points. See PointSymbolizer Specifies styling as lines. See LineSymbolizer Specifies styling as polygons. See PolygonSymbolizer Specifies styling for text labels. See TextSymbolizer Specifies styling for raster data. See RasterSymbolizer Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Scale Selection Rules support scale selection to allow specifying the scale range in which a rule may be applied (assuming the filter condition is satisfied as well, if present). Scale selection allows for varying portrayal of features at different map scales. In particular, at smaller scales it is common to use simpler styling for features, or even prevent the display of some features altogether. Scale ranges are specified by using scale denominators. These values correspond directly to the ground distance covered by a map, but are inversely related to the common “large” and “small” terminology for map scale. In other words: • large scale maps cover less area and have a smaller scale denominator • small scale maps cover more area and have a larger scale denominator Two optional elements specify the scale range for a rule: Tag <MinScaleDenominator> Required? No <MaxScaleDenominator> No Description Specifies the minimum scale denominator (inclusive) for the scale range in which this rule applies. If present, the rule applies at the given scale and all smaller scales. Specifies the maximum scale denominator (exclusive) for the scale range in which this rule applies. If present, the rule applies at scales larger than the given scale. Note: The current scale can also be obtained via the wms_scale_denominator SLD environment variable. This allows including scale dependency in Filter Expressions. The following example shows the use of scale selection in a pair of rules. The rules specify that: • at scales above 1:20,000 (larger scales, with scale denominators smaller than 20,000) features are symbolized with 10-pixel red squares, • at scales at or below 1:20,000 (smaller scales, with scale denominators larger than 20,000) features are symbolized with 4-pixel blue triangles. <Rule> <MaxScaleDenominator>20000</MaxScaleDenominator> <PointSymbolizer> <Graphic> <Mark> <WellKnownName>square</WellKnownName> <Fill><CssParameter name="fill">#FF0000</CssParameter> </Mark> <Size>10</Size> </Graphic> </PointSymbolizer> </Rule> <Rule> <MinScaleDenominator>20000</MinScaleDenominator> <PointSymbolizer> <Graphic> <Mark> <WellKnownName>triangle</WellKnownName> <Fill><CssParameter name="fill">#0000FF</CssParameter> </Mark> 6.2. SLD Styling 339 GeoServer User Manual, Release 2.15.1 <Size>4</Size> </Graphic> </PointSymbolizer> </Rule> Evaluation Order Within an SLD document each <FeatureTypeStyle> can contain many rules. Multiple-rule SLDs are the basis for thematic styling. In GeoServer each <FeatureTypeStyle> is evaluated once for each feature processed. The rules within it are evaluated in the order they occur. A rule is applied when its filter condition (if any) is true for a feature and the rule is enabled at the current map scale. The rule is applied by rendering the feature using each symbolizer within the rule, in the order in which they occur. The rendering is performed into the image buffer for the parent <FeatureTypeStyle>. Thus symbolizers earlier in a FeatureTypeStyle and Rule are rendered before symbolizers occuring later in the document (this is the “Painter’s Model” method of rendering). Examples The following rule applies only to features which have a POPULATION attribute greater than 100,000, and symbolizes the features as red points. <Rule> <ogc:Filter> <ogc:PropertyIsGreaterThan> <ogc:PropertyName>POPULATION</ogc:PropertyName> <ogc:Literal>100000</ogc:Literal> </ogc:PropertyIsGreaterThan> </ogc:Filter> <PointSymbolizer> <Graphic> <Mark> <Fill><CssParameter name="fill">#FF0000</CssParameter> </Mark> </Graphic> </PointSymbolizer> </Rule> An additional rule can be added which applies to features whose POPULATION attribute is less than 100,000, and symbolizes them as green points. <Rule> <ogc:Filter> <ogc:PropertyIsLessThan> <ogc:PropertyName>POPULATION</ogc:PropertyName> <ogc:Literal>100000</ogc:Literal> </ogc:PropertyIsLessThan> </ogc:Filter> <PointSymbolizer> <Graphic> <Mark> <Fill><CssParameter name="fill">#0000FF</CssParameter> </Mark> </Graphic> 340 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 </PointSymbolizer> </Rule> Filters A filter is the mechanism in SLD for specifying conditions. They are similar in functionality to the SQL “WHERE” clause. Filters are used within Rules to determine which styles should be applied to which features in a data set. The filter language used by SLD follows the OGC Filter Encoding standard. It is described in detail in the Filter Encoding Reference. A filter condition is specified by using a comparison operator or a spatial operator, or two or more of these combined by logical operators. The operators are usually used to compare properties of the features being filtered to other properties or to literal data. Comparison operators Comparison operators are used to specify conditions on the non-spatial attributes of a feature. The following binary comparison operators are available: • <PropertyIsEqualTo> • <PropertyIsNotEqualTo> • <PropertyIsLessThan> • <PropertyIsLessThanOrEqualTo> • <PropertyIsGreaterThan> • <PropertyIsGreaterThanOrEqualTo> These operators contain two filter expressions to be compared. The first operand is often a <PropertyName>, but both operands may be any expression, function or literal value. Binary comparison operators may include a matchCase attribute with the value true or false. If this attribute is true (which is the default), string comparisons are case-sensitive. If the attribute is specified and has the value false strings comparisons do not check case. Other available value comparison operators are: • <PropertyIsLike> • <PropertyIsNull> • <PropertyIsBetween> <PropertyIsLike> matches a string property value against a text pattern. It contains a <PropertyName> element containing the name of the property containing the string to be matched and a <Literal> element containing the pattern. The pattern is specified by a sequence of regular characters and three special pattern characters. The pattern characters are defined by the following required attributes of the <PropertyIsLike> element: • wildCard specifies a pattern character which matches any sequence of zero or more characters • singleChar specifies a pattern character which matches any single character • escapeChar specifies an escape character which can be used to escape these pattern characters 6.2. SLD Styling 341 GeoServer User Manual, Release 2.15.1 <PropertyIsNull> tests whether a property value is null. It contains a single <PropertyName> element containing the name of the property containing the value to be tested. <PropertyIsBetween> tests whether an expression value lies within a range. It contains a filter expression providing the value to test, followed by the elements <LowerBoundary> and <UpperBoundary>, each containing a filter expression. Examples • The following filter selects features whose NAME attribute has the value of “New York”: <PropertyIsEqualTo> <PropertyName>NAME</PropertyName> <Literal>New York</Literal> </PropertyIsEqualTo> • The following filter selects features whose geometry area is greater than 1,000,000: <PropertyIsGreaterThan> <ogc:Function name="area"> <PropertyName>GEOMETRY</PropertyName> </ogc:Function> <Literal>1000000</Literal> </PropertyIsEqualTo> Spatial operators Spatial operators are used to specify conditions on the geometric attributes of a feature. The following spatial operators are available: Topological Operators These operators test topological spatial relationships using the standard OGC Simple Features predicates: • <Intersects> • <Equals> • <Disjoint> • <Touches> • <Within> • <Overlaps> • <Crosses> • <Intersects> • <Contains> The content for these operators is a <PropertyName> element for a geometry-valued property and a GML geometry literal. Distance Operators These operators compute distance relationships between geometries: • <DWithin> 342 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 • <Beyond> The content for these elements is a <PropertyName> element for a geometry-valued property, a GML geometry literal, and a <Distance> element containing the value for the distance tolerance. The <Distance> element may include an optional units attribute. Bounding Box Operator This operator tests whether a feature geometry attribute intersects a given bounding box: • <BBOX> The content is an optional <PropertyName> element, and a GML envelope literal. If the PropertyName is omitted the default geometry attribute is assumed. Examples • The following filter selects features with a geometry that intersects the point (1,1): <Intersects> <PropertyName>GEOMETRY</PropertyName> <Literal> <gml:Point> <gml:coordinates>1 1</gml:coordinates> </gml:Point> </Literal> </Intersects> • The following filter selects features with a geometry that intersects the box [-10,0 : 10,10]: <ogc:BBOX> <ogc:PropertyName>GEOMETRY</ogc:PropertyName> <gml:Box srsName="urn:x-ogc:def:crs:EPSG:4326"> <gml:coord> <gml:X>-10</gml:X> <gml:Y>0</gml:Y> </gml:coord> <gml:coord> <gml:X>10</gml:X> <gml:Y>10</gml:Y> </gml:coord> </gml:Box> </ogc:BBOX> Logical operators Logical operators are used to create logical combinations of other filter operators. They may be nested to any depth. The following logical operators are available: • <And> • <Or> • <Not> The content for <And> and <Or> is two filter operator elements. The content for <Not> is a single filter operator element. 6.2. SLD Styling 343 GeoServer User Manual, Release 2.15.1 Examples • The following filter uses <And> to combine a comparison operator and a spatial operator: <And> <PropertyIsEqualTo> <PropertyName>NAME</PropertyName> <Literal>New York</Literal> </PropertyIsEqualTo> <Intersects> <PropertyName>GEOMETRY</PropertyName> <Literal> <gml:Point> <gml:coordinates>1 1</gml:coordinates> </gml:Point> </Literal> </Intersects> </And> Filter Expressions Filter expressions allow performing computation on data values. The following elements can be used to form expressions. Arithmetic Operators These operators perform arithmetic on numeric values. Each contains two expressions as sub-elements. • <Add> • <Sub> • <Mul> • <Div> Functions The <Function> element specifies a filter function to be evaluated. The name attribute gives the function name. The element contains a sequence of zero or more filter expressions providing the function arguments. See the Filter Function Reference for details of the functions provided by GeoServer. Feature Property Values The <PropertyName> element allows referring to the value of a given feature attribute. It contains a string specifying the attribute name. Literals The <Literal> element allows specifying constant values of numeric, boolean, string, date or geometry type. Rules contain Symbolizers to specify how features are styled. There are 5 types of symbolizers: • PointSymbolizer, which styles features as points • LineSymbolizer, which styles features as lines • PolygonSymbolizer, which styles features as polygons • TextSymbolizer, which styles text labels for features 344 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 • RasterSymbolizer, which styles raster coverages Each symbolizer type has its own parameters to control styling. PointSymbolizer A PointSymbolizer styles features as points. Points are depicted as graphic symbols at a single location on the map. Syntax A <PointSymbolizer> contains an optional <Geometry> element, and a required <Graphic> element specifying the point symbology. Tag <Geometry> <Graphic> Required? No Yes Description Specifies the geometry to be rendered. Specifies the styling for the point symbol. Geometry The <Geometry> element is optional. If present, it specifies the featuretype property from which to obtain the geometry to style using a <PropertyName> element. See also Geometry transformations in SLD for GeoServer extensions for specifying geometry. Any kind of geometry may be styled with a <PointSymbolizer>. For non-point geometries, a representative point is used (such as the centroid of a line or polygon). Graphic Symbology is specified using a <Graphic> element. The symbol is specified by either an <ExternalGraphic> or a <Mark> element. External Graphics are image files (in a format such as PNG or SVG) that contain the shape and color information defining how to render a symbol. Marks are vector shapes whose stroke and fill are defined explicitly in the symbolizer. There are five possible sub-elements of the <Graphic> element. One of <ExternalGraphic> or <Mark> must be specified; the others are optional. 6.2. SLD Styling 345 GeoServer User Manual, Release 2.15.1 Tag Required? Description <ExternalGraphic> No (when using Specifies an external image file to use as the symbol. <Mark>) <Mark> No (when using Specifies a named shape to use as the symbol. <ExternalGraphic>) <Opacity> No Specifies the opacity (transparency) of the symbol. Values range from 0 (completely transparent) to 1 (completely opaque). Value may contain expressions. Default is 1 (opaque). <Size> No Specifies the size of the symbol, in pixels. When used with an image file, this specifies the height of the image, with the width being scaled accordingly. if omitted the native symbol size is used. Value may contain expressions. <Rotation> No Specifies the rotation of the symbol about its center point, in decimal degrees. Positive values indicate rotation in the clockwise direction, negative values indicate counterclockwise rotation. Value may contain expressions. Default is 0. ExternalGraphic External Graphics are image files (in formats such as PNG or SVG) that contain the shape and color information defining how to render a symbol. For GeoServer extensions for specifying external graphics, see Graphic symbology in GeoServer. The <ExternalGraphic> element has the sub-elements: Tag Required? <OnlineResource>Yes <Format> Yes Description The xlink:href attribute specifies the location of the image file. The value can be either a URL or a local pathname relative to the SLD directory. The value can contain CQL expressions delimited by ${ }. The attribute xlink:type="simple" is also required. The element does not contain any content. The MIME type of the image format. Most standard web image formats are supported. Common MIME types are image/png, image/jpeg, image/gif, and image/ svg+xml Mark Marks are predefined vector shapes identified by a well-known name. Their fill and stroke can be defined explicitly in the SLD. For GeoServer extensions for specifying mark symbols, see Graphic symbology in GeoServer. The <Mark> element has the sub-elements: 346 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Tag Required? <WellKnownName> No <Fill> No <Stroke> No Description The name of the shape. Standard SLD shapes are circle, square, triangle, star, cross, or x. Default is square. Specifies how the symbol should be filled (for closed shapes). Options are to use <CssParameter name="fill"> to specify a solid fill color, or using <GraphicFill> for a tiled graphic fill. See the PolygonSymbolizer Fill for the full syntax. Specifies how the symbol linework should be drawn. Some options are using <CssParameter name="stroke"> to specify a stroke color, or using <GraphicStroke> for a repeated graphic. See the LineSymbolizer Stroke for the full syntax. Example The following symbolizer is taken from the Points section in the SLD Cookbook. 1 2 3 4 5 6 7 8 9 10 11 <PointSymbolizer> <Graphic> <Mark> <WellKnownName>circle</WellKnownName> <Fill> <CssParameter name="fill">#FF0000</CssParameter> </Fill> </Mark> <Size>6</Size> </Graphic> </PointSymbolizer> The symbolizer contains the required <Graphic> element. Inside this element is the <Mark> element and <Size> element, which are the minimum required element inside <Graphic> (when not using the <ExternalGraphic> element). The <Mark> element contains the <WellKnownName> element and a <Fill> element. No other element are required. In summary, this example specifies the following: 1. Features will be rendered as points 2. Points will be rendered as circles 3. Circles will be rendered with a diameter of 6 pixels and filled with the color red The next example uses an external graphic loaded from the file system: 1 2 3 4 5 6 7 8 9 <PointSymbolizer> <Graphic> <ExternalGraphic> <OnlineResource xlink:type="simple" xlink:href="file:///var/www/htdocs/sun.png" /> <Format>image.png</Format> </ExternalGraphic> </Graphic> </PointSymbolizer> For file:// URLs, the file must be readable by the user the GeoServer process is running as. You can also use href:// URLs to reference remote graphics. Further examples can be found in the Points section of the SLD Cookbook. 6.2. SLD Styling 347 GeoServer User Manual, Release 2.15.1 Using expressions in parameter values Many SLD parameters allow their values to be of mixed type. This means that the element content can be: • a constant value expressed as a string • a filter expression • any combination of strings and filter expressions. Using expressions in parameter values provides the ability to determine styling dynamically on a perfeature basis, by computing parameter values from feature properties. Using computed parameters is an alternative to using rules in some situations, and may provide a more compact SLD document. GeoServer also supports using substitution variables provided in WMS requests. This is described in Variable substitution in SLD. LineSymbolizer A LineSymbolizer styles features as lines. Lines are one-dimensional geometries that have both position and length. Each line is comprised of one or more line segments, and has either two ends or none (if it is closed). Syntax A <LineSymbolizer> contains an optional <Geometry> element, and a required <Stroke> element specifying the line symbology. Tag Required? <Geometry> No <Stroke> Yes <PerpendicularOffset> No Description Specifies the geometry to be rendered. Specifies the styling for the line. Specifies the perpendicular offset for the current line Geometry The <Geometry> element is optional. If present, it specifies the featuretype property from which to obtain the geometry to style using the PropertyName element. See also Geometry transformations in SLD for GeoServer extensions for specifying geometry. Any kind of geometry may be styled with a <LineSymbolizer>. Point geometries are treated as lines of zero length, with a horizontal orientation. For polygonal geometries the boundary (or boundaries) are used as the lines, each line being a closed ring with no ends. Stroke The <Stroke> element specifies the styling of a line. There are three elements that can be included inside the <Stroke> element. Tag <GraphicFill> <GraphicStroke> <CssParameter> 348 Required? No No 0..N Description Renders the pixels of the line with a repeated pattern. Renders the line with a repeated linear graphic. Determines the stroke styling parameters. Chapter 6. Styling GeoServer User Manual, Release 2.15.1 GraphicFill The <GraphicFill> element specifies that the pixels of the line are to be filled with a repeating graphic image or symbol. The graphic is specified by a <Graphic> sub-element, which is described in the PointSymbolizer Graphic section. GraphicStroke The <GraphicStroke> element specifies the the line is to be drawn using a repeated graphic image or symbol following the line. The graphic is specified by a <Graphic> sub-element, which is described in the PointSymbolizer Graphic section. The spacing of the graphic symbol can be specified using the <Size> element in the <Graphic> element, or the <CSSParameter name="stroke-dasharray"> in the Stroke element. CssParameter The <CssParameter> elements describe the basic styling of the line. Any number of <CssParameter> elements can be specified. The name attribute indicates what aspect of styling an element specifies, using the standard CSS/SVG styling model. The content of the element supplies the value of the styling parameter. The value may contain expressions. The following parameters are supported: Parameter name="stroke" Required? No name="stroke-width" name="stroke-opacity" No No name="stroke-linejoin" No name="stroke-linecap" No name="stroke-dasharray" No name="stroke-dashoffset"No 6.2. SLD Styling Description Specifies the solid color given to the line, in the form #RRGGBB. Default is black (#000000). Specifies the width of the line in pixels. Default is 1. Specifies the opacity (transparency) of the line. The value is a number are between 0 (completely transparent) and 1 (completely opaque). Default is 1. Determines how lines are rendered at intersections of line segments. Possible values are mitre (sharp corner), round (rounded corner), and bevel (diagonal corner). Default is mitre. Determines how lines are rendered at their ends. Possible values are butt (sharp square edge), round (rounded edge), and square (slightly elongated square edge). Default is butt. Encodes a dash pattern as a series of numbers separated by spaces. Odd-indexed numbers (first, third, etc) determine the length in pxiels to draw the line, and even-indexed numbers (second, fourth, etc) determine the length in pixels to blank out the line. Default is an unbroken line. Starting from version 2.1 dash arrays can be combined with graphic strokes to generate complex line styles with alternating symbols or a mix of lines and symbols. Specifies the distance in pixels into the dasharray pattern at which to start drawing. Default is 0. 349 GeoServer User Manual, Release 2.15.1 PerpendicularOffset The <PerpendicularOffset> element is optional. It is native to the SE 1.1 specification, but supported also in SLD 1.0 as a vendor extension. If present, it makes the renderer draw a line parallel to the original one, at the given distance. When applied on lines, positive values generate a parallel line on the left hand side, negative values on the right hand side. When applied on polygons instead, positive is interpreted as outwards, negative as inwards. As most properties, <PerpendicularOffset> accepts expressions. Care should be taken when using it, as it might become a performance bottleneck. When offsetting lines a fast offset algorithm is used, which works well at small distances, but can generate visible artifacts at higher values. When working against polygons the fast offset line algorithm is used up to 3 pixels away from the original geometry, after that a full buffer algorithm is used instead, which always provides correct results, but is significantly more expensive. Basic Example The following symbolizer is taken from the Lines section in the SLD Cookbook. <LineSymbolizer> <Stroke> <CssParameter name="stroke">#0000FF</CssParameter> <CssParameter name="stroke-width">3</CssParameter> <CssParameter name="stroke-dasharray">5 2</CssParameter> </Stroke> </LineSymbolizer> 1 2 3 4 5 6 7 The symbolizer styles a feature as a dashed blue line of width 3 pixels. Fig. 6.70: Dashed blue line 350 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Offsetting lines The following style excerpt generates a solid line, and then a dashed blue line 3 pixels on the left of it. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <LineSymbolizer> <Stroke> <CssParameter name="stroke">#000000</CssParameter> <CssParameter name="stroke-width">2</CssParameter> </Stroke> </LineSymbolizer> <LineSymbolizer> <Stroke> <CssParameter name="stroke">#0000FF</CssParameter> <CssParameter name="stroke-width">3</CssParameter> <CssParameter name="stroke-dasharray">5 2</CssParameter> </Stroke> <PerpendicularOffset>3</PerpendicularOffset> </LineSymbolizer> Fig. 6.71: Left offset dashed line 6.2. SLD Styling 351 GeoServer User Manual, Release 2.15.1 Offsetting polygons The following style excerpt builds a inward offset line for polygons. <PolygonSymbolizer> <Stroke> <CssParameter name="stroke">#000000</CssParameter> <CssParameter name="stroke-width">2</CssParameter> </Stroke> </PolygonSymbolizer> <LineSymbolizer> <Stroke> <CssParameter name="stroke">#AAAAAA</CssParameter> <CssParameter name="stroke-width">3</CssParameter> </Stroke> <PerpendicularOffset>-2</PerpendicularOffset> </LineSymbolizer> 1 2 3 4 5 6 7 8 9 10 11 12 13 Fig. 6.72: Inwards offset line PolygonSymbolizer A PolygonSymbolizer styles features as polygons. Polygons are two-dimensional geometries. They can be depicted with styling for their interior (fill) and their border (stroke). Polygons may contain one or more holes, which are stroked but not filled. When rendering a polygon, the fill is rendered before the border is stroked. Syntax A <PolygonSymbolizer> contains an optional <Geometry> element, and two elements <Fill> and <Stroke> for specifying styling: 352 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Tag <Geometry> <Fill> <Stroke> Required? No No No Description Specifies the geometry to be rendered. Specifies the styling for the polygon interior. Specifies the styling for the polygon border. Geometry The <Geometry> element is optional. If present, it specifies the featuretype property from which to obtain the geometry to style using the PropertyName element. See also Geometry transformations in SLD for GeoServer extensions for specifying geometry. Any kind of geometry may be styled with a <PolygonSymbolizer>. Point geometries are treated as small orthonormal square polygons. Linear geometries are closed by joining their ends. Stroke The <Stroke> element specifies the styling for the border of a polygon. The syntax is described in the <LineSymbolizer> Stroke section. Fill The <Fill> element specifies the styling for the interior of a polygon. It can contain the sub-elements: Tag Required? <GraphicFill> No <CssParameter> 0..N Description Renders the fill of the polygon with a repeated pattern. Specifies parameters for filling with a solid color. GraphicFill The <GraphicFill> element contains a <Graphic> element, which specifies a graphic image or symbol to use for a repeated fill pattern. The syntax is described in the PointSymbolizer Graphic section. CssParameter The <CssParameter> elements describe the styling of a solid polygon fill. <CssParameter> elements can be specified. Any number of The name attribute indicates what aspect of styling an element specifies, using the standard CSS/SVG styling model. The content of the element supplies the value of the styling parameter. The value may contain expressions. The following parameters are supported: Parameter name="fill" Required? No name="fill-opacity" No 6.2. SLD Styling Description Specifies the fill color, in the form #RRGGBB. Default is grey (#808080). Specifies the opacity (transparency) of the fill. The value is a decimal number between 0 (completely transparent) and 1 (completely opaque). Default is 1. 353 GeoServer User Manual, Release 2.15.1 Example The following symbolizer is taken from the Polygons section in the SLD Cookbook. <PolygonSymbolizer> <Fill> <CssParameter name="fill">#000080</CssParameter> </Fill> </PolygonSymbolizer> 1 2 3 4 5 This symbolizer contains only a <Fill> element. Inside this element is a <CssParameter> that specifies the fill color for the polygon to be #000080 (a muted blue). Further examples can be found in the Polygons section of the SLD Cookbook. TextSymbolizer A TextSymbolizer styles features as text labels. Text labels are positioned eoither at points or along linear paths derived from the geometry being labelled. Labelling is a complex operation, and effective labelling is crucial to obtaining legible and visually pleasing cartographic output. For this reason SLD provides many options to control label placement. To improve quality even more GeoServer provides additional options and parameters. The usage of the standard and extended options are described in greater detail in the following section on Labeling. Syntax A <TextSymbolizer> contains the following elements: Tag Required? <Geometry> No <Label> No <Font> No <LabelPlacement>No <Halo> No <Fill> <Graphic> No No <Priority> No <VendorOption> 0..N Description The geometry to be labelled. The text content for the label. The font information for the label. Sets the position of the label relative to its associated geometry. Creates a colored background around the label text, for improved legibility. The fill style of the label text. A graphic to be displayed behind the label text. See Graphic for content syntax. The priority of the label during conflict resolution. Content may contains expressions. See also Priority Labeling. A GeoServer-specific option. See Labeling for descriptions of the available options. Any number of options may be specified. Geometry The <Geometry> element is optional. If present, it specifies the featuretype property from which to obtain the geometry to label, using a <PropertyName> element. See also Geometry transformations in SLD for GeoServer extensions for specifying geometry. 354 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Any kind of geometry may be labelled with a <TextSymbolizer>. For non-point geometries, a representative point is used (such as the centroid of a line or polygon). Label The <Label> element specifies the text that will be rendered as the label. It allows content of mixed type, which means that the content can be a mixture of string data and Filter Expressions. These are concatenated to form the final label text. If a label is provided directly by a feature property, the content is a single <PropertyName>. Multiple properties can be included in the label, and property values can be manipulated by filter expressions and functions. Additional “boilerplate” text can be provided as well. Whitespace can be preserved by surrounding it with XML <![CDATA[ ]]> delimiters. If this element is omitted, no label is rendered. Font The <Font> element specifes the font to be used for the label. A set of <CssParameter> elements specify the details of the font. The name attribute indicates what aspect of the font is described, using the standard CSS/SVG font model. The content of the element supplies the value of the font parameter. The value may contain expressions. Parameter name="font-family" Required? No name="font-style" No name="font-weight" No name="font-size" No Description The family name of the font to use for the label. Default is Times. The style of the font. Options are normal, italic, and oblique. Default is normal. The weight of the font. Options are normal and bold. Default is normal. The size of the font in pixels. Default is 10. LabelPlacement The <LabelPlacement> element specifies the placement of the label relative to the geometry being labelled. There are two possible sub-elements: <PointPlacement> or <LinePlacement>. Exactly one of these must be specified. Tag Required? <PointPlacement>No <LinePlacement> No Description Labels a geometry at a single point Labels a geometry along a linear path PointPlacement The <PointPlacement> element indicates the label is placed at a labelling point derived from the geometry being labelled. The position of the label relative to the labelling point may be controlled by the following sub-elements: 6.2. SLD Styling 355 GeoServer User Manual, Release 2.15.1 Tag <AnchorPoint> Required? No <Displacement> No <Rotation> No Description The location within the label bounding box that is aligned with the label point. The location is specified by <AnchorPointX> and <AnchorPointY> sub-elements, with values in the range [0..1]. Values may contain expressions. Specifies that the label point should be offset from the original point. The offset is specified by <DisplacementX> and <DisplacementY> sub-elements, with values in pixels. Values may contain expressions. Default is (0, 0). The rotation of the label in clockwise degrees (negative values are counterclockwise). Value may contain expressions. Default is 0. The anchor point justification, displacement offsetting, and rotation are applied in that order. LinePlacement The <LinePlacement> element indicates the label is placed along a linear path derived from the geometry being labelled. The position of the label relative to the linear path may be controlled by the following subelement: Tag Required? <PerpendicularOffset> No Description The offset from the linear path, in pixels. Positive values offset to the left of the line, negative to the right. Value may contain expressions. Default is 0. The appearance of text along linear paths can be further controlled by the vendor options followLine, maxDisplacement, repeat, labelAllGroup, and maxAngleDelta. These are described in Labeling. Halo A halo creates a colored background around the label text, which improves readability in low contrast situations. Within the <Halo> element there are two sub-elements which control the appearance of the halo: Tag <Radius> Required? No <Fill> No Description The halo radius, in pixels. Value may contain expressions. Default is 1. The color and opacity of the halo via CssParameter elements for fill and fill-opacity. See Fill for full syntax. The parameter values may contain expressions. Default is a white fill (#FFFFFF) at 100% opacity. Fill The <Fill> element specifies the fill style for the label text. The syntax is the same as that of the PolygonSymbolizer Fill element. The default fill color is black (#FFFFFF) at 100% opacity.. 356 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Graphic The <Graphic> element specifies a graphic symbol to be displayed behind the label text (if any). A classic use for this is to display “highway shields” behind road numbers provided by feature attributes. The element content has the same syntax as the <PointSymbolizer> Graphic element. Graphics can be provided by internal mark symbols, or by external images or SVG files. Their size and aspect ratio can be changed to match the text displayed with them by using the vendor options graphic-resize and graphic-margin. Example The following symbolizer is taken from the Points section in the SLD Cookbook. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <TextSymbolizer> <Label> <ogc:PropertyName>name</ogc:PropertyName> </Label> <Font> <CssParameter name="font-family">Arial</CssParameter> <CssParameter name="font-size">12</CssParameter> <CssParameter name="font-style">normal</CssParameter> <CssParameter name="font-weight">bold</CssParameter> </Font> <LabelPlacement> <PointPlacement> <AnchorPoint> <AnchorPointX>0.5</AnchorPointX> <AnchorPointY>0.0</AnchorPointY> </AnchorPoint> <Displacement> <DisplacementX>0</DisplacementX> <DisplacementY>25</DisplacementY> </Displacement> <Rotation>-45</Rotation> </PointPlacement> </LabelPlacement> <Fill> <CssParameter name="fill">#990099</CssParameter> </Fill> </TextSymbolizer> The symbolizer labels features with the text from the name property. The font is Arial in bold at 12 pt size, filled in purple. The labels are centered on the point along their lower edge, then displaced 25 pixels upwards, and finally rotated 45 degrees counterclockwise. The displacement takes effect before the rotation during rendering, so the 25 pixel vertical displacement is itself rotated 45 degrees. Scalable Font Size The font size can also be set depending on the scale denominator as follows: 1 2 3 4 <CssParameter name="font-size"> <ogc:Function name="Categorize"> <!-- Value to transform --> <ogc:Function name="env"> 6.2. SLD Styling 357 GeoServer User Manual, Release 2.15.1 Fig. 6.73: Point with rotated label <ogc:Literal>wms_scale_denominator</ogc:Literal> </ogc:Function> <!-- Output values and thresholds --> <!-- Ranges: --> <!-- [scale <= 300, font 12] --> <!-- [scale 300 - 2500, font 10] --> <!-- [scale > 2500, font 8] --> <ogc:Literal>12</ogc:Literal> <ogc:Literal>300</ogc:Literal> <ogc:Literal>10</ogc:Literal> <ogc:Literal>2500</ogc:Literal> <ogc:Literal>8</ogc:Literal> </ogc:Function> </CssParameter> 5 6 7 8 9 10 11 12 13 14 15 16 17 18 The above example would display text at different sizes depending on the scale denominator setting. A font size of 12 for scale denominator of less than or equal to 300, a font size of 10 for scale denominator from 300-2500 and a font size of 8 for scale denominator greater than 2500. Labeling This section discusses the details of controlling label placement via the standard SLD options. It also describes a number of GeoServer enhanced options for label placement that provide better cartographic output. LabelPlacement The SLD specification defines two alternative label placement strategies which can be used in the <LabelPlacement> element: • <PointPlacement> places labels at a single point • <LinePlacement> places labels along a line 358 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 PointPlacement When <PointPlacement> is used the geometry is labelled at a single label point. For lines, this point lies at the middle of the visible portion of the line. For polygons, the point is the centroid of the visible portion of the polygon. The position of the label relative to the label point can be controlled by the following sub-elements: Element <AnchorPoint> <Displacement> <Rotation> Description Determines the placement of the label relative to the label point. Values given as decimals between 0-1. Offsets the label from the anchor point. Values given in pixels. Rotates the label clockwise by a given number of degrees. The best way to explain these options is with examples. AnchorPoint The anchor point determines where the label is placed relative to the label point. <AnchorPoint> <AnchorPointX> 0.5 </AnchorPointX> <AnchorPointY> 0.5 </AnchorPointY> </AnchorPoint> The anchor point values—listed here as (X, Y) ordered pairs—are specified relative to the bounding box of the label, with values from 0 to 1 inclusive. For example: • (Default) Bottom left of the box is (0, 0) • Top right is (1, 1) • Center is (0.5, 0.5) So to have the anchor location centered just below the label (label top-centered), use (0.5, 0): <AnchorPoint> <AnchorPointX> 0.5 </AnchorPointX> <AnchorPointY> 0 </AnchorPointY> </AnchorPoint> The following examples show how changing the anchor point affects the position of labels: 6.2. SLD Styling 359 GeoServer User Manual, Release 2.15.1 Fig. 6.74: (0, 0.5) places the label to the right of the label point Fig. 6.75: (0.5, 0.5) places the center of the label at the label point Displacement Displacement allows fine control of the placement of the label. The displacement values offset the location of the label from the anchor point by a specified number of pixels. The element syntax is: <Displacement> <DisplacementX> 10 </DisplacementX> <DisplacementY> 0 </DisplacementY> </Displacement> Examples: Displacement of X=10 pixels (compare with default anchor point of (X=0, Y=0.5) shown above) Displacement of Y=-10 pixels (compare with anchor point (X= 0.5, Y=1.0) - not shown) Rotation The optional <Rotation> element specifies that labels should be rotated clockwise by a given number of degrees <Rotation> 45 </Rotation> The examples below show how the rotation interacts with anchor points and displacements. 45 degree rotation 45 degree rotation with anchor point (X=0.5, Y=0.5) Fig. 6.76: (1, 0.5) places the label to the left of the label point 360 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.77: (0.5, 0) places the label horizontally centered above the label point 6.2. SLD Styling 361 GeoServer User Manual, Release 2.15.1 45 degree rotation with 40-pixel X displacement 45 degree rotation with 40-pixel Y displacement with anchor point (X=0.5, Y=0.5) LinePlacement To label linear features (such as a road or river), the <LinePlacement> element can be specified. This indicates that the styler should determine the best placement and rotation for the labels along the lines. The standard SLD LinePlacement element provides one optional sub-element, <PerpendicularOffset>. GeoServer provides much more control over line label placement via vendor-specific options; see below for details. PerpendicularOffset The optional <PerpendicularOffset> element allows you to position a label above or below a line. (This is similiar to the <DisplacementY> for label points described above.) The displacement value is specified in pixels. A positive value displaces upwards, a negative value downwards. <LabelPlacement> <LinePlacement> <PerpendicularOffset> 10 </PerpendicularOffset> </LinePlacement> </LabelPlacement> Examples: PerpendicularOffset = 0 (default) PerpendicularOffset = 10 362 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Composing labels from multiple attributes The <Label> element in <TextSymbolizer> allows mixed content. This means its content can be a mixture of plain text and Filter Expressions. The mix gets interepreted as a concatenation. You can leverage this to create complex labels out of multiple attributes. For example, if you want both a state name and its abbreviation to appear in a label, you can do the following: <Label> <ogc:PropertyName>STATE_NAME</ogc:PropertyName> (<ogc:PropertyName>STATE_ABBR</ ,→ogc:PropertyName>) </Label> and you’ll get a label looking like Texas (TX). If you need to add extra white space or newline, you’ll stumble into an XML oddity. The whitespace handling in the Label element is following a XML rule called “collapse”, in which all leading and trailing whitespaces have to be removed, whilst all whitespaces (and newlines) in the middle of the xml element are collapsed into a single whitespace. So, what if you need to insert a newline or a sequence of two or more spaces between your property names? Enter CDATA. CDATA is a special XML section that has to be returned to the interpreter as-is, without following any whitespace handling rule. So, for example, if you wanted to have the state abbreviation sitting on the next line you’d use the following: <Label> <ogc:PropertyName>STATE_NAME</ogc:PropertyName><![CDATA[ ]]>(<ogc:PropertyName>STATE_ABBR</ogc:PropertyName>) </Label> GeoServer Enhanced Options GeoServer provides a number of label styling options as extensions to the SLD specification. Using these options gives more control over how the map looks, since the SLD standard isn’t expressive enough to provide all the options one might want. These options are specified as subelements of <TextSymbolizer>. 6.2. SLD Styling 363 GeoServer User Manual, Release 2.15.1 Priority Labeling The optional <Priority> element allows specifying label priority. This controls how conflicts (overlaps) between labels are resolved during rendering. The element content may be an expression to retrieve or calculate a relative priority value for each feature in a layer. Alternatively, the content may be a constant value, to set the priority of a layer’s labels relative to other layers on a rendered map. The default priority for labels is 1000. Note: Standard SLD Conflict Resolution If the <Priority> element is not present, or if a group of labels all have the same priority, then standard SLD label conflict resolution is used. Under this strategy, the label to display out of a group of conflicting labels is chosen essentially at random. For example, take the following dataset of cities: City Name | population ------------+-----------Yonkers | 197,818 Jersey City | 237,681 Newark | 280,123 New York | 8,107,916 City locations (large scale map) More people know where New York City is than where Jersey City is. Thus we want to give the label “New York” priority so it will be visible when in conflict with (overlapping) “Jersey City”. To do this we include the following code in the <TextSymbolizer>: <Priority> <ogc:PropertyName>population</ogc:PropertyName> </Priority> This ensures that at small scales New York is labeled in preference to the less populous cities nearby: City locations (small scale map) Without priority labeling, Jersey City could be labeled in preference to New York, making it difficult to interpret the map. At scales showing many features, priority labeling is essential to ensure that larger cities are more visible than smaller cities. 364 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Grouping Features (group) The group option allows displaying a single label for multiple features in a logical group. <VendorOption name="group">yes</VendorOption> Grouping works by collecting all features with the same label text, then choosing a representative geometry for the group, according to the following rules: Geometry Point Set Line Set Polygon Set Label Point The first point inside the view rectangle is used. Lines are joined together, clipped to the view rectangle, and the longest path is used. Polygons are clipped to the view rectangle, and the largest polygon is used. If desired the labeller can be forced to label every element in a group by specifying the labelAllGroup option. Warning: Be careful that the labels truly indicate features that should be grouped together. For example, grouping on city name alone might end up creating a group containing both Paris (France) and Paris (Texas). Road data is a classic example to show why grouping is useful. It is usually desirable to display only a single label for all of “Main Street”, not a label for every block of “Main Street.” When the group option is off (the default), grouping is not performed and every block feature is labeled (subject to label deconfliction): 6.2. SLD Styling 365 GeoServer User Manual, Release 2.15.1 When the group option is used, geometries with the same label are grouped together and the label position is determined from the entire group. This produces a much less cluttered map: labelAllGroup The labelAllGroup option can be used in conjunction with the group option (see Grouping Features (group)). It causes all of the disjoint paths in a line group to be labeled, not just the longest one. <VendorOption name="labelAllGroup">true</VendorOption> Overlapping and Separating Labels (spaceAround) By default GeoServer will not render labels “on top of each other”. By using the spaceAround option you can either allow labels to overlap, or add extra space around labels. The value supplied for the option is a positive or negative size, in pixels. <VendorOption name="spaceAround">10</VendorOption> Using the default value of 0, the bounding box of a label cannot overlap the bounding box of another label: With a negative spaceAround value, overlapping is allowed: With a positive spaceAround value of 10, each label is at least 20 pixels apart from others: Positive spaceAround values actually provide twice the space that you might expect. This is because you can specify a spaceAround for one label as 5, and for another label (in another TextSymbolizer) as 3. The 366 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 total distance between them is 8. Two labels in the first symbolizer (“5”) will each be 5 pixels apart from each other, for a total of 10 pixels. Note: Interaction between values in different TextSymbolizers You can have multiple TextSymbolizers in your SLD file, each with a different spaceAround option. If all the spaceAround options are >=0, this will do what you would normally expect. If you have negative values (‘allow overlap’) then these labels can overlap labels that you’ve said should not be overlapping. If you don’t like this behavior, it’s not difficult to change - feel free to submit a patch! followLine The followLine option forces a label to follow the curve of the line. To use this option add the following to the <TextSymbolizer>. Note: Straight Lines You don’t need to use followLine for straight lines. GeoServer will automatically follow the orientation of the line. However in this case followLine can be used to ensure the text isn’t rendered if longer than the line. <VendorOption name="followLine">true</VendorOption> It is required to use <LinePlacement> along with this option to ensure that labels are placed along lines: 6.2. SLD Styling 367 GeoServer User Manual, Release 2.15.1 <LabelPlacement> <LinePlacement/> </LabelPlacement> maxDisplacement The maxDisplacement option controls the displacement of the label along a line, around a point and inside a polygon. For lines, normally GeoServer labels a line at its center point only. If this label conflicts with another one it may not be displayed at all. When this option is enabled the labeller will attempt to avoid conflic by using an alternate location within maxDisplacement pixels along the line from the pre-computed label point. If used in conjunction with repeat, the value for maxDisplacement should always be lower than the value for repeat. For points this causes the renderer to start circling around the point in search of a empty stop to place the label, step by step increasing the size of the circle until the max displacement is reached. The same happens for polygons, around the polygon labelling point (normally the centroid). <VendorOption name="maxDisplacement">10</VendorOption> repeat The repeat option determines how often GeoServer displays labels along a line. Normally GeoServer labels each line only once, regardless of length. Specifying a positive value for this option makes the labeller attempt to draw the label every repeat pixels. For long or complex lines (such as contour lines) this makes labeling more informative. <VendorOption name="repeat">100</VendorOption> maxAngleDelta When used in conjunction with followLine, the maxAngleDelta option sets the maximum angle, in degrees, between two subsequent characters in a curved label. Large angles create either visually disconnected words or overlapping characters. It is advised not to use angles larger than 30. <VendorOption name="maxAngleDelta">15</VendorOption> autoWrap The autoWrap option wraps labels when they exceed the given width (in pixels). The size should be wide enough to accommodate the longest word, otherwise single words will be split over multiple lines. <VendorOption name="autoWrap">50</VendorOption> Labeling with autoWrap enabled 368 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 forceLeftToRight The renderer tries to draw labels along lines so that the text is upright, for maximum legibility. This means a label may not follow the line orientation, but instead may be rotated 180° to display the text the right way up. In some cases altering the orientation of the label is not desired; for example, if the label is a directional arrow showing the orientation of the line. The forceLeftToRight option can be set to false to disable label flipping, making the label always follow the inherent orientation of the line being labelled: <VendorOption name="forceLeftToRight">false</VendorOption> conflictResolution By default labels are subject to conflict resolution, meaning the renderer will not allow any label to overlap with a label that has been already drawn. Setting the conflictResolution option to false causes this label to bypass conflict resolution. This means the label will be drawn even if it overlaps with other labels, and other labels drawn after it may overlap it. <VendorOption name="conflictResolution">false</VendorOption> goodnessOfFit GeoServer will remove labels if they are a particularly bad fit for the geometry they are labeling. Geometry Point Line Polygon Goodness of Fit Algorithm Always returns 1.0 since the label is at the point Always returns 1.0 since the label is always placed on the line. The label is sampled approximately at every letter. The distance from these points to the polygon is determined and each sample votes based on how close it is to the polygon. (see LabelCacheDefault#goodnessOfFit()) The default value is 0.5, but it can be modified using: 6.2. SLD Styling 369 GeoServer User Manual, Release 2.15.1 <VendorOption name="goodnessOfFit">0.3</VendorOption> polygonAlign GeoServer normally tries to place labels horizontally within a polygon, and gives up if the label position is busy or if the label does not fit enough in the polygon. This option allows GeoServer to try alternate rotations for the labels. <VendorOption name="polygonAlign">mbr</VendorOption> Option manual ortho mbr Description The default value. Only a rotation manually specified in the <Rotation> tag will be used If the label does not fit horizontally and the polygon is taller than wider then vertical alignment will also be tried If the label does not fit horizontally the minimum bounding rectangle will be computed and a label aligned to it will be tried out as well graphic-resize When a <Graphic> is specified for a label by default it is displayed at its native size and aspect ratio. The graphic-resize option instructs the renderer to magnify or stretch the graphic to fully contain the text of the label. If this option is used the graphic-margin option may also be specified. <VendorOption name="graphic-resize">stretch</VendorOption> Option none proportional stretch Description Graphic is displayed at its native size (default) Graphic size is increased uniformly to contain the label text Graphic size is increased anisotropically to contain the label text Labeling with a Graphic Mark “square” - L) at native size; R) with “graphic-resize”=stretch and “graphic-margin”=3 graphic-margin The graphic-margin options specifies a margin (in pixels) to use around the label text when the graphic-resize option is specified. 370 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 <VendorOption name="graphic-margin">margin</VendorOption> partials The partials options instructs the renderer to render labels that cross the map extent, which are normally not painted since there is no guarantee that a map put on the side of the current one (tiled rendering) will contain the other half of the label. By enabling “partials” the style editor takes responsibility for the other half being there (maybe because the label points have been placed by hand and are assured not to conflict with each other, at all zoom levels). <VendorOption name="partials">true</VendorOption> underlineText The underlineText option instruct the renderer to underline labels. The underline will work like a typical word processor text underline. The thickness and position of the underline will be defined by the font and color will be the same as the text. Spaces will also be underlined. <VendorOption name="underlineText">true</VendorOption> Some underlines examples: strikethroughText The strikethroughText option instruct the renderer to strikethrough labels. The strikethrough will work like a typical word processor text strikethrough. The thickness and position of the line will be defined by the font and color will be the same as the text. Spaces will also be stroken. <VendorOption name="strikethroughText">true</VendorOption> Some strikethrough examples: charSpacing The charSpacing option controls the amount of space between characters, a positive value increases it, a negative value shrinks it (and will eventually make characters overlap). The value is specified in pixels. 6.2. SLD Styling 371 GeoServer User Manual, Release 2.15.1 372 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 <VendorOption name="charSpacing">3</VendorOption> Example of adding 3 extra pixels of space between chars on road names: wordSpacing The wordSpacing option controls the amount of space between words, for this option only positive values (or zero) are accepted. The value is specified in pixels. <VendorOption name="wordSpacing">5</VendorOption> Example of adding 5 extra pixels of space between words on road names: displacementMode Comma separated list of label displacement directions for point/polygon labels (used along with maxDisplacement). The indicated directions will be tried in turn. Valid values are cardinal directions abbreviations, in particular, N, W, E, S, NW, NE, SW, SE. The following example sets the typical “diagonal displacement” typically used for points: <VendorOption name="displacementMode">NE, NW, SW, SE</VendorOption> While this one allows displacement only in the vertical direction: <VendorOption name="displacementMode">N, S</VendorOption> RasterSymbolizer GeoServer supports the ability to display raster data in addition to vector data. Raster data is not merely a picture, rather it can be thought of as a grid of georeferenced information, much like a graphic is a grid of visual information (with combination of reds, greens, and blues). Unlike graphics, 6.2. SLD Styling 373 GeoServer User Manual, Release 2.15.1 which only contain visual data, each point/pixel in a raster grid can have many different attributes (bands), with possibly none of them having an inherently visual component. With the above in mind, one needs to choose how to visualize the data, and this, like in all other cases, is done by using an SLD. The analogy to vector data is evident in the naming of the tags used. Vectors, consisting of points, line, and polygons, are styled by using the <PointSymbolizer>, <LineSymbolizer>, and <PolygonSymbolizer> tags. It is therefore not very surprising that raster data is styled with the tag <RasterSymbolizer>. Syntax The following elements can be used inside the <RasterSymbolizer> element. • <Opacity> • <ColorMap> • <ChannelSelection> • <ContrastEnhancement> • <ShadedRelief> * • <OverlapBehavior> * • <ImageOutline> * Warning: The starred (*) elements are not yet implemented in GeoServer. Opacity The <Opacity> element sets the transparency level for the entire rendered image. As is standard, the values range from zero (0) to one (1), with zero being transparent, and one being opaque. The syntax is: <Opacity>0.5</Opacity> where, in this case, the raster is rendered at 50% opacity. ColorMap The <ColorMap> element defines the color values for the pixels of a raster image, as either color gradients, or a mapping of specific values to fixed colors. A color map is defined by a sequence of <ColorMapEntry> elements. Each <ColorMapEntry> element specifies a color and a quantity attribute. The quantity refers to the value of a raster pixel. The color value is denoted in standard hexadecimal RGB format (#RRGGBB). <ColorMapEntry> elements can also have opacity and label attributes. The opacity attribute overrides the global <Opacity> value. The label attribute is used to provide text for legends. A color map can contain up to 255 <ColorMapEntry> elements. The simplest <ColorMap> has two color map entries. One specifyies a color for the “bottom” of the dataset, and the other specifyies a color for the “top” of the dataset. Pixels with values equal to or less than the minimum value are rendered with the bottom color (and opacity). Pixels with values equal to or great than the maximum value are rendered with the top color and opacity. The colors for values in between are automatically interpolated, making creating color gradients easy. 374 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 A color map can be refined by adding additional intermediate entries. This is useful if the dataset has discrete values rather than a gradient, or if a multi-colored gradient is desired. One entry is added for each different color to be used, along with the corresponding quantity value. For example, a simple ColorMap can define a color gradient from color #323232 to color #BBBBBB over quantity values from -300 to 200: <ColorMap> <ColorMapEntry color="#323232" quantity="-300" label="label1" opacity="1"/> <ColorMapEntry color="#BBBBBB" quantity="200" label="label2" opacity="1"/> </ColorMap> A more refined example defines a color gradient from color #FFCC32 through color #BBBBBB, running through color #3645CC and color #CC3636. The bottom color #FFCC32 is defined to be transparent This simulates an alpha channel, since pixels with values of -300 and below will not be rendered. Notice that the default opacity is 1 (opaque) when not specified. GeoServer extends the <ColorMap> element to allow two attributes: type and extended. type The <ColorMap> type attribute specifies the kind of ColorMap to use. There are three different types of ColorMaps that can be specified: ramp, intervals and values. type="ramp" is the default ColorMap type. It specifies that colors should be interpolated for values between the color map entries. The result is shown in the following example. <ColorMap type="ramp"> <ColorMapEntry color="# ,→" quantity="-300" label="labe <ColorMapEntry color=" ,→#2851CC" quantity="0" label=" 6.2. SLD Styling 375 GeoServer User Manual, Release 2.15.1 <ColorMapEntry color=" #211F1F" quantity="50" label= <ColorMapEntry color="# ,→" quantity="100" label="label <ColorMapEntry color="# ,→" quantity="200" label="label <ColorMapEntry color="# ,→" quantity="250" label="label <ColorMapEntry color="# ,→" quantity="300" label="label <ColorMapEntry color="# ,→" quantity="350" label="label <ColorMapEntry color="# ,→" quantity="400" label="label <ColorMapEntry color="# ,→" quantity="450" label="label <ColorMapEntry color="# ,→" quantity="600" label="label </ColorMap> ,→ type="values" means that only pixels with the specified entry quantity values are rendered. Pixels with other values are not rendered. Using the example set of color map entries: <ColorMap type="values"> <ColorMapEntry color="# ,→" quantity="-300" label="labe ... <ColorMapEntry color="# ,→" quantity="600" label="label </ColorMap> The result image is: type="intervals" value means that each interval defined by two entries is rendered using the color of the first (lowest-value) entry. No color interpolation is applied across the intervals. Using the example set of color map entries: <ColorMap type="intervals ,→" extended="true"> <ColorMapEntry ,→color="#EEBE2F" ,→quantity="-300" label= ,→"label" opacity="0"/> ... 376 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 <ColorMapEntry color="#DDB02C ,→" quantity="600" label= ,→"label" opacity="1"/> </ColorMap> ,→ The result image is: The color map type is also reflected in the legend graphic. A typical request for a raster legend is (using the forceRule:true option to force output of the color map): OPTIONS=forceRule:true& LAYER=it. ,→geosolutions:di08032_da ,→ ,→ The the legends different returned types for are: extended The extended attribute specifies whether the color map gradient uses 256 (8-bit) or 65536 (16-bit) colors. The value false (the default) specifies that the color scale is calculated using 8-bit color, and true specifies using 16-bit color. CQL Expressions All of the ColorMapEntry attributes (color, quantity, label and opacity) can be defined using cql expressions, with the ${. . . expression. . . } syntax. CQL expressions are useful to make the color map dynamic, using values taken from the client: <ColorMapEntry color="#00FF00 ,→" quantity="${env('low',3)}" label="Low" opacity="1"/> <ColorMapEntry color="#FFFF00" quantity= ,→"${env('medium',10)}" label="Medium" opacity="1"/> <ColorMapEntry color="#FF0000" quantity= ,→"${env('high',1000)}" label="High" opacity="1"/> 6.2. SLD Styling 377 GeoServer User Manual, Release 2.15.1 In this example quantity values are not fixed, but can be specified by the client using the ENV request parameter: http://localhost:8080/geoserver/wms?REQUEST=GetMap&VERSION=1.0.0&. . . &ENV=low:10;medium:100;high:50 For a complete reference of CQL capabilities, see here ChannelSelection The <ChannelSelection> element specifies how dataset bands are mapped to image color channels. Named dataset bands may be mapped to red, green and blue channels, or a single named band may be mapped to a grayscale channel. The following example maps source channels 1, 2 and 3 to the red, green, and blue color channels. <ChannelSelection> <RedChannel> <SourceChannelName>1</SourceChannelName> </RedChannel> <GreenChannel> <SourceChannelName>2</SourceChannelName> </GreenChannel> <BlueChannel> <SourceChannelName>3</SourceChannelName> </BlueChannel> </ChannelSelection> The next example shows selecting a single band of an RGB image as a grayscale channel, and re-colorizing it via a ColorMap: <RasterSymbolizer> <Opacity>1.0</Opacity> <ChannelSelection> <GrayChannel> ,→ <SourceChannelName>1< </GrayChannel> </ChannelSelection> <ColorMap extended="true"> ,→ <ColorMapEntry color="#0000ff" ,→ <ColorMapEntry color="#009933" ,→ <ColorMapEntry color="#ff9900" q <ColorMapEntry color="#ff0000" q </ColorMap> </RasterSymbolizer> ,→ ChannelSelection Expressions Since the previous approach supports Strings only and therefore is static and not suitable when dealing with multispectral imagery 378 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 that has more than four bands and hyperspectral imagery (hyperspectral sensors have typically hundreds of bands), a dynamical approach is needed. By replacing Strings with Expressions in <SourceChannelName>, context free functions like env can be used to indicate which bands are to be used in a particular rendering session. The following example shows how to set the Red, Green and Blue channels and to map them into the desired bands. Here below, the env function will set, by default in the WMS request, the RedChannel on the second band, the GreenChannel on the fifth band and the BlueChannel on the seventh band. <RasterSymbolizer> <ChannelSelection> <RedChannel> <SourceChannelName> <ogc:Function name="env"> <ogc:Literal>B1</ogc:Literal> <ogc:Literal>1</ogc:Literal> </ogc:Function> </SourceChannelName> </RedChannel> <GreenChannel> <SourceChannelName> <ogc:Function name="env"> <ogc:Literal>B2</ogc:Literal> <ogc:Literal>2</ogc:Literal> </ogc:Function> </SourceChannelName> </GreenChannel> <BlueChannel> <SourceChannelName> <ogc:Function name="env"> <ogc:Literal>B3</ogc:Literal> <ogc:Literal>3</ogc:Literal> </ogc:Function> </SourceChannelName> </BlueChannel> </ChannelSelection> <RasterSymbolizer> 6.2. SLD Styling 379 GeoServer User Manual, Release 2.15.1 The style Schema supports also the SLD 1.1 and CSS. As a CSS examples: * { raster-channels: [env('B1','1')] '2' * { raster-channels: @B1(1) '2' '3';} One can specify the env request parameters in the WMS request to switch the bands and render the raster layer using the desired bands, for example the 4, 2, 3 as the following: http:// ,→localhost:8083/geosolutions/wms?servic ,→1.0&request=GetMap&layers=geosolutions ,→multichannel&styles=&bbox=-180. ,→0,-90.5,180.0,90.5&width=768&height=38 ,→format=application/openlayers&env=B1:4 Now let us suppose that we want to work on a single band and to exclude all the remaining bands in order to render a monochromatic raster. As an SLD example: <RasterSymbolizer> <Opacity>1.0</se:Opacity> <ChannelSelection> <GrayChannel> <SourceChannelName> <Function name="env"> <ogc:Literal>B1</ogc:Litera <ogc:Literal>7</ogc:Literal </ogc:Function> </SourceChannelName> </GrayChannel> </ChannelSelection> </RasterSymbolizer> The Schema above will render the channel “7” by default. As before, you can choose to render any channel of the raster by calling the env function in your WMS request and setting the desired band. By adding to the request &env=B1:3 for example: http://localhost:8083/ ,→geoserver/wms?service=WMS&vers ,→1.0&request=GetMap&layers=geos ,→styles=&bbox=-130.85168,20.705 ,→0054,54.1141&width=768&height= ,→format=application/openlayers& 380 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Finally, you can add a ColorMap on the selected channel as the following: <RasterSymbolizer> <Opacity>1.0</Opacity> <ChannelSelection> <GrayChannel> <SourceChannelName> <ogc:Function name=" <ogc:Literal>B1</ogc <ogc:Literal>7</ogc: </ogc:Function> </SourceChannelName> </GrayChannel> </ChannelSelection> <ColorMap> ,→ <ColorMapEntry color="#0000f ,→ <ColorMapEntry color="#009933 <ColorMapEntry color="#ff9900" ,→ <ColorMapEntry color="#ff0000 </ColorMap> </RasterSymbolizer> ,→ ContrastEnhancement The <ContrastEnhancement> element is used to adjust the relative brightness of the image data. A <ContrastEnhancement> element can be specified for the entire image, or in individual Channel elements. In this way, different enhancements can be used on each channel. There are three types of enhancements possible: • Normalize • Histogram • GammaValue <Normalize> means to expand the contrast so that the minimum quantity is mapped to minimum brightness, and the maximum quantity is mapped to maximum brightness. 6.2. SLD Styling 381 GeoServer User Manual, Release 2.15.1 <Histogram> is similar to Normalize, but the algorithm used attempts to produce an image with an equal number of pixels at all brightness levels. <GammaValue> is a scaling factor that adjusts the brightness of the image. A value less than one (1) darkens the image, and a value greater than one (1) brightens it. The default is 1 (no change). These examples turn on Normalize and Histogram, respectively: <ContrastEnhancement> <Normalize/> </ContrastEnhancement> <ContrastEnhancement> <Histogram/> </ContrastEnhancement> This example increases the brightness of the image by a factor of two. <ContrastEnhancement> <GammaValue>2</GammaValue> </ContrastEnhancement> It is also possible to customize Normalize Contrast Enhancement element for the RasterSymbolizer. 3 new VendorOptions are supported: • <VendorOption name=”algorithm”>ALGORITHM_NAME</VendorOption> to control the algorithm to apply • <VendorOption name=”minValue”>MIN_VALUE</VendorOption> to control the min value for the algorithm • <VendorOption name=”maxValue”>MAX_VALUE</VendorOption> to control the max value for the algorithm Supported algorithms are: • StretchToMinimumMaximum it will linearly stretch the source raster by linearly mapping values within the [MIN_VALUE, MAX_VALUE] range to [0,255]. This will also automatically result into a clip of the values outside the specified input range. • ClipToMinimumMaximum it will result into a clamp operation. Values smaller than MIN_VALUE will be forced to MIN_VALUE. Values greater than MAX_VALUE will be forced to MAX_VALUE. Values in the [MIN_VALUE, MAX_VALUE] range will passthrough unchanged. • ClipToZero is similar to ClipToMinimumMaximum. However, values outside the [MIN_VALUE, MAX_VALUE] range will be forced to be 0. Note: The target data type for the stretch algorithm is always byte (this might change in the future). This means that if the MAX_VALUE for the Clip oriented algorithms is greater than 255 an implicit clamp will apply anyway to clamp to 255. Here below some examples 382 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 <ContrastEnhancement> <Normalize> <VendorOption name= ,→"algorithm">StretchToMinimumMaximum</VendorOption> <VendorOption name="minValue">50</VendorOption> <VendorOption name="maxValue">100</VendorOption> </Normalize> </ContrastEnhancement> This example will apply a Normalized ContrastEnhancement by linearly stretch from pixel values [50, 100] to [0, 255] <ContrastEnhancement> <Normalize> <VendorOption ,→name="algorithm">ClipToMinimumMaximum</VendorOption> <VendorOption name="minValue">50</VendorOption> <VendorOption name="maxValue">100</VendorOption> </Normalize> </ContrastEnhancement> <ContrastEnhancement> <Normalize> <VendorOption ,→name="algorithm">ClipToMinimumMaximum</VendorOption> <VendorOption name="minValue">50</VendorOption> <VendorOption name="maxValue">100</VendorOption> </Normalize> </ContrastEnhancement> Here below a more complex example that shows the possibility to control the values from a client using env functions. This is extremely interesting for interactive applications. ... <ContrastEnhancement> <Normalize> <VendorOption name="algorithm"> <ogc:Function name="env"> <ogc:Literal>algorithm</ogc:Literal> ,→ 6.2. SLD Styling <ogc:Literal>StretchToMinimumMaximum</ogc:Literal> </ogc:Function> </VendorOption> <VendorOption name='minValue'> <ogc:Function name="env"> <ogc:Literal>minValue</ogc:Literal> <ogc:Literal>10</ogc:Literal> </ogc:Function> </VendorOption> <VendorOption name='maxValue'> <ogc:Function name="env"> <ogc:Literal>maxValue</ogc:Literal> <ogc:Literal>1200</ogc:Literal> </ogc:Function> </VendorOption> </Normalize> 383 GeoServer User Manual, Release 2.15.1 </ContrastEnhancement> ... ShadedRelief Warning: Support for this element has not been implemented yet. The <ShadedRelief> element can be used to create a 3-D effect, by selectively adjusting brightness. This is a nice effect to use on an elevation dataset. There are two types of shaded relief possible. • BrightnessOnly • ReliefFactor BrightnessOnly, which takes no parameters, applies shading in WHAT WAY? ReliefFactor sets the amount of exaggeration of the shading (for example, to make hills appear higher). According to the OGC SLD specification, a value of around 55 gives “reasonable results” for Earth-based datasets: <ShadedRelief> <BrightnessOnly /> <ReliefFactor>55</ReliefFactor> </ShadedRelief> The above example turns on Relief shading in WHAT WAY? OverlapBehavior Warning: Support for this element has not been implemented yet. Sometimes raster data is comprised of multiple image sets. Take, for example, a satellite view of the Earth at night . As all of the Earth can’t be in nighttime at once, a composite of multiple images are taken. These images are georeferenced, and pieced together to make the finished product. That said, it is possible that two images from the same dataset could overlap slightly, and the OverlapBehavior element is designed to determine how this is handled. There are four types of OverlapBehavior: • AVERAGE • RANDOM • LATEST_ON_TOP • EARLIEST_ON_TOP AVERAGE takes each overlapping point and displays their average value. RANDOM determines which image gets displayed according to chance (which can sometimes result in a crisper image). 384 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 LATEST_ON_TOP and EARLIEST_ON_TOP sets the determining factor to be the internal timestamp on each image in the dataset. None of these elements have any parameters, and are all called in the same way: <OverlapBehavior> <AVERAGE /> </OverlapBehavior> The above sets the OverlapBehavior to AVERAGE. ImageOutline Warning: Support for this element has not been implemented yet. Given the situation mentioned previously of the image composite, it is possible to style each image so as to have an outline. One can even set a fill color and opacity of each image; a reason to do this would be to “gray-out” an image. To use ImageOutline, you would define a <LineSymbolizer> or <PolygonSymbolizer> inside of the element: <ImageOutline> <LineSymbolizer> <Stroke> <CssParameter name="stroke">#0000ff</CssParameter> </Stroke> </LineSymbolizer> </ImageOutline> ,→ The above would create a border line (colored blue with a one pixel default thickness) around each image in the dataset. 6.2.5 SLD Extensions in GeoServer GeoServer provides a number of vendor-specific extensions to SLD 1.0. Although not portable to other applications, these extensions make styling more powerful and concise and allow for the generation of better-looking maps. Geometry transformations in SLD SLD symbolizers may contain an optional <Geometry> element, which allows specifying which geometry attribute is to be rendered. In the common case of a featuretype with a single geometry attribute this element is usually omitted, but it is useful when a featuretype has multiple geometry-valued attributes. SLD 1.0 requires the <Geometry> content to be a <ogc:PropertyName>. GeoServer extends this to allow a general SLD expression to be used. The expression can contain 6.2. SLD Styling 385 GeoServer User Manual, Release 2.15.1 filter functions that manipulate geometries by transforming them into something different. This facility is called SLD geometry transformations. GeoServer provides a number of filter functions that can transform geometry. A full list is available in the Filter Function Reference. They can be used to do things such as extracting line vertices or endpoints, offsetting polygons, or buffering geometries. Geometry transformations are computed in the geometry’s original coordinate reference system, before any reprojection and rescaling to the output map is performed. For this reason, transformation parameters must be expressed in the units of the geometry CRS. This must be taken into account when using geometry transformations at different screen scales, since the parameters will not change with scale. Examples Let’s look at some examples. Extracting vertices Here is an example that allows one to extract all the vertices of a geometry, and make them visible in a map, using the vertices function: <PointSymbolizer> <Geometry> <ogc:Function name="vertices"> <ogc:PropertyName>the_geom</ogc:PropertyName> </ogc:Function> </Geometry> <Graphic> <Mark> <WellKnownName>square</WellKnownName> <Fill> 1 2 3 4 5 6 7 8 9 10 11 <CssParameter name="fill">#FF0000</CssParameter> </Fill> </Mark> <Size>6</Size> </Graphic> </PointSymbolizer> ,→ 12 13 14 15 16 View the full "Vertices" SLD Applied to the sample tasmania_roads layer this will result in: Start and end point The startPoint and endPoint functions can be used to extract the start and end point of a line. 386 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.78: Extracting and showing the vertices out of a geometry <PointSymbolizer> <Geometry> <ogc:Function name="startPoint"> <ogc:PropertyName>the_geom</ogc:PropertyName> </ogc:Function> </Geometry> <Graphic> <Mark> <WellKnownName>square</WellKnownName> <Stroke> 1 2 3 4 5 6 7 8 9 10 11 ,→ <CssParameter name="stroke">0x00FF00</CssParameter> 12 <CssParameter name="stroke-width">1.5</CssParameter> </Stroke> </Mark> <Size>8</Size> </Graphic> </PointSymbolizer> <PointSymbolizer> <Geometry> <ogc:Function name="endPoint"> <ogc:PropertyName>the_geom</ogc:PropertyName> </ogc:Function> </Geometry> <Graphic> <Mark> <WellKnownName>circle</WellKnownName> <Fill> ,→ 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 ,→ 29 30 31 6.2. SLD Styling <CssParameter name="fill">0xFF0000</CssParameter> </Fill> </Mark> <Size>4</Size> 387 GeoServer User Manual, Release 2.15.1 </Graphic> </PointSymbolizer> 32 33 View the full "StartEnd" SLD Applied to the sample tasmania_roads layer this will result in: Fig. 6.79: Extracting start and end point of a line Drop shadow The offset function can be used to create drop shadow effects below polygons. Notice that the offset values reflect the fact that the data used in the example is in a geographic coordinate system. <PolygonSymbolizer> <Geometry> <ogc:Function name="offset"> <ogc:PropertyName>the_geom</ogc:PropertyName> <ogc:Literal>0.00004</ogc:Literal> <ogc:Literal>-0.00004</ogc:Literal> </ogc:Function> </Geometry> <Fill> <CssParameter name="fill">#555555</CssParameter> </Fill> </PolygonSymbolizer> 1 2 3 4 5 6 7 8 9 10 11 12 View the full "Shadow" SLD Applied to the sample tasmania_roads layer this will result in: 388 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.80: Dropping building shadows Performance tips GeoServer’s filter functions contain a number of set-related or constructive geometric functions, such as buffer, intersection, difference and others. These can be used as geometry transformations, but they be can quite heavy in terms of CPU consumption so it is advisable to use them with care. One strategy is to activate them only at higher zoom levels, so that fewer features are processed. Buffering can often be visually approximated by using very large strokes together with round line joins and line caps. This avoids incurring the performance cost of a true geometric buffer transformation. Adding new transformations Additional filter functions can be developed in Java and then deployed in a JAR file as a GeoServer plugin. A guide is not available at this time, but see the GeoTools main module for examples. Rendering Transformations Rendering Transformations allow processing to be carried out on datasets within the GeoServer rendering pipeline. A typical transformation computes a derived or aggregated result from the input data, allowing various useful visualization effects to be obtained. Transformations may transform data from one format into another (i.e vector to raster or vice-versa), to provide an appropriate format for display. 6.2. SLD Styling 389 GeoServer User Manual, Release 2.15.1 The following table lists examples of various kinds of rendering transformations available in GeoServer: Type Raster-to-Vector Vector-to-Raster Vector-to-Vector Examples Contour extracts contours from a DEM raster. RasterAsPointCollections extracts a vector field from a multi-band raster BarnesSurfaceInterpolation computes a surface from scattered data points. Heatmap computes a heatmap surface from weighted data points. PointStacker aggregates dense point data into clusters. Rendering transformations are invoked within SLD styles. Parameters may be supplied to control the appearance of the output. The rendered output for the layer is produced by applying the styling rules and symbolizers in the SLD to the result of transformation. Rendering transformations are implemented using the same mechanism as Process Cookbook. They can thus also be executed via the WPS protocol, if required. Conversely, any WPS process can be executed as a transformation, as long as the input and output are appropriate for use within an SLD. This section is a general guide to rendering transformation usage in GeoServer. For details of input, parameters, and output for any particular rendering transformation, refer to its own documentation. Installation Using Rendering Transformations requires the WPS extension to be installed. See Installing the WPS extension. Note: The WPS service does not need to be enabled to use Rendering Transformations. To avoid unwanted consumption of server resources it may be desirable to disable the WPS service if it is not being used directly. Usage Rendering Transformations are invoked by adding the <Transformation> element to a <FeatureTypeStyle> element in an SLD document. This element specifies the name of the transformation process, and usually includes parameter values controlling the operation of the transformation. The <Transformation> element syntax leverages the OGC Filter function syntax. The content of the element is a <ogc:Function> with the name of the rendering transformation process. Transformation processes may accept some number of parameters, which may be either required (in which case they must be specified), or optional (in which case they may be omitted if the default value is acceptable). Parameters are supplied as name/value pairs. Each parameter’s name and value are supplied via another function <ogc:Function name="parameter">. The first argument to 390 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 this function is an <ogc:Literal> containing the name of the parameter. The optional following arguments provide the value for the parameter (if any). Some parameters accept only a single value, while others may accept a list of values. As with any filter function argument, values may be supplied in several ways: • As a literal value • As a computed expression • As an SLD environment variable, whose actual value is supplied in the WMS request (see Variable substitution in SLD). • As a predefined SLD environment variable (which allows obtaining values for the current request such as output image width and height). The order of the supplied parameters is not significant. Most rendering transformations take as input a dataset to be transformed. This is supplied via a special named parameter which does not have a value specified. The name of the parameter is determined by the particular transformation being used. When the transformation is executed, the input dataset is passed to it via this parameter. The input dataset is determined by the same query mechanism as used for all WMS requests, and can thus be filtered in the request if required. In rendering transformations which take as input a featuretype (vector dataset) and convert it to a raster dataset, in order to pass validation the SLD needs to mention the geometry attribute of the input dataset (even though it is not used). This is done by specifying the attribute name in the symbolizer <Geometry> element. The output of the rendering transformation is styled using symbolizers appropriate to its format: PointSymbolizer, LineSymbolizer, PolygonSymbolizer, and TextSymbolizer for vector data, and RasterSymbolizer for raster coverage data. If it is desired to display the input dataset in its orginal form, or transformed in another way, there are two options: • Another <FeatureTypeStyle> can be used in the same SLD • Another SLD can be created, and the layer displayed twice using the different SLDs Notes • Rendering transformations may not work correctly in tiled mode, unless they have been specifically written to accomodate it. Examples Contour extraction ras:Contour is a Raster-to-Vector rendering transformation which extracts contour lines at specified lev6.2. SLD Styling 391 GeoServer User Manual, Release 2.15.1 els from a raster DEM. The following SLD invokes the transformation and styles the contours as black lines. <?xml version="1.0" encoding="ISO-8859-1"?> <StyledLayerDescriptor version="1.0.0" xsi:schemaLocation="http:/ ,→/www.opengis.net/sld StyledLayerDescriptor.xsd" xmlns="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi= ,→"http://www.w3.org/2001/XMLSchema-instance"> <NamedLayer> <Name>contour_dem</Name> <UserStyle> <Title>Contour DEM Extracts contours from DEM data levels 1100 1200 1300 1400 1500 1600 1700 1800 rule1 Contour Line 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 ,→ #000000 ,→ 1 38 39 40 41 42 43 44 45 46 Arial ,→ 47 Normal ,→ 48 ,→ 392 10 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 2 49 50 51 52 53 54 55 56 57 58 ,→ #FFFFFF ,→ 0.6 ,→ #000000 2000 ,→ true 59 60 61 62 63 64 65 66 67 100 50 ,→ 68 69 ,→ 70 71 72 73 74 75 30 Key aspects of the SLD are: • Lines 14-15 define the rendering transformation, using the process ras:Contour. • Lines 16-18 supply the input data parameter, named data in this process. • Lines 19-29 supply values for the process’s levels parameter, which specifies the elevation levels for the contours to extract. • Lines 35-40 specify a LineSymbolizer to style the contour lines. • Lines 41-70 specify a TextSymbolizer to show the contour levels along the lines. The result of using this transformation is shown in the following map image (which also shows the underlying DEM raster): Heatmap generation vec:Heatmap is a Vector-to-Raster rendering transformation which generates a heatmap surface from weighted point data. The following SLD invokes a Heatmap rendering transformation on a featuretype 6.2. SLD Styling 393 GeoServer User Manual, Release 2.15.1 with point geometries and an attribute pop2000 supplying the weight for the points (in this example, a dataset of world urban areas is used). The output is styled using a color ramp across the output data value range [0 .. 1]. Heatmap Heatmap A ,→heatmap surface showing population density data weightAttr pop2000 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ,→ radiusPixels radius 100 ,→ pixelsPerCell 25 26 27 28 29 30 31 394 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 10 outputBBOX wms_bbox outputWidth wms_width 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 ,→ 48 outputHeight 49 wms_height ,→the_geom 0.6 ,→ 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 Key aspects of the SLD are: • Lines 14-15 define the rendering transformation, using the process vec:Heatmap. • Lines 16-18 supply the input data parameter, named data in this 6.2. SLD Styling 395 GeoServer User Manual, Release 2.15.1 process. • Lines 19-22 supply a value for the process’s weightAttr parameter, which specifies the input attribute providing a weight for each data point. • Lines 23-29 supply the value for the radiusPixels parameter, which controls the “spread” of the heatmap around each point. In this SLD the value of this parameter may be supplied by a SLD substitution variable called radius, with a default value of 100 pixels. • Lines 30-33 supply the pixelsPerCell parameter, which controls the resolution at which the heatmap raster is computed. • Lines 34-38 supply the outputBBOX parameter, which is given the value of the standard SLD environment variable wms_bbox. • Lines 40-45 supply the outputWidth parameter, which is given the value of the standard SLD environment variable wms_width. • Lines 46-52 supply the outputHeight parameter, which is given the value of the standard SLD environment variable wms_height. • Lines 55-70 specify a RasterSymbolizer to style the computed raster surface. The symbolizer contains a ramped color map for the data range [0..1]. • Line 58 specifies the geometry attribute of the input featuretype, which is necessary to pass SLD validation. This transformation styles a layer to produce a heatmap surface for the data in the requested map extent, as shown in the image below. (The map image also shows the original input data points styled by another SLD, as well as a base map layer.) Running map algebra on the fly using Jiffle The Jiffle rendering transformation allows to run map algebra on the bands of an input raster layer using the Jiffle language. For example, the following style computes the NDVI index from a 13 bands Sentinel 2 image, in which the red and NIR bands are the 396 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 forth and eight bands (Jiffle band indexes are zero based), and then displays the resulting index with a color map: Sentinel2 NDVI NDVI coverage script nir = src[7]; vir = src[3]; dest = (nir - vir) / (nir + vir); 1.0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 ,→ ,→ ,→ ,→ ,→ 29 30 31 32 33 ,→ 34 35 36 37 38 39 40 Here are a view of the area, using the visible color bands: and then the display of the NDVI index computed with the above style: 6.2. SLD Styling 397 GeoServer User Manual, Release 2.15.1 398 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Graphic symbology in GeoServer Graphic symbology is supported via the SLD element. This element can appear in several contexts in SLD: • in a PointSymbolizer, to display symbols at points • in the / element of a LineSymbolizer and PolygonSymbolizer, to display repeated symbols along lines and polygon boundaries. • in the / element of a LineSymbolizer and PolygonSymbolizer, to fill lines and polygon boundaries with tiled symbols. • in the / element of a PolygonSymbolizer, to fill polygons with tiled symbols (stippling). • in a TextSymbolizer to display a graphic behind or instead of text labels (this is a GeoServer extension). contains either a or an element. Marks are pure vector symbols whose geometry is predefined but with stroke and fill defined in the SLD itself. External Graphics are external files (such as PNG images or SVG graphics) that contain the shape and color information defining how to render a symbol. In standard SLD the and names are fixed strings. GeoServer extends this by providing dynamic symbolizers, which allow computing symbol names on a per-feature basis by embedding CQL expressions in them. Marks GeoServer supports the standard SLD symbols, a userexpandable set of extended symbols, and also TrueType Font glyphs. The symbol names are specified in the element. See also the PointSymbolizer reference for further details, as well as the examples in the Points Cookbook section. Standard symbols The SLD specification mandates the support of the following symbols: Name square circle triangle star cross x 6.2. SLD Styling Description A square A circle A triangle pointing up five-pointed star A square cross with space around (not suitable for hatch fills) A square X with space around (not suitable for hatch fills) 399 GeoServer User Manual, Release 2.15.1 Shape symbols The shape symbols set adds extra symbols that are not part of the basic set. Their names are prefixed by shape:// Name shape:// vertline shape:// horline shape://slash shape:// backslash shape://dot shape://plus shape://times shape:// oarrow shape:// carrow Description A vertical line (suitable for hatch fills or to make railroad symbols) A horizontal line (suitable for hatch fills) A diagonal line leaning forwards like the “slash” keyboard symbol (suitable for diagonal hatches) Same as shape://slash, but oriented in the opposite direction A very small circle with space around A + symbol, without space around (suitable for cross-hatch fills) A “X” symbol, without space around (suitable for cross-hatch fills) An open arrow symbol (triangle without one side, suitable for placing arrows at the end of lines) A closed arrow symbol (closed triangle, suitable for placing arrows at the end of lines) The weather symbols are prefixed by the extshape:// protocol in the SLD: Name Description extshape:// triangle cold front extshape:// emicircle warm front Produces extshape:// stationary front triangleemicircle You can use extshape:// for a few additional built-in shapes: extshape:// narrow extshape:// sarrow North Arrow South Arrow More complex symbols like Wind Barbs can be created with the windbarbs:// prefix. There are some examples: 400 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Name windbarbs://default(15)[kts] windbarbs://default(9)[m/s]? hemisphere=s Description 15 wind intensity with [kts] unit of measure 9 wind intensity with [m/s] unit of measure, in the south hemisphere Custom WKT Shapes Custom shapes can be defined using your own Geometry. Geometry is defined using the same well-known-text format used for CQL_FILTER. ,→wkt://MULTILINESTRING((-0.25 -0.25, -0. ,→125 -0.25), (0.125 -0.25, 0.25 -0.25), (-0.25 0.25, ,→0.125 0.25), (0.125 0.25, 0.25 0.25)) ,→ #0000ff ,→ #0000ff 1 6 ,→ Which produces double dashed line: You can also make use of curves when defining WKT: wkt:/ ,→/COMPOUNDCURVE((0 0, 0.25 0), CIRCULARSTRING(0.25 ,→0, 0.5 0.5, 0.75 0), (0.75 0, 1 0)) ,→ 6.2. SLD Styling #0000ff 401 GeoServer User Manual, Release 2.15.1 ,→ #0000ff 1 10 ,→ Producing an “emi circle” line: Bulk TTF marks It is possible to create a mark using glyphs from any decorative or symbolic True Type Font, such as Wingdings, WebDings, or the many symbol fonts available on the internet. The syntax for specifying this is: ttf://# where fontname is the full name of a TTF font available to GeoServer, and hexcode is the hexadecimal code of the symbol. To get the hex code of a symbol, use the “Char Map” utility available in most operating systems (Windows and Linux Gnome both have one). For example, to use the “shield” symbol contained in the WebDings font, the Gnome charmap reports the symbol hex code as shown: The SLD to use the shield glyph as a symbol is: 1 2 3 4 ,→ 5 ttf://Webdings#0x0064 6 #AAAAAA 16 ,→ 7 8 9 10 11 12 This results in the following map display: 402 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.81: Selecting a symbol hex code in the Gnome char map Fig. 6.82: Shield symbols rendered on the map 6.2. SLD Styling 403 GeoServer User Manual, Release 2.15.1 Extending the Mark subsytem using Java The Mark subsystem is user-extensible. To do this using Java code, implement the MarkFactory interface and declare the implementation in the META-INF/services/org.geotools.renderer. style.MarkFactory file. For further information see the Javadoc of the GeoTools MarkFactory, along with the following example code: • The factory SPI registration file • The TTFMarkFactory implementation • The ShapeMarkFactory implementation External Graphics is the other way to define point symbology. Unlike marks, external graphics are used as-is, so the specification is somewhat simpler. The element content specifies a graphic using a URL or file path, and the graphic using a MIME type: image/png 1 2 3 4 5 6 7 8 As with , a element can be optionally specified. When using images as graphic symbols it is better to avoid resizing, as that may blur their appearance. Use images at their native resolution by omitting the element. In contrast, for SVG graphics specifying a is recommended. SVG files are a vector-based format describing both shape and color, so they scale cleanly to any size. If the path of the symbol file is relative, the file is looked for under $GEOSERVER_DATA_DIR/styles. For example: image/svg+xml 20 1 2 3 4 5 6 7 8 9 In this example an SVG graphic is being used, so the size is specified explicitly. 404 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Bulk WKT Shapes It is possible to create a symbol set of your own custom marks using a property file. Here is an example.properties: zig=LINESTRING(0. ,→0 0.25, 0.25 0.25, 0.5 0.75, 0.75 0.25, 1.00 0.25) block=POLYGON((0 0, 1 0, 1 1, 0 1, 0 0)) The SLD to use the symbols defined in example.properties is: wkt 20 1 2 3 4 5 6 7 8 9 10 11 Symbol Positioning Graphic symbols are rendered so that the center of the graphic extent lies on the placement point (or points, in the case of repeated or tiled graphics). If it is desired to have a graphic offset from a point (such as a symbol which acts as a pointer) it is necessary to offset the visible portion of the graphic within the overall extent. For images this can be accomplished by extending the image with transparent pixels. For SVG graphics this can be done by surrounding the shape with an invisible rectangle with the desired relative position. Dynamic symbolizers In standard SLD, the Mark/WellKnowName element and the ExternalGraphic/OnlineResource/@xlink:href attribute are fixed strings. This means they have the same value for all rendered features. When the symbols to be displayed vary depending on feature attributes this restriction leads to very verbose styling, as a separate Rule and Symbolizer must be used for each different symbol. GeoServer improves this by allowing CQL expressions to be embedded inside the content of both WellKnownName and OnlineResource/@xlink:href. When the names of the symbols can be derived from the feature attribute values, this provides much more compact styling. CQL expressions can be embedded in a content string or an xlink:href attribute by using the syntax: 6.2. SLD Styling 405 GeoServer User Manual, Release 2.15.1 ${} Note: Currently xlink:href strings must be valid URLs before expression expansion is performed. This means that the URL cannot be completely provided by an expression. The xlink:href string must explicitly include at least the prefix http:// The simplest form of expression is a single attribute name, such as ${STATE_ABBR}. For example, suppose we want to display the flags of the US states using symbols whose file names match the state name. The following style specifies the flag symbols using a single rule: image/jpeg ,→ 4 5 If manipulation of the attribute values is required a full CQL expression can be specified. For example, if the values in the STATE_ABBR attribute are uppercase but the URL requires a lowercase name, the CQL strToLowerCase function can be used: image/jpeg 1 2 3 4 5 Variable substitution in SLD Variable substitution in SLD is a GeoServer extension (starting in version 2.0.2) that allows passing values from WMS requests into SLD styles. This allows dynamically setting values such as colors, fonts, sizes and filter thresholds. Variables are specified in WMS GetMap requests by using the env request parameter followed by a list of name:value pairs separated by semicolons: ...&env=name1:value1;name2=value2&... In an SLD the variable values are accessed using the env function. The function retrieves a substitution variable value specified in the current request: size A default value can be provided. It will be used if the variable was not specified in the request: 406 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 size 6 The env function can be used in an SLD anywhere an OGC expression is allowed. For example, it can be used in CSSParameter elements, in size and offset elements, and in rule filter expressions. It is also accepted in some places where full expressions are not allowed, such as in the Mark/WellKnownName element. Predefined Variables GeoServer has predefined variables which provide information about specific properties of the request output. These are useful when SLD parameters need to depend on output dimensions. The predefined variables are: Name Type Description wms_bbox ReferencedEnvelope the georeferenced extent of the request output wms_crs CoordinateReferenceSystem the definition of the output coordinate reference system wms_srs String the code for the output coordinate reference system wms_width Integer the width (in pixels) of the output image wms_height Integer the height (in pixels) of the output image wms_scale_denominator Integer the denominator of the output map scale kmlOutputMode Either vector or this variable gets set to vector when the kml generator empty is writing out vector features as placemarks, as opposed to ground overlays Example The following SLD symbolizer has been parameterized in three places, with default values provided in each case: name square # color FF0000 6.2. SLD Styling 407 GeoServer User Manual, Release 2.15.1 size 6 Download the full SLD style When no variables are provided in the WMS request, the SLD uses the default values and renders the sample sf:bugsites dataset as shown: Fig. 6.83: Default rendering If the request is changed to specify the following variable values: &env=color:00FF00;name:triangle;size:12 the result is instead: Fig. 6.84: Rendering with variables supplied 408 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Specifying symbolizer sizes in ground units The SLD 1.0 specification allows giving symbolizer sizes in a single unit of measure: pixels. This means that the size of symbolizers is the same at all zoom levels (which is usually the desired behaviour). The Symbology Encoding 1.1 specification provides a uom attribute on Symbolizer elements. This allows specifying styling parameter sizes in ground units of metres or feet, as well as the default which is screen pixels. When ground units are used, the screen size of styled elements increases as the map is zoomed in to larger scales. GeoServer supports the SE 1.1 uom attribute in its extended SLD 1.0 support. Note: This extended feature is officially supported in GeoServer 2.1.0. It is available in GeoServer 2.0.3 if the -DenableDpiUomRescaling=true system variable is specified for the JVM. The value of the uom attribute is a URI indicating the desired unit. The units of measure supported are those given in the SE 1.1 specification: http://www.opengeospatial.org/se/units/metre http://www.opengeospatial.org/se/units/foot http://www.opengeospatial.org/se/units/pixel Note: The px override modifier for parameters values is not currently supported. Example The following SLD shows the uom attribute used to specify the width of a LineSymbolizer in metres: 5m blue line tm blue line Default line style, 5m wide blue ,→ Blue Line, 5m large ,→ 6.2. SLD Styling #0000FF 409 GeoServer User Manual, Release 2.15.1 ,→ 5 Applying the style to the tiger:tiger_roads dataset shows how the line widths increase as the map is zoomed in: Label Obstacles GeoServer implements an algorithm for label conflict resolution, to prevent labels from overlapping one another. By default this algorithm only considers conflicts with other labels. This can result in labels overlapping other symbolizers, which may produce an undesirable effect. GeoServer supports a vendor option called labelObstacle that allows marking a symbolizer as an obstacle. This tells the labeller to avoid rendering labels that overlap it. 410 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Warning: Beware of marking a line or poly symbolizer as a label obstacle. The label conflict resolving routine is based on the bounding box so marking as a label obstacle will result in no label overlapping not only the geometry itself, but its bounding box as well. image/png 32 6.2. SLD Styling 411 GeoServer User Manual, Release 2.15.1 true Applying the obstacle to a regular point style: image/png 32 true Applying the obstacle to line/polygon style style: 412 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 6.2. SLD Styling 413 GeoServer User Manual, Release 2.15.1 Adding space around graphic fills Starting with GeoServer 2.3.4 it is possible to add white space around symbols used inside graphic fills, effectively allowing to control the density of the symbols in the map. image/png 10 The above forces 10 pixels of white space above, below and on either side of the symbol, effectively adding 20 pixels of white space between the symbols in the fill. The graphic-margin can be expressed, just like the CSS margin, in four different ways: • top,right,bottom,left (one explicit value per margin) • top,right-left,bottom (three values, with right and left sharing the 414 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 same value) • top-bottom,right-left (two values, top and bottom sharing the same value) • top-right-bottom-left (single value for all four margins) The ability to specify different margins allows to use more than one symbol in a fill, and synchronize the relative positions of the various symbols to generate a composite fill: image/png 35 17 17 35 image/png 16 16 32 32 6.2. SLD Styling 415 GeoServer User Manual, Release 2.15.1 Fills with randomized symbols Starting with GeoServer 2.4.2 it is possible to generate fills by randomly repeating a symbol in the polygons to be filled. Or, to be more precise, generate the usual texture fill by repeating over and over a tile, whose contents is the random repetition of a fill. The random distribution is stable, so it will be the same across calls and tiles, and it’s controlled by the seed used to generate the distribution. The random fill is generated by specifying a GraphicFill with a Mark or ExternalGraphic, and then adding vendor options to control how the symbol is randomly repeated. Here is a table with options, default values, and possible values: Option random Default value none random-tile-size 256 random-rotation none random-symbolcount 16 random-seed 0 Description Activates random distribution of symbol. Possible values are none, free, grid. none disables random distribution, free generates a completely random distribution, grid will generate a regular grid of positions, and only randomizes the position of the symbol around the cell centers, providing a more even distribution in space Size the the texture fill tile that will contain the randomly distributed symbols Activates random symbol rotation. Possible values are none (no rotation) or free The number of symbols in the tile. The number of symbols actually painted can be lower, as the distribution will ensure no two symbols overlap with each other. The “seed” used to generate the random distribution. Changing this value will result in a different symbol distribution Here is an example: shape://slash #0000ff round 4 8 5 grid ,→ 416 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 100 free 50 ,→ Fig. 6.85: Random distribution of a diagonal line Randomized distributions can also be used for thematic mapping, for example, here is the SLD for a version of topp:states that displays the number of inhabitantìs varying the density of a random point distribution: Default Styler name 6.2. SLD Styling ,→ PERSONS 2000000 ,→ PERSONS 4000000 417 GeoServer User Manual, Release 2.15.1 circle #a9a9a9 2 grid 100 150 PERSONS 2000000 ,→ circle #a9a9a9 2 grid 100 50 ,→ 418 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 PERSONS 4000000 circle #a9a9a9 2 grid 100 500 ,→ Fig. 6.86: Thematic map via point density approach 6.2. SLD Styling 419 GeoServer User Manual, Release 2.15.1 Color compositing and color blending It is possible to perform color blending and compositing, either between feature type styles or by associating blending operations with each symbolizer. GeoServer implements most of the color compositing and blending modes suggested by the SVG compositing and blending level 1 specification. Either set of operations allows one to control how two overlapping layers/symbols are merged together to form a final map (as opposed to the normal behavior of just stacking images on top of each other). This section will use the following definitions for the common terms “source” and “destination”: • Source : Image currently being painted on top of the map • Destination: Background image that the source image is being drawn on Specifying compositing and blending in SLD Composites Both compositing and blending can be specified in SLD by adding the following VendorOption to either the end of a Symbolizer or FeatureTypeStyle: multiply In case a custom opacity is desired, it can be added after the operation name separated with a comma: multiply, 0.5 Note: See the full list of available modes. Warning: Blending against symbolizers causes exceptions inside the JDK when using OpenJDK. The issue is known and has been reportedly fixed, but only in OpenJDK 9. One way to get around this issue with OpenJDK 7/8 is to install the Marlin renderer. This replaces the OpenJDK core renderer and does not suffer from the same issue. Oracle JDK 7 or 8 does not show this issue. Composite bases For FeatureTypeStyles an additional vendor option can be added to control compositing groups: 420 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 true This will tell the rendering engine to use that FeatureTypeStyle as the destination, and will compose all subsequent FeatureTypeStyle/Layers on top of it, until another base is found. Once the full set of layers against a base is composed, then the base itself will be composed against the next set of composed layers, using its own compositing operator, if present. Without this setting, the destination will be the full stack of all previous FeatureTypeStyles and layers drawn before the current one. This can be limiting for two reasons: • It limits the usefulness of alpha-composite masking operations • It breaks the WMS model, where the client can decide freely how to stack layers (the desired compositing effects will be achieved only when a certain stack of layers is used) Consider the following example: In this example, the first two layers are drawn on top of each other, forming “Merge1”. The third layer is a composite base, as such it won’t be merged on top of the already drawn map immediately, but it will be drawn to an off-screen buffer, and layer 4 and 5 will be drawn/composited on top of it. Once that happens, “Merge2” is ready, and gets drawn on top of “Merge1”, The next layer is another base, so “Base2” will be again drawn to an off-screen buffer, and layer 7 and 8 will be drawn/composited on top of it, forming Merge3. Once Merge3 is ready, it will be drawn/composited on top of the already fused Merge1/Merge2, generating the final map. Composite and blending modes There are two types of modes: alpha composite and color blending. Alpha compositing controls how two images are merged together by using the alpha levels of the two. No color mixing is being performed, only pure binary selection (either one or the other). 6.2. SLD Styling 421 GeoServer User Manual, Release 2.15.1 Color blending modes mix the colors of source and destination in various ways. Each pixel in the result will be some sort of combination between the source and destination pixels. The following page shows the full list of available modes. (See the syntax page for more details.) To aid in comprehension, two source and two destination images will be used to show visually how each mode works: Source 1 Source 2 Destination 1 Destination 2 Alpha compositing modes copy Only the source will be present in the output. 422 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Example 1 Example 2 destination Only the destination will be present in the output Example 1 Example 2 source-over The source is drawn over the destination, and the destination is visible where the source is transparent. Opposite of destination-over. Example 1 6.2. SLD Styling Example 2 423 GeoServer User Manual, Release 2.15.1 destination-over The source is drawn below the destination, and is visible only when the destination is transparent. Opposite of source-over. Example 1 Example 2 source-in The source is visible only when overlapping some non-transparent pixel of the destination. This allows the background map to act as a mask for the layer/feature being drawn. Opposite of destination-in. Example 1 Example 2 destination-in The destination is retained only when overlapping some non transparent pixel in the source. This allows the layer/feature to be drawn to act as a mask for the background map. Opposite of source-in. 424 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Example 1 Example 2 source-out The source is retained only in areas where the destination is transparent. This acts as a reverse mask when compared to source-in. Example 1 Example 2 destination-out The destination is retained only in areas where the source is transparent. This acts as a reverse mask when compared to destination-in. Example 1 6.2. SLD Styling Example 2 425 GeoServer User Manual, Release 2.15.1 source-atop The destination is drawn fully, while the source is drawn only where it intersects the destination. Example 1 Example 2 destination-atop The source is drawn fully, and the destination is drawn over the source and only where it intersects it. Example 1 Example 2 xor “Exclusive Or” mode. Each pixel is rendered only if either the source or the destination is not blank, but not both. 426 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Example 1 Example 2 Color blending modes multiply The source color is multiplied by the destination color and replaces the destination. The resulting color is always at least as dark as either the source or destination color. Multiplying any color with black results in black. Multiplying any color with white preserves the original color. Example 1 Example 2 screen Multiplies the complements of the source and destination color values, then complements the result. The end result color is always at least as light as either of the two constituent colors. Screening any color with white produces white; screening with black leaves the original color unchanged. The effect is similar to projecting multiple photographic slides simultaneously onto a single screen. 6.2. SLD Styling 427 GeoServer User Manual, Release 2.15.1 Example 1 Example 2 overlay Multiplies (screens) the colors depending on the destination color value. Source colors overlay the destination while preserving its highlights and shadows. The backdrop color is not replaced but is mixed with the source color to reflect the lightness or darkness of the backdrop. Example 1 Example 2 darken Selects the darker of the destination and source colors. The destination is replaced with the source only where the source is darker. Example 1 428 Example 2 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 lighten Selects the lighter of the destination and source colors. The destination is replaced with the source only where the source is lighter. Example 1 Example 2 color-dodge Brightens the destination color to reflect the source color. Drawing with black produces no changes. Example 1 Example 2 color-burn Darkens the destination color to reflect the source color. Drawing with white produces no change. 6.2. SLD Styling 429 GeoServer User Manual, Release 2.15.1 Example 1 Example 2 hard-light Multiplies or screens the colors, depending on the source color value. The effect is similar to shining a harsh spotlight on the destination. Example 1 Example 2 soft-light Darkens or lightens the colors, depending on the source color value. The effect is similar to shining a diffused spotlight on the destination. Example 1 430 Example 2 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 difference Subtracts the darker of the two constituent colors from the lighter color. White inverts the destination color; black produces no change. Example 1 Example 2 exclusion Produces an effect similar to that of difference but lower in contrast. White inverts the destination color; black produces no change. Example 1 Example 2 Compositing and blending example Let’s say we want to draw the topp:states layer so that the polygons are not filled with the population keyed colors, but only an inner border inside the polygon should appear, leaving the internal fully transparent. This is the destination: Using alpha blending, this can be achived by creating a mask around the state borders with a thick stroke, and then using a “destination-in” alpha compositing. This is the source (mask): The SLD will contain three FeatureTypeStyles. The first one would be the standard rules (states colored by population) and the last one 6.2. SLD Styling 431 GeoServer User Manual, Release 2.15.1 Fig. 6.87: topp:states layer Fig. 6.88: Layer mask 432 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 will contain the label rules. The second (middle) one is where the blending will occur: ... ,→ 10 #000000 destination-in ... ,→ This is the result of the composition: Now, if for example someone makes a WMS call in which the another layer is drawn below this one, the result will look like this: This other background layer is hardly visible, because it has been cut by the mask. This shows the risks of using alpha compositing without care in a WMS setting. In order to achieve the desired result no matter how the client composes the request, the first FeatureTypeStyle that draws the polygons (the states themselves) needs to be set as a compositing base, ensuring the mask will only be applied to it. 6.2. SLD Styling 433 GeoServer User Manual, Release 2.15.1 true The result will look like the following (though a multiply blend was added to the base to ensure a nice visual transparency effect on the border lines): Download the final style Note: See the full list of available modes. Z ordering features within and across feature types and layers Starting with GeoServer 2.8.0 it is possible to control the order in which the features are being loaded and painted on the map, thus replicating the same above/below relationships found in the reality. Enabling z-ordering in a single FeatureTypeStyle The z-ordering is implemented as a new FeatureTypeStyle vendor option, sortBy, which controls in which order the features are ex434 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 tracted from the data source, and thus painted. The sortBy syntax is the same as the WFS one, that is, a list of comma separated field names, with an optional direction modifier (ascending being the default): field1 [A|D], field2 [A|D], ... , fieldN [A|D] Some examples: • “z”: sorts the features based on the z field, ascending (lower z values are painted first, higher later) • “cat,z D”: sorts the features on the cat attribute, with ascending order, and for those that have the same cat value, the sorting is on descending z • “cat D,z D”: sorts the features on the cat attribute, with descending order, and for those that have the same cat value, the sorting is on descending z So, if we wanted to order features based on a single “elevation” attribute we’d be using the following SLD snippet: ... ... ... elevation ... z-ordering across FeatureTypeStyle It is a common need to perform road casing against a complex road network, which can have its own z-ordering needs (e.g., over and under passes). Casing is normally achieved by using two separate 6.2. SLD Styling 435 GeoServer User Manual, Release 2.15.1 two FeatureTypeStyle, one drawing a thick line, one drawing a thin one. Let’s consider a simple data set, made of just three roads: _=geom:LineString:404000,z:int Line.1=LINESTRING(0 4, 10 4)|1 Line.2=LINESTRING(0 6, 10 6)|3 Line.3=LINESTRING(7 0, 7 10)|1 Adding a “sortBy” rule to both FeatureTypeStyle objects will achieve no visible result: ,→ #FF0000 ,→ 8 ,→ z ,→ #FFFFFF ,→ 6 z ,→ The result will be the following: 436 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 This is happening because while the roads are loaded in the right order, Line.1,Line.3,Line.2, they are all painted with the tick link first, and then the code will start over, and paint them all with the thin line. In order to get both casing and z-ordering to work a new vendor option, sortByGroup, needs to be added to both FeatureTypeStyle, grouping them in a single z-ordering paint. 6.2. SLD Styling ,→ #FF0000 ,→ 8 437 GeoServer User Manual, Release 2.15.1 z roads ,→ ,→ #FFFFFF ,→ 6 z roads ,→ The result will be the following: 438 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 When grouping is used, the code will first paint Line.1,Line3 with the thick line, then track back and paint them with the thin line, then move to paint Line.2 with the thick line, and finally Line.2 with the thin line, achieving the desired result. z-ordering across layers Different layers, such for example roads and rails, can have their features z-ordered together by putting all the FeatureTypeStyle in their styles in the same sortByGroup, provided the following conditions are met: • The layers are side by side in the WMS request/layer group. In other words, the z-ordering allows to break the WMS specified order only if the layers are directly subsequent in the request. This can be extended to any number of layers, provided the progression of FeatureTypeStyle in the same group is not broken • There is no FeatureTypeStyle in the layer style that’s breaking the sequence Let’s consider an example, with a rails layer having two FeatureTypeStyle, one with a group, the other not: FeatureTypeStyle id rails1 rails2 SortByGroup id linework none We then have a roads layer with two FeatureTypeStyle, both in the same group: FeatureTypeStyle id road1 road2 SortByGroup id linework linework If the WMS request asks for &layers=roads,rails, then the expanded FeatureTypeStyle list will be: FeatureTypeStyle id road1 road2 rails1 rails2 SortByGroup id linework linework linework none As a result, the road1,road2,rails1 will form a single group, and this will result in the rails be merged with the roads when zordering. If instead the WMS request asks for &layers=rails,roads‘, then the expanded FeatureTypeStyle list will be: 6.2. SLD Styling 439 GeoServer User Manual, Release 2.15.1 FeatureTypeStyle id rails1 rails2 road1 road2 SortByGroup id linework none linework linework The rails2 feature type style breaks the sequence, as a result, the rails will not be z-ordered in the same group as the roads. Z ordering single layer example The OpenStreetMap dataset uses extensively a z_order attribute to model the above/below relationships between elements in the real world. A small downloadable shapefile is provided that shows a small area with a rich set of different z-orders, where roads and rails go above and below each other. For reference, this is the dataset schema: Name osm_id type Type numeric string bridge ref tunnel oneway z_order class numeric numeric numeric numeric numeric string Notes The type of the segment, can be “mainroads”, “minorroads”, “railways”, . . . 0 or 1 0 or 1 0 or 1 The dataset contains several different values for z_order, in particular: -10, -7, -5, -3, -1, 0, 3, 4, 5, 7, 9, 10, 13, 14, 15, 17, 19. Here is a sample CSS style using z-ordering, but not groups, to perform the display. Road casing is achieved by multiple FeatureTypeStyle, or z-index values in CSS: [class = 'railways' and bridge = 1] { stroke: #333333; stroke-width: 8; z-index: 0; } [class = 'minorroads'] { stroke: #a69269; stroke-width: 3; z-index: 0; } [class = 'mainroads'] { stroke: #ff0000; stroke-width: 5; 440 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 z-index: 0; } [class = 'motorways'] { stroke: #990000; stroke-width: 8; z-index: 0; } [class = 'railways' and bridge = 1] { stroke: #ffffff; stroke-width: 6; z-index: 1; } [class = 'railways'] { stroke: #333333; stroke-width: 3; z-index: 2; } [class = 'railways'] { stroke: #ffffff; stroke-width: 1.5; stroke-dasharray: 5, 5; z-index: 3; } [class = 'motorways'] { stroke: #ff6666; stroke-width: 6; stroke-linecap: round; z-index: 3; } [class = 'minorroads'] { stroke: #ffffff; stroke-width: 2,5; stroke-linecap: round; z-index: 3; } [class = 'mainroads'] { stroke: #ff9999; stroke-width: 4; stroke-linecap: round; z-index: 3; } * { sort-by: "z_order"; } The sorting is achieved by using the sort-by property, which translates into a sortBy VendorOption in SLD. A full equivalent SLD is available for download. This is the resulting map: 6.2. SLD Styling 441 GeoServer User Manual, Release 2.15.1 As one can see, there are evident issues: • Roads and rails are not showing any evident z-ordering, in fact, all rails are below roads, but their dashed white center shows a mix of below and above roads • The rails bridges (depicted with a third thicker line around the rail symbol) are consistently below some other road or rail, while they should be above. This is mostly happening because the various FeatureTypeStyle elements are not put doctor in a single group. A slight change in the CSS, grouping all levels in the same sortByGroup, solves the issues above: [class = 'railways' and bridge = 1] { stroke: #333333; stroke-width: 8; z-index: 0; } [class = 'minorroads'] { stroke: #a69269; stroke-width: 3; z-index: 0; } [class = 'mainroads'] { stroke: #ff0000; 442 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 stroke-width: 5; z-index: 0; } [class = 'motorways'] { stroke: #990000; stroke-width: 8; z-index: 0; } [class = 'railways' and bridge = 1] { stroke: #ffffff; stroke-width: 6; z-index: 1; } [class = 'railways'] { stroke: #333333; stroke-width: 3; z-index: 2; } [class = 'railways'] { stroke: #ffffff; stroke-width: 1.5; stroke-dasharray: 5, 5; z-index: 3; } [class = 'motorways'] { stroke: #ff6666; stroke-width: 6; stroke-linecap: round; z-index: 3; } [class = 'minorroads'] { stroke: #ffffff; stroke-width: 2,5; stroke-linecap: round; z-index: 3; } [class = 'mainroads'] { stroke: #ff9999; stroke-width: 4; stroke-linecap: round; z-index: 3; } * { sort-by: "z_order"; sort-by-group: "roadsGroup"; } A full equivalent SLD is also available for download. The result now shows proper z-ordering: 6.2. SLD Styling 443 GeoServer User Manual, Release 2.15.1 6.2.6 SLD Tips and Tricks This section details various advanced strategies for working with SLD. Styling mixed geometry types On occasion one might need to style a geometry column whose geometry type can be different for each feature (some are polygons, some are points, etc), and use different styling for different geometry types. SLD 1.0 does not provide a clean solution for dealing with this situation. Point, Line, and Polygon symbolizers do not select geometry by type, since each can apply to all geometry types: • Point symbolizers apply to any kind of geometry. If the geometry is not a point, the centroid of the geometry is used. • Line symbolizers apply to both lines and polygons. For polygons the boundary is styled. • Polygon symbolizers apply to lines, by adding a closing segment connecting the first and last points of the line. There is also no standard filter predicate to identify geometry type which could be used in rules. This section suggests a number of ways to accomplish styling by 444 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 geometry type. They require either data restructuring or the use of non-standard filter functions. Restructuring the data There are a few ways to restructure the data so that it can be styled by geometry type using only standard SLD constructs. Split the table The first and obvious one is to split the original table into a set of separate tables, each one containing a single geometry type. For example, if table findings has a geometry column that can contain point, lines, and polygons, three tables can be created, each one containing a single geometry type. Separate geometry columns A second way is to use one table and separate geometry columns. So, if the table findings has a geom column, the restructured table will have point, line and polygon columns, each of them containing just one geometry type. After the restructuring, the symbolizers will refer to a specific geometry, for example: ,→polygon This way each symbolizer will match only the geometry types it is supposed to render, and skip over the rows that contain a null value. Add a geometry type column A third way is to add a geometry type column allowing standard filtering constructs to be used, and then build a separate rule per geometry type. In the example above a new attribute, gtype will be added containing the values Point, Line and Polygon. The following SLD template can be used after the change: gtype Point ... 6.2. SLD Styling 445 GeoServer User Manual, Release 2.15.1 gtype Line ... gtype Polygon ... The above suggestions assume that restructuring the data is technically possible. This is usually true in spatial databases that provide functions that allow determining the geometry type. Create views A less invasive way to get the same results without changing the structure of the table is to create views that have the required structure. This allows the original data to be kept intact, and the views may be used for rendering. Using SLD rules and filter functions SLD 1.0 uses the OGC Filter 1.0 specification for filtering out the data to be styled by each rule. Filters can contain Filter functions to compute properties of geometric values. In GeoServer, filtering by geometry type can be done using the geometryType or dimension filter functions. Note: The Filter Encoding specification provides a standard syntax for filter functions, but does not mandate a specific set of functions. SLDs using these functions may not be portable to other styling software. geometryType function The geometryType function takes a geometry property and returns a string, which (currently) is one of the values Point, LineString, LinearRing, Polygon, MultiPoint, MultiLineString, MultiPolygon and GeometryCollection. 446 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Using this function, a Rule matching only single points can be written as: geom Point ... The filter is more complex if it has to match all linear geometry types. In this case, it looks like: geom LineString LinearRing MultiLineString true ... This filter is read as geometryType(geom) in ("LineString", "LinearRing", "MultiLineString"). Filter functions in Filter 1.0 have a fixed number of arguments, so there is a series of in functions whose names correspond to the number of arguments they accept: in2, in3, . . . , in10. dimension function A slightly simpler alternative is to use the geometry dimension function to select geometries of a desired dimension. Dimension 0 selects Points and MultiPoints, dimension 1 selects LineStrings, LinearRings and MultiLineStrings, and dimension 2 selects Polygons and MultiPolygons. The following example shows how to select linear geometries: geom 6.2. SLD Styling 447 GeoServer User Manual, Release 2.15.1 1 ... Styling using Transformation Functions The Symbology Encoding 1.1 specification defines the following transformation functions: • Recode transforms a set of discrete attribute values into another set of values • Categorize transforms a continuous-valued attribute into a set of discrete values • Interpolate transforms a continuous-valued attribute into another continuous range of values These functions provide a concise way to compute styling parameters from feature attribute values. GeoServer implements them as Filter functions with the same names. Note: The GeoServer function syntax is slightly different to the SE 1.1 definition, since the specification defines extra syntax elements which are not available in GeoServer functions. These functions can make style documents more concise, since they express logic which would otherwise require many separate rules or complex Filter expressions, They even allow logic which is impossible to express any other way. A further advantage is that they often provide superior performance to explicit rules. One disadvantage of using these functions for styling is that they are not displayed in WMS legend graphics. Recode The Recode filter function transforms a set of discrete values for an attribute into another set of values. The function can be used within SLD styling parameters to convert the value of a feature attribute into specific values for a parameter such as color, size, width, opacity, etc. The recoding is defined by a set of (input, output) value pairs. Example Consider a chloropleth map of the US states dataset using the fill color to indicate the topographic regions for the states. The dataset has an attribute SUB_REGION containing the region code for each state. The Recode function is used to map each region code into a different color. 448 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 The symbolizer for this style is: ,→ SUB_REGION N Eng #6495ED Mid Atl #B0C4DE S Atl #00FFFF E N Cen #9ACD32 E S Cen #00FA9A W N Cen #FFF8DC W S Cen #F5DEB3 Mtn #F4A460 Pacific #87CEEB This style produces the following output: 6.2. SLD Styling 449 GeoServer User Manual, Release 2.15.1 Categorize The Categorize filter function transforms a continuous-valued attribute into a set of discrete values. The function can be used within SLD styling parameters to convert the value of a feature attribute into specific values for a parameter such as color, size, width, opacity, etc. The categorization is defined by a list of alternating output values and data thresholds. The threshold values define the breaks between the input ranges. Inputs are converted into output values depending on which range they fall in. Example Consider a chloropleth map of the US states dataset using the fill color to indicate a categorization of the states by population. The dataset has attributes PERSONS and LAND_KM from which the population density is computed using the Div operator. This value is input to the Categorize function, which is used to assign different colors to the density ranges [ <= 20], [20 - 100], and [ > 100]. The symbolizer for this style is: PERSONS LAND_KM #87CEEB 20 #FFFACD 100 #F08080 This style produces the following output: Interpolate The Interpolate filter function transforms a continuous-valued attribute into another continuous range of values. The function can be used within SLD styling parameters to convert the value of a feature attribute into a continuous-valued parameter such as color, size, width, opacity, etc. 450 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 The transformation is defined by a set of (input, output) control points chosen along a desired mapping curve. Piecewise interpolation along the curve is used to compute an output value for any input value. The function is able to compute either numeric or color values as output. This is known as the interpolation method, and is specified by an optional parameter with a value of numeric (the default) or color. The shape of the mapping curve between control points is specified by the interpolation mode, which is an optional parameter with values of linear (the default), cubic, or cosine. Example Interpolating over color ranges allows concise definition of continuously-varying colors for chloropleth (thematic) maps. As an example, consider a map of the US states dataset using the fill color to indicate the population of the states. The dataset has an attribute PERSONS containing the population of each state. The population values lie in the range 0 to around 30,000,000. The interpolation curve is defined by three control points which assign colors to the population levels 0, 9,000,000 and 23,000,000. The colors for population values are computed by piecewise linear interpolation along this curve. For example, a state with a population of 16,000,000 is displayed with a color midway between the ones for the middle and upper control points. States with populations greater than 23,000,000 are displayed with the last color. Because the interpolation is being performed over color values, the method parameter is supplied, with a value of color. Since the default linear interpolation is used, no interpolation mode is supplied, The symbolizer for this style is: PERSONS 6.2. SLD Styling 451 GeoServer User Manual, Release 2.15.1 0 #fefeee ,→ 9000000 #00ff00 23000000 #ff0000 color ,→ This symbolizer produces the following output: 6.2.7 i18N in SLD This section describes how to specify metadata (titles and abstracts) in different languages in SLD documents. Metadata in different languages GeoServer extends Title and Abstract sections, so that text in different languages can be included. This is an example of the syntax to use: This is the default title <Localized lang="en">English title</Localized> <Localized lang="it">Titolo in italiano</Localized> A default text (This is the default title in the example) and a set of Localized sections, one for each language that you want to support. 452 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Each Localized section specifies the language (using a two letter abbreviation in the lang attribute) and the related text. Currently, GeoServer supports localized text in SLD in WMS GetLegendGraphic requests (legends that contain labels are rendered using the requested language, if a LANGUAGE parameter is added to the request, e.g. LANGUAGE=it). 6.3 Generating SLD styles with QGIS QGIS includes a sophisticated style editor with many map rendering possibilities. Styles generated with QGIS can then be exported (with limitations) to SLD for usage with GeoServer. QGIS style exporting abilities have been evolving over time, as a reference: • For vector data QGIS exports SLD 1.1 styles that can be read by GeoServer. In order to get the suitable results it’s important to use QGIS 3.0 or newer, and GeoServer 2.13.x or newer. • Raster data styling export is new in QGIS 3.4.5 (yet to be released at the time of writing). This new version exports SLD 1.0 styles with vendor extensions to support constrast streching that most recent GeoServer versions support properly. For older QGIS versions limited export functionality is available using the SLD4Raster plugin. For the export it is advised to use the Save As functionality available in the style dialog, as indicated below in this guide. Other plugins exist that streamline the export process, but they may ruin the style trying to adapt it to older GeoServer versions (e.g., translating it down to SLD 1.0 by simple text processing means), or rewrite it entirely. Warning: Despite the progress in the last years, it is known that not all QGIS rendering options are supported by SLD and/or by GeoServer (e.g. shapeburst symbology), and that support for exporting some parts is simply missing (e.g.. expression based symbology is supported in SLD, but QGIS won’t export it). If you are interested, both projects would welcome sponsoring to improve the situation. 6.3.1 Exporting vector symbology This is a step by step guide to style a GeoServer demo layer, sfdem. 1. Open QGIS (minimum version 3.0) 2. Load the states.shp dataset from the GeoServer data directory, /data/shapefiles/states.shp 3. Double click the layer to open the Properties dialog and switch to the Symbology page. 4. Choose a Graduated rendering, on the PERSONS column, and click on Classify button to generate 1.5 standard deviations, select the spectral 6.3. Generating SLD styles with QGIS 453 GeoServer User Manual, Release 2.15.1 color ramp, switch mode to Quantile and finally and click on the “Classify button to generate a 5 classes map, as shown in figure. Fig. 6.89: QGIS vector styling 5. Switch to the Labels page, choose Single labels‘, label with the STATE NAME attribute and choose your preferred text rendering options, as shown in figure 6. The layer renders as follows: 7. Go back At the Properties dialog, from the bottom of the Styles page, choose Style → Save Style. 8. Choose export in the SLD format, placing the file in the desired location. 9. Go in GeoServer, create a new style, use the Upload a new style dialog to choose the exported file, and click on upload link. 10. Click on guilabel:Apply. 11. Change to the Layer preview tab, click on the Preview on Layer link to choose topp:states to verify proper rendering. 12. Eventually switch to the Publishing tab, search for states, and select Default or Associated checkbox to publish the layer to use the new style permanently. 6.3.2 Exporting raster symbology This is a step by step guide to style a GeoServer demo layer, sfdem. 1. Open QGIS (minimum version 3.4.5) 454 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.90: QGIS labelling Fig. 6.91: QGIS raster styling Fig. 6.92: Export using Save As. . . 6.3. Generating SLD styles with QGIS 455 GeoServer User Manual, Release 2.15.1 Fig. 6.93: Choosing export format. . . Fig. 6.94: Uploading style in GeoServer. . . 456 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.95: Previewing style in GeoServer. . . Fig. 6.96: Associating style in GeoServer. . . 6.3. Generating SLD styles with QGIS 457 GeoServer User Manual, Release 2.15.1 2. Load the sfdem.tif raster from the GeoServer data directory, /data/sf/sfdem.tif 3. Double click the layer to open the Properties dialog and switch to the Symbology page. 4. Choose a Singleband pseudocolor rendering, Generate Min / Max Value Settings using Mean +/- standard deviation with using 1.5 standard deviations. Generate a 5 classes Linear interpolated map, as shown in figure. Fig. 6.97: QGIS raster styling 5. The layer renders as follows: 6. Return to the layer’s Properties dialog Symbology page, at the bottom of the page choose Style → Save Style. 458 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.98: QGIS raster styling Fig. 6.99: Export using Save As. . . 6.3. Generating SLD styles with QGIS 459 GeoServer User Manual, Release 2.15.1 7. Choose export in the SLD format, placing the file in the desired location Fig. 6.100: Choosing export format. . . 8. Go in GeoServer, create a new style, use the Upload a new style dialog to choose the exported file, and click on upload link. Fig. 6.101: Uploading style in GeoServer. . . 9. Click on guilabel:Apply then change to the Layer preview tab. Click on the Preview on Layer link to choose sfdem to verify proper rendering. 10. Finally switch to the Publishing tab, search for sfdem layer, and select Default or Associated checkbox to publish sfdem with the new style. 6.4 CSS Styling The CSS extension uses a CSS-derived language instead of SLD. These CSS styles are internally converted to SLD, which is then used as normal by GeoServer. The CSS syntax is duplicated from SVG styling where appropriate, but extended to avoid losing facilities provided by SLD when possible. CSS is not a part of GeoServer by default, but is available as an extension. 460 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.102: Previewing style in GeoServer. . . Fig. 6.103: Associating style in GeoServer. . . 6.4. CSS Styling 461 GeoServer User Manual, Release 2.15.1 6.4.1 Installation The CSS extension is listed among the other extension downloads on the GeoServer download page. The installation process is similar to other GeoServer extensions: 1. Download the appropriate archive from the GeoServer download page. Please verify that the version number in the filename corresponds to the version of GeoServer you are running. The file will be called geoserver-A.B.C-css-plugin.zip where A.B.C is the GeoServer version. 2. Extract the contents of the archive into the WEB-INF/lib directory in GeoServer. Make sure you do not create any sub-directories during the extraction process. 3. Restart GeoServer. If installation was successful, you will see a new CSS entry in the Styles editor. Fig. 6.104: CSS format in the new style page After installation, you may wish to read the tutorial: Styling data with CSS. 6.4.2 Tutorial: Styling data with CSS This tutorial will show using CSS to style a layer, along with the equivalent SLD code. To use this tutorial, you will need the CSS extension as well as the states layer from the default GeoServer configuration. Creating a style for the states layer The SLD file for the default states layer looks like this: 462 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 USA states population population Population in the United States A sample ,→filter that filters the United States into three categories ,→of population, drawn in different colors < 2M PERSONS 2000000 ,→ 6.4. CSS Styling ,→ #4DFF4D ,→ 0.7 2M - 4M ,→ PERSONS 2000000 4000000 463 GeoServer User Manual, Release 2.15.1 ,→ ,→ #FF4D4D ,→ 0.7 > 4M ,→ PERSONS 4000000 ,→ ,→ #4D4DFF ,→ 0.7 Boundary ,→ 0.2 Times New Roman ,→ Normal ,→ ,→ 464 14 0.5 0.5 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Now, let’s start on a CSS file that accomplishes the same thing. First, got to the styles page and click on Add a new style link to start a new style. In the “New style” page, do the following: • Name the new style anything you’d like, such as csstutorial • Choose CSS as the format • In the Generate a default style dropdown choose Polygon and click on Generate. . . Fig. 6.105: Creating a new CSS style This creates an example style with a source similar to this one (the colors may differ): /* @title cyan polygon */ * { stroke: #000000; stroke-width: 0.5; 6.4. CSS Styling 465 GeoServer User Manual, Release 2.15.1 fill: #0099cc; } This demonstrates the basic elements of a CSS style: A selector that identifies some part of the data to style. Here, the selector is *, indicating that all data should use the style properties. Properties inside curly braces ({}) which specify how the affected features should be styled. Properties consist of name/value pairs separated by colons (:). We can also see the basics for styling a polygon (fill), and its outline (stroke). See also: The Filter syntax and Property listing pages provide more information about the options available in CSS styles. Before moving on, let’s save the style and preview it with the states layer: • Click on “Apply” to save the layer and enable the style preview • Now on the “Style Editor page”, switch to the “layer preview” tab and click on the “previewing on layer” link, then choose the “states” layer in the dialog • The style editor should now show the states layer filled and stroked Fig. 6.106: Previewing the CSS style with the state layer Let’s use these basics to start translating the states style. The first rule in the SLD applies to states where the PERSONS field is less than two million: 466 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 < 2M PERSONS 2000000 ,→ #4DFF4D 0.7 ,→ Using a CQL-based selector, and copying the names and values of the CssParameters over, we get: [PERSONS < 2000000] { fill: #4DFF4D; fill-opacity: 0.7; } For the second style, we have a PropertyIsBetween filter, which doesn’t directly translate to CSS: 2M - 4M PERSONS 2000000 4000000 ,→ #FF4D4D 0.7 ,→ However, PropertyIsBetween can easily be replaced by a combination of two comparison selectors. In CSS, you can apply multiple 6.4. CSS Styling 467 GeoServer User Manual, Release 2.15.1 selectors to a rule by simply placing them one after the other. Selectors separated by only whitespace must all be satisfied for a style to apply. Multiple such groups can be attached to a rule by separating them with commas (,). If a feature matches any of the commaseparated groups for a rule then that style is applied. Thus, the CSS equivalent of the second rule is: [PERSONS >= 2000000] [PERSONS < 4000000] { fill: #FF4D4D; fill-opacity: 0.7; } The third rule can be handled in much the same manner as the first: [PERSONS >= 4000000] { fill: #4D4DFF; fill-opacity: 0.7; } The fourth and final rule is a bit different. It applies a label and outline to all the states: Boundary 0.2 Times New Roman ,→ Normal 14 0.5 0.5 ,→ This introduces the idea of rendering an extracted value (STATE_ABBR) directly into the map, unlike all of the rules thus far. For this, you can use a CQL expression wrapped in square braces ([]) as the value of a CSS property. It is also necessary to surround values containing whitespace, such as Times New Roman, with single- or double-quotes (", '). With these details in mind, 468 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 let’s write the rule: * { stroke-width: 0.2; label: [STATE_ABBR]; label-anchor: 0.5 0.5; font-family: "Times New Roman"; font-fill: black; font-style: normal; font-size: 14; } Putting it all together, you should now have a style that looks like: [PERSONS < 2000000] { fill: #4DFF4D; fill-opacity: 0.7; } [PERSONS >= 2000000] [PERSONS < 4000000] { fill: #FF4D4D; fill-opacity: 0.7; } [PERSONS >= 4000000] { fill: #4D4DFF; fill-opacity: 0.7; } * { stroke-width: 0.2; label: [STATE_ABBR]; label-anchor: 0.5 0.5; font-family: "Times New Roman"; font-fill: black; font-style: normal; font-size: 14; } Click the Apply button at the bottom of the form to save your changes. You will see that the borders are missing! In the GeoServer CSS module, each type of symbolizer has a “key” property which controls whether it is applied. Without these “key” properties, subordinate properties are ignored. These “key” properties are: • fill, which controls whether or not Polygon fills are applied. This specified the color or graphic to use for the fill. • stroke, which controls whether or not Line and Polygon outline strokes are applied. This specifies the color (or graphic fill) of the stroke. • mark, which controls whether or not point markers are drawn. This identifies a Well-Known Mark or image URL to use. • label, which controls whether or not to draw labels on the map. This identifies the text to use for labeling the map, usually as a CQL expression. 6.4. CSS Styling 469 GeoServer User Manual, Release 2.15.1 Fig. 6.107: CSS style applied to the states layer 470 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 • halo-radius, which controls whether or not to draw a halo around labels. This specifies how large such halos should be. See also: The Property listing page for information about the other properties. Since we don’t specify a stroke color, no stroke is applied. Let’s add it, replacing the final rule so that it will now look like this: * { stroke: black; stroke-width: 0.2; label: [STATE_ABBR]; label-anchor: 0.5 0.5; font-family: "Times New Roman"; font-fill: black; font-style: normal; font-size: 14; } Fig. 6.108: Border added to style Refining the style Removing duplicated properties The style that we have right now is only 23 lines, a nice improvement over the 103 lines of XML that we started with. However, we are still repeating the fill-opacity attribute everywhere. We can move it into the * rule and have it applied everywhere. This works because the GeoServer CSS module emulates cascading: While SLD uses a “painter’s model” where each rule is processed independently, a cascading style allows you to provide general style properties and override only specific properties for particular features. This brings the style down to only 21 lines: 6.4. CSS Styling 471 GeoServer User Manual, Release 2.15.1 [PERSONS < 2000000] { fill: #4DFF4D; } [PERSONS > 2000000] [PERSONS < 4000000] { fill: #FF4D4D; } [PERSONS > 4000000] { fill: #4D4DFF; } * { fill-opacity: 0.7; stroke-width: 0.2; label: [STATE_ABBR]; label-anchor: 0.5 0.5; font-family: "Times New Roman"; font-fill: black; font-style: normal; font-size: 14; } Scale-dependent styles The labels for this style are nice, but at lower zoom levels they seem a little crowded. We can easily move the labels to a rule that doesn’t activate until the scale denominator is below 2000000. We do want to keep the stroke and fill-opacity at all zoom levels, so we can separate them from the label properties. Keep the following properties in the main (*) rule: * { fill-opacity: 0.7; stroke-width: 0.2; } Remove all the rest, moving them into a new rule: [@sd < 20M] { label: [STATE_ABBR]; label-anchor: 0.5 0.5; font-family: "Times New Roman"; font-fill: black; font-style: normal; font-size: 14; } Setting titles for the legend So far, we haven’t set titles for any of the style rules. This doesn’t really cause any problems while viewing maps, but GeoServer uses the title in auto-generating legend graphics. Without the titles, 472 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 GeoServer falls back on the names, which in the CSS module are generated from the filters for each rule. Titles are not normally a part of CSS, so GeoServer looks for them in specially formatted comments before each rule. We can add titles like this: /* @title Population < 2M */ [PERSONS < 2000000] { ... /* @title 2M < Population < 4M */ [PERSONS > 2000000] [PERSONS < 4000000] { ... /* @title Population > 4M */ [PERSONS > 4000000] { ... /* @title Boundaries */ * { ... Because of the way that CSS is translated to SLD, each SLD rule is a combination of several CSS rules. This is handled by combining the titles with the word “with”. If the title is omitted for a rule, then it is simply not included in the SLD output. The final CSS should looks like this: /* @title Population < 2M */ [PERSONS < 2000000] { fill: #4DFF4D; fill-opacity: 0.7; } /* @title 2M < Population < 4M */ [PERSONS >= 2000000] [PERSONS < 4000000] { fill: #FF4D4D; fill-opacity: 0.7; } /* @title Population > 4M */ [PERSONS >= 4000000] { fill: #4D4DFF; fill-opacity: 0.7; } /* @title Boundaries */ * { stroke: black; stroke-width: 0.2; fill-opacity: 0.7; } 6.4. CSS Styling 473 GeoServer User Manual, Release 2.15.1 [@sd < 20M] { label: [STATE_ABBR]; label-anchor: 0.5 0.5; font-family: "Times New Roman"; font-fill: black; font-style: normal; font-size: 14; } Fig. 6.109: Final style with rule names Applying rule nesting As a final variation, the style can be made more compact by leveraging rule nesting: * { stroke: black; stroke-width: 0.2; fill-opacity: 0.7; /* @title Population < 2M */ [PERSONS < 2000000] { fill: #4DFF4D; }; /* @title 2M < Population < 4M */ [PERSONS >= 2000000] [PERSONS < 4000000] { fill: #FF4D4D; }; /* @title Population > 4M */ [PERSONS >= 4000000] { fill: #4D4DFF; }; /* Labelling */ [@sd < 20M] { label: [STATE_ABBR]; label-anchor: 0.5 0.5; 474 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 font-family: "Times New Roman"; font-fill: black; font-style: normal; font-size: 14; } } CSS Workshop For more details, visit the next section, the CSS workshop. This workshop has been used in the past for classroom settings to teach the CSS extension and has been ported to the user documentation. 6.4.3 Filter syntax Filters limit the set of features affected by a rule’s properties. There are several types of simple filters, which can be combined to provide more complex filters for rules. Combining filters Combination is done in the usual CSS way. A rule with two filters separated by a comma affects any features that match either filter, while a rule with two filters separated by only whitespace affects only features that match both filters. Here’s an example using a basic attribute filter (described below): /* Matches places where the lake is flooding */ [rainfall>12] [lakes>1] { fill: black; } /* Matches wet places */ [rainfall>12], [lakes>1] { fill: blue; } When writing a selector that uses both and and or combinators, remember that the and combinator has higher precedence. For example: restricted [cat='2 ,→'], [cat='3'], [cat='4'] [@sd <= 200k] [@sd > 100k] { fill: #EE0000; } The above selector should be read as: • typename is ‘restricted’ and cat='2' or • cat='3' or • cat='4' and scale is between 100000 and 200000 6.4. CSS Styling 475 GeoServer User Manual, Release 2.15.1 If instead the intention was to combine in or just the three cat filters, the right syntax would have been: restricted [cat='2 ,→' or cat='3' or cat='4'] [@sd <= 200k] [@sd > 100k] { fill: #EE0000; } Which should be read as: • typename is ‘restricted’ and • (cat='2' or cat='3' or cat='4') and • scale is between 100000 and 200000 Filtering on data attributes An attribute filter matches some attribute of the data (for example, a column in a database table). This is probably the most common type of filter. An attribute filter takes the form of an attribute name and a data value separated by some predicate operator (such as the less-than operator <). Supported predicate operators include the following: Operator = <> > >= < <= LIKE Meaning The property must be exactly equal to the specified value. The property must not be exactly equal to the specified value. The property must be greater than (or alphabetically later than) the specified value. The property must be greater than or equal to the specified value. The property must be less than (or alphabetically earlier than) the specified value. The property must be less than or equal to the specified value. The property must match the pattern described by the specified value. Patterns use _ to indicate a single unspecified character and % to indicate an unknown number of unspecified characters. For example, to only render outlines for the states whose names start with letters in the first half of the alphabet, the rule would look like: [STATE_NAME<='M'] { stroke: black; } Note: The current implementation of property filters uses ECQL syntax, described on the GeoTools documentation. Filtering on type When dealing with data from multiple sources, it may be useful to provide rules that only affect one of those sources. This is done very simply; just specify the name of the layer as a filter: 476 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 states { stroke: black; } Filtering by ID For layers that provide feature-level identifiers, you can style specific features simply by specifying the ID. This is done by prefixing the ID with a hash sign (#): #states.2 { stroke: black; } Note: In CSS, the . character is not allowed in element ids; and the #states.foo selector matches the element with id states only if it also has the class foo. Since this form of identifier comes up so frequently in GeoServer layers, the CSS module deviates from standard CSS slightly in this regard. Future revisions may use some form of munging to avoid this deviation. Filtering by rendering context (scale) Often, there are aspects of a map that should change based on the context in which it is being viewed. For example, a road map might omit residential roads when being viewed at the state level, but feature them prominently at the neighborhood level. Details such as scale level are presented as pseudo-attributes; they look like property filters, but the property names start with an @ symbol: [roadtype = 'Residential'][@sd > 100k] { stroke: black; } The context details that are provided are as follows: Pseudo-Attribute @sd @scale Meaning The scale denominator for the current rendering. More explicitly, this is the ratio of real-world distance to screen/rendered distance. Same as above, the scale denominator (not scale) for the current rendering. Supported for backwards compatibility The scale value can be expressed as a plain number, for for brevity and readability the suffixes k (kilo), M (mega), G (giga) can be used, for example: [@sd > 100k] [@sd < 12M] [@sd < 1G] 6.4. CSS Styling 477 GeoServer User Manual, Release 2.15.1 Note: While property filters (currently) use the more complex ECQL syntax, pseudo-attributes cannot use complex expressions and MUST take the form of . Filtering symbols When using symbols to create graphics inline, you may want to apply some styling options to them. You can specify style attributes for built-in symbols by using a few special selectors: PseudoSelector :mark :stroke :fill :symbol :nth-mark(n) :nth-stroke(n) :nth-fill(n) :nth-symbol(n) Meaning specifies that a rule applies to symbols used as point markers specifies that a rule applies to symbols used as stroke patterns specifies that a rule applies to symbols used as fill patterns specifies that a rule applies to any symbol, regardless of which context it is used in specifies that a rule applies to the symbol used for the nth stacked point marker on a feature. specifies that a rule applies to the symbol used for the nth stacked stroke pattern on a feature. specifies that a rule applies to the symbol used for the nth stacked fill pattern on a feature. specifies that a rule applies to the symbol used for the nth stacked symbol on a feature, regardless of which context it is used in. For more discussion on using these selectors, see Styled marks. Global rules Sometimes it is useful to have a rule that matches all features, for example, to provide some default styling for your map (remember, by default nothing is rendered). This is accomplished using a single asterisk * in place of the usual filter. This catch-all rule can be used in complex expressions, which may be useful if you want a rule to provide defaults as well as overriding values for some features: * { stroke: black; } 6.4.4 Metadata One feature that appears in SLD that has no analog in CSS is the ability to provide metadata for styles and style rules. For example, this SLD embeds a title for its single rule: Country Borders borders Country Borders Borders of ,→countries, in an appropriately sovereign aesthetic. Borders ,→ 0.2 ,→ Software such as GeoServer can use this metadata to automatically generate nice legend images directly from the style. You don’t have to give up this ability when styling maps in CSS; just add comment before your rules including lines that start with @title and @abstract. Here is the analogous style in CSS: /* * @title This is a point layer. * @abstract This is an abstract point layer. */ * { mark: mark(circle); } Rules can provide either a title, an abstract, both, or neither. The SLD Name for a rule is autogenerated based on the filters from the CSS rules that combined to form it, for aid in troubleshooting. Combined rules One thing to keep in mind when dealing with CSS styles is that multiple rules may apply to the same subset of map features, especially as styles get more complicated. Metadata is inherited similarly to CSS properties, but metadata fields are combined instead of over- 6.4. CSS Styling 479 GeoServer User Manual, Release 2.15.1 riding less specific rules. That means that when you have a style like this: /* @title Borders */ * { stroke: black; } /* @title Parcels */ [category='parcel'] { fill: blue; } The legend entry for parcels will have the title 'Parcels with Borders'. If you don’t like this behavior, then only provide titles for the most specific rules in your style. (Or, suggest something better in an issue report!) Rules that don’t provide titles are simply omitted from title aggregation. 6.4.5 Multi-valued properties When rendering maps, it is sometimes useful to draw the same feature multiple times. For example, you might want to stroke a roads layer with a thick line and then a slimmer line of a different color to create a halo effect. In GeoServer’s css module, all properties may have multiple values. There is a distinction between complex properties, and multivalued properties. Complex properties are separated by spaces, while multi-valued properties are separated by commas. So, this style fills a polygon once: * { fill: url("path/to/img.png") red; } Using red as a fallback color if the image cannot be loaded. If you wanted to draw red on top of the image, you would have to style like so: * { fill: url("path/to/img.png"), red; /* set a transparency for the second fill, leave the first fully opaque. */ fill-opacity: 100%, 20%; } For each type of symbolizer (fill, mark, stroke, and label) the number of values determines the number of times the feature will be drawn. For example, you could create a bulls-eye effect by drawing multiple circles on top of each other with decreasing sizes: * { ,→ 480 mark: symbol(circle), symbol(circle), symbol(circle), symbol(circle); mark-size: 40px, 30px, 20px, 10px; Chapter 6. Styling GeoServer User Manual, Release 2.15.1 } If you do not provide the same number of values for an auxiliary property, the list will be repeated as many times as needed to finish. So: * { ,→ mark: symbol(circle), symbol(circle), symbol(circle), symbol(circle); mark-size: 40px, 30px, 20px, 10px; mark-opacity: 12%; } makes all those circles 12% opaque. (Note that they are all drawn on top of each other, so the center one will appear 4 times as solid as the outermost one.) Inheritance For purposes of inheritance/cascading, property lists are treated as indivisible units. For example: * { stroke: red, green, blue; stroke-width: 10px, 6px, 2px; } [type='special'] { stroke: pink; } This style will draw the ‘special’ features with only one outline. It has stroke-width: 10px, 6px, 2px; so that outline will be 10px wide. 6.4.6 Property listing This page lists the supported rendering properties. See CSS value types for more information about the value types for each. 6.4. CSS Styling 481 GeoServer User Manual, Release 2.15.1 Point symbology Property Type mark url, symbol mark-composite string mark-mime string (MIME Type) mark-geometry expression mark-size length mark-rotation angle z-index integer mark-label-obstacle boolean 482 Meaning The image or well-known shape to render for points The composite mode to be used and the optional opacity separated with a comma. See the full list of available modes. The type of the image referenced by a url() An expression to use for the geometry when rendering features The width to assume for the provided image. The height will be adjusted to preserve the source aspect ratio. A rotation to be applied (clockwise) to the mark image. Controls the z ordering of output If true the point symbol will be consider an obstable for labels, no label will overlap it Accepts Expression? yes no No, defaults to ‘image/jpeg’ yes yes yes no no Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Line symbology Property Type color, symbol stroke-composite string stroke Meaning url, stroke-geometry expression stroke-offset expression stroke-mime string (MIME Type) stroke-opacity percentage stroke-widthlength stroke-size length stroke-rotation angle stroke-linecap keyword: butt, square, round stroke-linejoin keyword: miter, round, bevel stroke-dasharray list of lengths stroke-dashoffset length stroke-repeat keyword: repeat, stipple z-index integer stroke-label-obstacle boolean 6.4. CSS Styling The color, graphic, or well-known shape to use to stroke lines or outlines The composite mode to be used and the optional opacity separated with a comma. See the full list of available modes. An expression to use for the geometry when rendering features. Draws a parallel line using the specified distance, positive values offset left, negative right. The type of the image referenced by a url() A value in the range of 0 (fully transparent) to 1.0 (fully opaque) The width to use for stroking the line. An image or symbol used for the stroke pattern will be stretched or squashed to this size before rendering. If this value differs from the stroke-width, the graphic will be repeated or clipped as needed. A rotation to be applied (clockwise) to the stroke image. See also the stroke- repeat property. The style to apply to the ends of lines drawn Accepts Expression? yes no yes yes No, defaults to ‘image/jpeg’ yes yes yes yes yes The style to apply to the “elbows” where segments of multiline features meet. yes The lengths of segments to use in a dashed line. no How far to offset the dash pattern from the ends of the lines. How to use the provided graphic to paint the line. If repeat, then the graphic is repeatedly painted along the length of the line (rotated appropriately to match the line’s direction). If stipple, then the line is treated as a polygon to be filled. Controls the z ordering of output If true the line will be consider an obstable for labels, no label will overlap it yes| yes no no 483 GeoServer User Manual, Release 2.15.1 Polygon symbology Property Type color, symbol fill-composite string fill Meaning url, fill-geometry expression fill-mime string (MIME Type) The color, graphic, or well-known shape to use to stroke lines or outlines The composite mode to be used and the optional opacity separated with a comma. See the full list of available modes. An expression to use for the geometry when rendering features. The type of the image referenced by a url() A value in the range of 0 (fully transparent) to 1.0 (fully opaque) fill-size length The width to assume for the image or graphic provided. fill-rotation angle A rotation to be applied (clockwise) to the fill image. z-index integer Controls the z ordering of output fill-label-obstacle boolean If true the polygon will be consider an obstable for labels, no label will overlap it graphic-margin List of A list of 1 to 4 values, specifying the space between repeated lengths graphics in a texture paint. One value is uniform spacing in all directions, two values are considered top/bottom and right/left, three values are considered top, right/left, bottom, four values are read as top,right,bottom,left. random none,grid,free Activates random distribution of symbols in a texture fill tile. See Fills with randomized symbols for details. Defaults to “none” random-seed integer num- The seed for the random generator. Defaults to 0 ber random-rotation none/free When set to “free” activates random rotation of the symbol in addition to random distribution. Defaults to “none” random-symbol-count positive inte- Number of suymbols to be placed in the texture fill tile. May ger number not be respected due to location conflicts (no two symbols are allowed to overlap). Defaults to 16. random-tile-size positive inte- Size of the texture paint tile that will be filled with the random ger number symbols. Defaults to 256. fill-opacitypercentage 484 Accepts Expression? yes no yes No, defaults to ‘image/jpeg’ yes yes yes no no no no no no no no Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Text symbology (labeling) - part 1 Property Type label string label-geometry expression label-anchorexpression label-offsetexpression label-rotation expression label-z-index expression mark, symbol shield-mime string (MIME Type) shield font-family string font-fill fill font-style keyword: normal, italic, oblique font-weight keyword: normal, bold font-size length halo-radius length Meaning The text to display as labels for features An expression to use for the geometry when rendering features. The part of the label to place over the point or middle of the polygon. This takes 2 values - x y where x=0 is the left edge of the label, x=1 is the right edge. y=0 is the bottom edge of the label, y=1 is the top edge. Specify 0.5 0.5 to centre a label. This is for fine-tuning label-anchor. x and y values specify pixels to adjust the label position. For lines, a single value will make the label be parallel to the line, at the given distance, while two values will force a point style placement, with the label painted horizonally at the center of the line (plus the given offsets) Clockwise rotation of label in degrees. Used to determine which labels are drawn on top of other labels. Lower z-indexes are drawn on top. A graphic to display behind the label, such as a highway shield. The type of the image referenced by a url() yes yes yes yes yes The name of the font or font family to use for labels The fill to use when rendering fonts The style for the lettering No, defaults to ‘image/jpeg’ yes yes yes The weight for the lettering yes The size for the font to display. The size of a halo to display around the lettering (to enhance readability). This is required to activate the halo feature. halo-color color The color for the halo halo-opacitypercentage The opacity of the halo, from 0 (fully transparent) to 1.0 (fully opaque). label-padding length The amount of ‘padding’ space to provide around labels. Labels will not be rendered closer together than this threshold. This is equivalent to the spaceAround vendor parameter. label-group one of: true If true, the render will treat features with the same label text or false as a single feature for the purpose of labeling. This is equivalent to the group vendor parameter. label-max-displacement length If set, this is the maximum displacement that the renderer will apply to a label. Labels that need larger displacements to avoid collisions will simply be omitted. This is equivalent to the maxDisplacement vendor parameter. 6.4. CSS Styling Accepts Expression? yes yes yes yes yes yes no no no 485 GeoServer User Manual, Release 2.15.1 Text symbology (labeling) - part 2 Property Type Meaning label-min-group-distance length This is equivalent to the minGroupDistance vendor parameter in SLD. label-repeatlength If set, the renderer will repeat labels at this interval along a line. This is equivalent to the repeat vendor parameter. label-all-group one of true when using grouping, whether to label only the longest line or false that could be built by merging the lines forming the group, or also the other ones. This is equivalent to the allGroup vendor parameter. label-remove-overlaps one of true If enabled, the renderer will remove overlapping lines within or false a group to avoid duplicate labels. This is equivalent to the removeOverlaps vendor parameter. label-allow-overruns one of true Determines whether the renderer will show labels that are or false longer than the lines being labelled. This is equivalent to the allowOverrun vendor parameter. label-follow-line one of true If enabled, the render will curve labels to follow the lines beor false ing labelled. This is equivalent to the followLine vendor parameter. label-max-angle-delta one of true The maximum amount of curve allowed between two charor false acters of a label; only applies when ‘follow-line: true’ is set. This is equivalent to the maxAngleDelta vendor parameter. label-auto-wrap length Labels will be wrapped to multiple lines if they exceed this length in pixels. This is equivalent to the autoWrap vendor parameter. label-force-ltr one of true By default, the renderer will flip labels whose normal orienor false tation would cause them to be upside-down. Set this parameter to false if you are using some icon character label like an arrow to show a line’s direction. This is equivalent to the forceLeftToRight vendor parameter. label-conflict-resolution one of true Set this to false to disable label conflict resolution, allowing or false overlapping labels to be rendered. This is equivalent to the conflictResolution vendor parameter. label-fit-goodness scale The renderer will omit labels that fall below this “match quality” score. The scoring rules differ for each geometry type. This is equivalent to the goodnessOfFit vendor parameter. label-priority expression Specifies an expression to use in determining which features to prefer if there are labeling conflicts. This is equivalent to the Priority SLD extension. 486 Accepts Expression? no no no no no no no no no no no yes Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Text symbology (labeling) - part 3 Property Type Meaning shield-resize string, one Specifies a mode for resizing label graphics (such as highof none, way shields) to fit the text of the label. The default mode, stretch, or ‘none’, never modifies the label graphic. In stretch mode, proportionalGeoServer will resize the graphic to exactly surround the label text, possibly modifying the image’s aspect ratio. In proportional mode, GeoServer will expand the image to be large enough to surround the text while preserving its original aspect ratio. shield-margin list of Specifies an extra margin (in pixels) to be applied to the lalengths, bel text when calculating label dimensions for use with the one to four shield-resize option. Similar to the margin shorthand elements property in CSS for HTML, its interpretation varies dependlong. ing on how many margin values are provided: 1 = use that margin length on all sides of the label 2 = use the first for top & bottom margins and the second for left & right margins. 3 = use the first for the top margin, second for left & right margins, third for the bottom margin. 4 = use the first for the top margin, second for the right margin, third for the bottom margin, and fourth for the left margin. label-underline-text one of true If enabled, the renderer will underline labels. This is equivaor false lent to the underlineText vendor parameter. label-strikethrough-text one of true If enabled, the renderer will strikethrough labels. This is or false equivalent to the strikethroughText vendor parameter. label-char-spacing an amount If present, expands or shrinks the space between subsequent of pixels, can characters in a label according to the value specified be negative label-word-spacing an amount If present, expands the space between subsequent words in a of pixels, label according to the value specified must be zero or positive 6.4. CSS Styling Accepts Expression? none none no no no no 487 GeoServer User Manual, Release 2.15.1 Raster symbology Property Type raster-channels string Meaning The list of raster channels to be used in the output. It can be “auto” to make the renderer choose the best course of action, or a list of band numbers, a single one will generate a gray image, three will generate an RGB one, four will generate a RGBA one. E.g., “1 3 7” to choose the first, third and seventh band of the input raster to make a RGB image raster-composite string The composite mode to be used and the optional opacity separated with a comma. See the full list of available modes. raster-geometry expression The attribute containing the raster to be painted. Normally not needed, but it would work if you had a custom vector data source that contains a GridCoverage attribute, in order to select it raster-opacity floating A value comprised between 0 and 1, 0 meaning completely point transparent, 1 meaning completely opaque. This controls the whole raster trasparency. raster-contrast-enhancement string Allows to stretch the range of data/colors in order to enhance tiny differences. Possible values are ‘normalize’, ‘histogram’ and ‘none’ raster-gammafloating Gamma adjustment for the output raster point raster-z-index integer Controls the z ordering of the raster output raster-color-map string Applies a color map to single banded input. The contents is a space separate list of color-map-entry(color, value) (opacity assumed to be 1), or color-map-entry(color, value, opacity). The values must be provided in increasing order. raster-color-map-type string Controls how the color map entries are interpreted, the possible values are “ramp”, “intervals” and “values”, with ramp being the default if no “raster-color-map-type” is provided. The default “ramp” behavior is to linearly interpolate color between the provided values, and assign the lowest color to all values below the lowest value, and the highest color to all values above the highest value. The “intervals” behavior instead assigns solid colors between values, whilst “values” only assigns colors to the specified values, every other value in the raster is not painted at all 488 Accepts Expression? no no yes no no no no no no Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Shared Property Type Meaning composite string The composite mode to be used and the optional opacity separated with a comma. See the full list of available modes. This will tell the rendering engine to use that FeatureTypeStyle as the destination, and will compose all subsequent FeatureTypeStyle/Layers on top of it, until another base is found. An expression to use for the geometry when rendering features. This provides a geometry for all types of symbology, but can be overridden by the symbol-specific geometry properties. A comma separated list of sorting directives, “att1 A|D, att2 A|D, . . . ” where att? are attribute names, and A or D are an optional direction specification, A is ascending, D is descending. Determines the loading, and thus painting, order of the features Rules with the different z-index but same sort-by-group id have their features sorted as a single group. Useful to z-order across layers or across different feature groups, like roads and rails, especially when using z-index to support casing Applies a rendering transformationon the current level. The function syntax is txName(key1:value1,key1:value2). Values can be single ones, or space separated lists. composite-base one of true or false geometry expression sort-by string sort-by-group string transform function Accepts Expression? no no yes no no no Symbol properties These properties are applied only when styling built-in symbols. See Styled marks for details. Property Type Meaning size rotation length angle The size at which to render the symbol. An angle through which to rotate the symbol. Accepts Expression? yes yes 6.4.7 CSS value types This page presents a brief overview of CSS types as used by this project. Note that these can be repeated as described in Multi-valued properties. Numbers Numeric values consist of a number, or a number annotated with a measurement value. In general, it is wise to use measurement annotations most of the time, to avoid ambiguity and protect against potential future changes to the default units. 6.4. CSS Styling 489 GeoServer User Manual, Release 2.15.1 Currently, the supported units include: • Length – px pixels – m meters – ft feet • Angle – deg degrees • Ratio – % percentage When using expressions in place of numeric values, the first unit listed for the type of measure is assumed. Since the CSS module translates styles to SLD before any rendering occurs, its model of unit-of-measure is tied to that of SLD. In practice, this means that for any particular symbolizer, there only one unit-of-measure applied for the style. Therefore, the CSS module extracts that unit-of-measure from one special property for each symbolizer type. Those types are listed below for reference: • fill-size determines the unit-of-measure for polygon symbolizers (but that doesn’t matter so much since it is the only measure associated with fills) • stroke-width determines the unit-of-measure for line symbolizers • mark-size determines the unit-of-measure for point symbolizers • font-size determines the unit-of-measure for text symbolizers and the associated halos Strings String values consist of a small snippet of text. For example, a string could be a literal label to use for a subset of roads: [lanes>20] { label: "Serious Freaking Highway"; } Strings can be enclosed in either single or double quotes. It’s easiest to simply use whichever type of quotes are not in your string value, but you can escape quote characters by prefixing them with a backslash \. Backslash characters themselves must also be prefixed. For example, '\\\'' is a string value consisting of a single backslash followed by a single single quote character. Labels While labels aren’t really a special type of value, they deserve a special mention since labels are more likely to require special string manipulation than other CSS values. If a label is a simple string value, then it works like any other string would: 490 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 [lanes > 20] { label: "Serious Freaking Highway"; } However, if a label has multiple values, all of those values will be concatenated to form a single label: [lanes > 20] { label: "Serious " "Freaking " "Highway"; } Note the whitespace within the label strings here; no whitespace is added when concatenating strings, so you must be explicit about where you want it included. You can also mix CQL expressions in with literal string values here: states { label: [STATE_NAME] " (" [STATE_ABBR] ")"; } Note: This automatic concatenation is currently a special feature only provided for labels. However, string concatenation is also supported directly in CQL expressions by using the strConcat filter function: * { fill: [strConcat('#', color_hex)]; } This form of concatenation works with any property that supports expressions. Colors Color values are relatively important to styling, so there are multiple ways to specify them. Format #RRGGBB #RGB rgb(r, g, b) Simple name Interpretation A hexadecimal-encoded color value, with two digits each for red, green, and blue. A hexadecimal-encoded color value, with one digits each for red, green, and blue. This is equivalent to the two-digit-per-channel encoding with each digit duplicated. A three-part color value with each channel represented by a value in the range 0 to 1, or in the range 0 to 255. 0 to 1 is used if any of the values include a decimal point, otherwise it is 0 to 255. The simple English name of the color. A full list of the supported colors is available at http://www.w3.org/TR/SVG/types.html#ColorKeywords External references When using external images to decorate map features, it is necessary to reference them by URL. This is done by a call to the url function. The URL value may be wrapped in single or double-quotes, or not at all. The same escaping rules as for string values. The url function is 6.4. CSS Styling 491 GeoServer User Manual, Release 2.15.1 also a special case where the surrounding quote marks can usually be omitted. Some examples: /* These properties are all equivalent. */ * { stroke: url("http://example.com/"); stroke: url('http://example.com/'); stroke: url(http://example.com/); } Note: While relative URLs are supported, they will be fully resolved during the conversion process to SLD and written out as absolute URLs. This may be cause problems when relocating data directories, etc. The style can be regenerated with the current correct URL by opening it in the demo editor and using the Submit button there. Well-known marks As defined in the SLD standard, GeoServer’s css module also allows using a certain set of well-known mark types without having to provide graphic resources explicitly. These include: • circle • square • cross • star • arrow And others. Additionally, vendors can provide an extended set of well-known marks, a facet of the standard that is exploited by some GeoTools plugins to provide dynamic map features such as using characters from TrueType fonts as map symbols, or dynamic charting. In support of these extended mark names, the css module provides a symbol function similar to url. The syntax is the same, aside from the function name: * { mark: symbol(circle); mark: symbol('ttf://Times+New+Roman&char=0x19b2'); mark: symbol("chart://type=pie&x&y&z"); } 6.4.8 Directives A directive is a CSS top level declaration that allows control of some aspects of the stylesheet application or translation to SLD. All directives are declared at the beginning of the CSS sheet and follow the same syntax: 492 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 @name value; For example: @mode 'Flat'; @styleTitle 'The title; @styleAbstract 'This is a longer description' * { stroke: black } [cat = 10] { stroke: yellow; stroke-width: 10 } Supported directives Directive Type Meaning mode String, Exclusive, Simple, Auto, Flat Controls how the CSS is translated to SLD. Exclusive, Simple and Auto are cascaded modes, Flat turns off cascading and has the CSS behave like a simplified syntax SLD sheet. See Understanding Cascading in CSS for an explanation of how the various modes work The generated SLD style title The generated SLD style abstract/description styleTitle String styleAbstract String Accepts Expression? false No No 6.4.9 Understanding Cascading in CSS Cascading Style Sheets are the styling language of the web, use a simple syntax, but sometimes their simplicity can be deceitful if the writer is not aware of how the “Cascading” part of it works. The confusion might become greater by looking at the translated SLD, and wondering how all the SLD rules came to be from a much smaller set of CSS rules. This document tries to clarify how cascading works, how it can be controlled in SLD translation, and for those that would prefer simpler, if more verbose, styles, shows how to turn cascading off for good. CSS rules application Given a certain feature, how are CSS rules applied to it? This is roughly the algorithm: • Locate all rules whose selector matches the current feature • Sort them by specificity, less specific to more specific 6.4. CSS Styling 493 GeoServer User Manual, Release 2.15.1 • Have more specific rules add to and override properties set in less specific rules As you can see, depending on the feature attributes a new rule is built by the above algorithm, mixing all the applicable rules for that feature. The core of the algorithm allows to prepare rather succinct style sheets for otherwise very complex rule sets, by setting the common bits in less specific rules, and override them specifying the exceptions to the norm in more specific rules. Understanding specificity In web pages CSS specificity is setup as a tuple of four numbers called a,b,c,d: • a: set to 1 if the style is local to an element, that is, defined in the element style attribute • b: counts the number of ID attributes in the selector • c: count the number of other attributes and pseudo classes in the selector • d: count the number of element names or pseudo elements in the selector a is more important than b, which is more important than c, and so on, so for example, if one rule has a=1 and then second has a=0, the first is more specific, regardless of what values have b, c and d. Here are some examples from the CSS specification, from less specific to more specific: * ,→ {} /* a=0 b=0 c=0 d=0 -> specificity = 0,0,0,0 */ li ,→ {} /* a=0 b=0 c=0 d=1 -> specificity = 0,0,0,1 */ li:first-line ,→{} /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */ ul li ,→ {} /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */ ul ol+li ,→ {} /* a=0 b=0 c=0 d=3 -> specificity = 0,0,0,3 */ h1 + *[rel=up] ,→{} /* a=0 b=0 c=1 d=1 -> specificity = 0,0,1,1 */ ul ol li.red ,→ {} /* a=0 b=0 c=1 d=3 -> specificity = 0,0,1,3 */ li.red.level ,→ {} /* a=0 b=0 c=2 d=1 -> specificity = 0,0,2,1 */ #x34y ,→ {} /* a=0 b=1 c=0 d=0 -> specificity = 0,1,0,0 */ style="..." ,→ /* a=1 b=0 c=0 d=0 -> specificity = 1,0,0,0 */ In cartographic CSS there are no HTML elements that could have a local style, so a is always zero. The others are calculated as follows: • b: number of feature ids in the rule • c: number of attributes in CQL filters and pseudo-classes (e.g., :mark) used in the selector • d: 1 if a typename is specified, 0 otherwise 494 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Here are some examples, from less to more specific: * ,→ {} /* a=0 b=0 c=0 d=0 topp:states ,→ {} /* a=0 b=0 c=0 d=1 :mark ,→ {} /* a=0 b=0 c=1 d=0 [a = 1 and b > 10] ,→{} /* a=0 b=0 c=1 d=0 -> #states.1 ,→ {} /* a=0 b=1 c=0 d=0 -> specificity = 0,0,0,0 */ -> specificity = 0,0,0,1 */ -> specificity = 0,0,1,0 */ specificity = 0,0,2,0 */ -> specificity = 0,1,0,0 */ In case two rules have the same specificity, the last one in the document wins. Understanding CSS to SLD translation in cascading mode As discussed above, CSS rule application can potentially generate a different rule for each feature, depending on its attributes and how they get matched by the various CSS selectors. SLD on the other hand starts from the rules, and applies all of them, in turn, to each feature, painting each matching rule. The two evaluation modes are quite different, in order to turn CSS into SLD the translator has to generate every possible CSS rule combination, while making sure the generated SLD rules are mutually exclusive (CSS generated a single rule for a given feature in the end). The combination of all rules is called a power set, and the exclusivity is guaranteed by negating the filters of all previously generated SLD rules and adding to the current one. As one might imagine, this would result in a lot of rules, with very complex filters. The translator addresses the above concerns by applying a few basic strategies: • The generated filters are evaluated in memory, if the filter is found to be “impossible”, that is, something that could never match an exiting feature, the associated rule is not emitted (e.g., a = 1 and a = 2 or a = 1 and not(a = 1)) • The generated SLD has a vendor option first which forces the renderer to give up evaluating further rules once one of them actually matched a feature The above is nice and sufficient in theory, while in practice it can break down with very complex CSS styles having a number of orthogonal selectors (e.g., 10 rules controlling the fill on the values of attribute a and 10 rules controlling the stroke on values of attribute b, and another 10 rules controlling the opacity of fill and stroke based on attribute c, resulting in 1000 possible combinations). For this reason by default the translator will try to generated simplified and fully exclusive rules only if the set of rules is “small”, and will instead generate the full power set otherwise, to avoid incurring in a CSS to SLD translation time of minutes if not hours. 6.4. CSS Styling 495 GeoServer User Manual, Release 2.15.1 The translation modes are controlled by the @mode directive, with the following values: • 'Exclusive': translate the style sheet in a minimum set of SLD rules with simplified selectors, taking whatever time and memory required • 'Simple': just generated the power set without trying to build a minimum style sheet, ensuring the translation is fast, even if the resulting SLD might look very complex • 'Auto': this is the default value, it will perform the power set expansion, and then will proceed in Exclusive mode if the power set contains less than 100 derived rules, or in Simple mode otherwise. The rule count threshold can be manually controlled by using the @autoThreshold directive. The Flat translation mode The @mode directive has one last possible value, Flat, which enables a flat translation mode in which specificity and cascading are not applied. In this mode the CSS will be translated almost 1:1 into a corresponding SLD, each CSS rule producing and equivalent SLD rule, with the exception of the rules with pseudo-classes specifying how to stroke/fill marks and symbols in general. Care should be taken when writing rules with pseudo classes, they will be taken into consideration only if their selector matches the one of the preceding rule. Consider this example: @mode "Flat"; [type = 'Capital'] { mark: symbol(circle); } [type = 'Capital'] :mark { fill: white; size: 6px; } :mark { stroke: black; stroke-width: 2px; } In the above example, the first rule with the :mark pseudo class will be taken into consideration and merged with the capital one, the second one instead will be ignored. The resulting SLD will thus not contain any stroke specification for the ‘circle’ mark: 496 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Default Styler type Capital circle #ffffff 6 ,→ The advantages of flat mode are: • Easy to understand, the rules are applied in the order they are written • Legend control, the generated legend contains no surprises as rules are not mixed together and are not reordered The main disadvantage is that there is no more a way to share common styling bits in general rules, all common bits have to be repeated in all rules. Note: In the future we hope to add the ability to nest rules, which is going to address some of the limitations of flat mode without introducing the most complex bits of the standard cascading mode Comparing cascading vs flat modes, an example Consider the following CSS: * { stroke: black; stroke-width: 10 } [cat = 'important'] { stroke: yellow; } If the above style is translated in cascading mode, it will generate two mutually exclusive SLD rules: 6.4. CSS Styling 497 GeoServer User Manual, Release 2.15.1 • One applying a 10px wide yellow stroke on all features whose cat attribute is ‘important’ • One applying a 10px wide black stroke on all feature whose cat attribute is not ‘important’ Thus, each feature will be painted by a single line, either yellow or black. If instead the style contains a @mode 'Flat' directive at the top, it will generated two non mutually exclusive SLD rules: • One applying a 10px wide black stroke on all features • One applying a 1px wide yewllow stroke on all feature whose cat attribute is ‘important’ Thus, all features will at least be painted 10px black, but the ‘important’ ones will also have a second 1px yellow line on top of the first one 6.4.10 Nested rules Starting with GeoServer 2.10 the CSS modules supports rule nesting, that is, a child rule can be written among properties of a parent rule. The nested rules inherits the parent rule selector and properties, adding its own extra selectors and property overrides. Each nested rule can be written as normal, however, if other rules or properties follow, it must be terminated with a semicolon (this char being the separator in the CSS language). Nesting is a pure syntax improvement, as such it does not actually provide extra functionality, besides more compact and hopefully readable styles. This is an example of a CSS style using only cascading to get a different shape, fill and stroke color for a point symbol in case the type attribute equals to important: [@sd < 3000] { mark: symbol(circle) } [@sd < 3000] :mark { fill: gray; size: 5 } [@sd < 3000] [type = 'important'] { mark: symbol('triangle') } [@sd < 3000] [type = 'important'] :mark { fill: red; stroke: yellow } 498 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 This second version uses rule nesting getting a more compact expression, putting related symbology element close by: [@sd < 3000] { mark: symbol(circle); :mark { fill: gray; size: 5 }; [type = 'important'] { mark: symbol(triangle); :mark { fill: red; stroke: yellow } } } 6.4.11 Rendering transformations in CSS Starting with GeoServer 2.10 the CSS modules supports rendering transformations via the transform property. The property is a function call with a special key/value pair syntax, using the following template: transformationName(key1:value1, ,→key2:v21 v22 ... v2M,...,keyN:vN) The values can be simple ones, or can be a space separated list. The parameter representing the input layer can be omitted, the engine will automatically recognize input parameters of type feature collection or grid coverage. The transformation function is subject to cascading like all other properties, but cascading acts at the whole z-level, so if multiple transformations are needed, they need to be associated with two different z-levels. This is an example of a CSS style extracting contour lines from a DEM, and also showing the single values when a suitable zoom level is reached: /* @title Levels */ * { transform: ras:Contour(levels: ,→1100 1200 1300 1400 1500 1600 1700); z-index: 0; stroke: gray; label: [numberFormat('#', value)]; font-size: 12; font-fill: black; font-weight: bold; halo-color: white; halo-radius: 2; label-follow-line: true; label-repeat: 200; 6.4. CSS Styling 499 GeoServer User Manual, Release 2.15.1 label-max-angle-delta: 45; label-priority: 2000; } /* @title Values */ [@sd < 12000] { transform: ras:RasterAsPointCollection(scale: 0.5); z-index: 1; label: [GRAY_INDEX]; label-anchor: 0.5 0.5; font-family: Arial; font-fill: black; font-size: 6; label-priority: 1000; } Fig. 6.110: The two transformations in action against a DEM layer 6.4.12 Styled marks GeoServer’s CSS module provides a collection of predefined symbols that you can use and combine to create simple marks, strokes, and fill patterns without needing an image editing program. You can access these symbols via the symbol() CSS function. For example, the built-in circle symbol makes it easy to create a simple ‘dot’ marker for a point layer: * { mark: symbol(circle); } Symbols work anywhere you can use a url() to reference an image (as in, you can use symbols for stroke and fill patterns as well as markers.) Symbol names GeoServer extensions can add extra symbols (such as the chart:/ / symbol family which allows the use of charts as symbols via a naming scheme similar to the Google Charts API). However, there are a few symbols that are always available: • circle 500 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 • square • triangle • arrow • cross • star • x • shape://horizline • shape://vertline • shape://backslash • shape://slash • shape://plus • shape://times • windbarbs://default(size)[unit] Symbol selectors Symbols offer some additional styling options beyond those offered for image references. To specify these style properties, just add another rule with a special selector. There are 8 “pseudoclass” selectors that are used to style selectors: • :mark specifies that a rule applies to symbols used as point markers • :shield specifies that a rule applies to symbols used as label shields (icons displayed behind label text) • :stroke specifies that a rule applies to symbols used as stroke patterns • :fill specifies that a rule applies to symbols used as fill patterns • :symbol specifies that a rule applies to any symbol, regardless of which context it is used in • :nth-mark(n) specifies that a rule applies to the symbol used for the nth stacked point marker on a feature. • :nth-shield(n) specifies that a rule applies to the symbol used for the background of the nth stacked label on a feature • :nth-stroke(n) specifies that a rule applies to the symbol used for the nth stacked stroke pattern on a feature. • :nth-fill(n) specifies that a rule applies to the symbol used for the nth stacked fill pattern on a feature. • :nth-symbol(n) specifies that a rule applies to the symbol used for the nth stacked symbol on a feature, regardless of which context it is used in. These pseudoclass selectors can be used in a top level rule, but starting with GeoServer 2.10, they are more commonly used in sub-rules close to the mark property, to get better readability (see example below). 6.4. CSS Styling 501 GeoServer User Manual, Release 2.15.1 Symbol styling properties Styling a built-in symbol is similar to styling a polygon feature. However, the styling options are slightly different from those available to a true polygon feature: • The mark and label families of properties are unavailable for symbols. • Nested symbol styling is not currently supported. • Only the first stroke and fill will be used. • Additional size (as a length) and rotation (as an angle) properties are available. These are analogous to the (mark|stroke|fill)-size and (mark|stroke|fill)-rotation properties available for true geometry styling. Note: The various prefixed ‘-size’ and ‘-rotation’ properties on the containing style override those for the symbol if they are present. Example styled symbol As an example, consider a situation where you are styling a layer that includes data about hospitals in your town. You can create a simple hospital logo by placing a red cross symbol on top of a white circle background: [usage='hospital'] { mark: symbol('circle'), symbol('cross'); :nth-mark(1) { size: 16px; fill: white; stroke: red; }; :nth-mark(2) { size: 12px; fill: red; } } Also an windbarb example where you get wind speed and direction from your data fields horSpeed and horDir (direction): * { /* select windbard based on speed( ,→here in meters per second, and south hemisphere) */ mark: symbol('windbarbs:/ ,→/default(${horSpeed})[m/s]?hemisphere=s'); /* rotate windbarb based on horDir property (in degrees) */ mark-rotation: [horDir]; ,→ 502 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 mark-size: 20; } 6.4.13 CSS Cookbook The CSS Cookbook is a collection of CSS “recipes” for creating various types of map styles. Wherever possible, each example is designed to show off a single CSS feature so that code can be copied from the examples and adapted when creating CSS styles of your own. Most examples are shared with the SLD Cookbook, to make a comparison between the two syntaxes immediate. The CSS Cookbook is divided into four sections: the first three for each of the vector types (points, lines, and polygons) and the fourth section for rasters. Each example in every section contains a screenshot showing actual GeoServer WMS output and the full CSS code for reference. Each section uses data created especially for the Cookbooks (both CSS and SLD), with shapefiles for vector data and GeoTIFFs for raster data. The projection for data is EPSG:4326. All files can be easily loaded into GeoServer in order to recreate the examples. Data type Point Line Polygon Raster Shapefile sld_cookbook_point.zip sld_cookbook_line.zip sld_cookbook_polygon.zip sld_cookbook_raster.zip Points While points are seemingly the simplest type of shape, possessing only position and no other dimensions, there are many different ways that a point can be styled in CSS. Example points layer The points layer used for the examples below contains name and population information for the major cities of a fictional country. For reference, the attribute table for the points in this layer is included below. fid (Feature ID) point.1 point.2 point.3 point.4 point.5 point.6 point.7 6.4. CSS Styling name (City name) Borfin Supox City Ruckis Thisland Synopolis San Glissando Detrania pop (Population) 157860 578231 98159 34879 24567 76024 205609 503 GeoServer User Manual, Release 2.15.1 Download the points shapefile Simple point This example specifies points be styled as red circles with a diameter of 6 pixels. Fig. 6.111: Simple point Code * { mark: symbol(circle); mark-size: 6px; :mark { fill: red; } } 1 2 3 4 5 6 7 Details There are two rules in this CSS, the outer one matches all features, and asks them to be depicted with a circular mark, 6 pixels wide. The nested rule uses a symbol selector, :mark, which selects all marks, and allows to specify how to fill the contents of the circle, in this case, with a solid red fill (a stand alone fill property would have been interpreted as the request to fill all polygons in the input with solid red instead). Simple point with stroke This example adds a stroke (or border) around the Simple point, with the stroke colored black and given a thickness of 2 pixels. 504 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.112: Simple point with stroke Code * { mark: symbol(circle); mark-size: 6px; :mark { fill: red; stroke: black; stroke-width: 2px; } } 1 2 3 4 5 6 7 8 9 Details This example is similar to the Simple point example, in this case a stroke and a stroke width have been specified in the mark selector in order to apply them to the circle symbols. Rotated square This example creates a square instead of a circle, colors it green, sizes it to 12 pixels, and rotates it by 45 degrees. Code * { mark: symbol(square); mark-size: 12px; mark-rotation: 45; :mark { fill: #009900; } } 1 2 3 4 5 6 7 8 6.4. CSS Styling 505 GeoServer User Manual, Release 2.15.1 Fig. 6.113: Rotated square Details In this example, line 2 sets the shape to be a square, with line 6 setting the color to a dark green (#009900). Line 3 sets the size of the square to be 12 pixels, and line 4 set the rotation is to 45 degrees. Transparent triangle This example draws a triangle, creates a black stroke identical to the Simple point with stroke example, and sets the fill of the triangle to 20% opacity (mostly transparent). Fig. 6.114: Transparent triangle Code * { mark: symbol(triangle); mark-size: 12; :mark { fill: #009900; 1 2 3 4 5 506 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 fill-opacity: 0.2; stroke: black; stroke-width : 2px; 6 7 8 } 9 } 10 Details In this example, line 2 once again sets the shape, in this case to a triangle, where line 3 sets the mark size to 12 pixels. Line 5 sets the fill color to a dark green (#009900) and line 6 sets the opacity to 0.2 (20% opaque). An opacity value of 1 means that the shape is drawn 100% opaque, while an opacity value of 0 means that the shape is drawn 0% opaque, or completely transparent. The value of 0.2 (20% opaque) means that the fill of the points partially takes on the color and style of whatever is drawn beneath it. In this example, since the background is white, the dark green looks lighter. Were the points imposed on a dark background, the resulting color would be darker. Line 8 set the stroke color to black and width to 2 pixels. Point as graphic This example styles each point as a graphic instead of as a simple shape. Fig. 6.115: Point as graphic Code * { mark: url(smileyface.png); mark-mime: "image/png"; } 1 2 3 4 6.4. CSS Styling 507 GeoServer User Manual, Release 2.15.1 Details This style uses a graphic instead of a simple shape to render the points. Line 2 sets the path and file name of the graphic, while line 3 indicates the format (MIME type) of the graphic (image/png). In this example, the graphic is contained in the same directory as the SLD, so no path information is necessary, although a full URL could be used if desired. Fig. 6.116: Graphic used for points Point with default label This example shows a text label on the Simple point that displays the “name” attribute of the point. This is how a label will be displayed in the absence of any other customization. Fig. 6.117: Point with default label Code * { mark: symbol(circle); mark-size: 6px; label: [name]; font-fill: black; :mark { fill: red; } } 1 2 3 4 5 6 7 8 9 508 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Details This style is quite similar to the Simple point, but two new properties have been added to specify the labelling options. Line 4 indicates that the label contents come from the “name” attribute (anything in square brackets is a CQL expression, the attribute name being the simplest case) while Line 5 sets the label color to black. Point with styled label This example improves the label style from the Point with default label example by centering the label above the point and providing a different font name and size. Fig. 6.118: Point with styled label Code * { mark: symbol(circle); mark-size: 6px; label: [name]; font-fill: black; font-family: Arial; font-size: 12; font-weight: bold; label-anchor: 0.5 0; label-offset: 0 5; :mark { fill: red; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 } 15 6.4. CSS Styling 509 GeoServer User Manual, Release 2.15.1 Details This example expands on Point with default label and specifies the font attributes, in particular, the text is Aria, bold, 12px wide. Moreover, the label is moved on top of the point, by specifying an anchor of 0.5 0, which sets the point to be centered (0.5) horizontally axis and bottom aligned (0.0) vertically with the label, and an offset which moves the label 5 pixels up vertically. The result is a centered bold label placed slightly above each point. Point with rotated label This example builds on the previous example, Point with styled label, by rotating the label by 45 degrees, positioning the labels farther away from the points, and changing the color of the label to purple. Fig. 6.119: Point with rotated label Code * { mark: symbol(circle); mark-size: 6px; label: [name]; font-fill: #990099; font-family: Arial; font-size: 12; font-weight: bold; label-anchor: 0.5 0; label-offset: 0 25; label-rotation: -45; :mark { fill: red; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 510 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Details This example is similar to the Point with styled label, but there are three important differences. Line 10 specifies 25 pixels of vertical displacement. Line 11 specifies a rotation of “-45” or 45 degrees counter-clockwise. (Rotation values increase clockwise, which is why the value is negative.) Finally, line 5 sets the font color to be a shade of purple (#99099). Note that the displacement takes effect before the rotation during rendering, so in this example, the 25 pixel vertical displacement is itself rotated 45 degrees. Attribute-based point This example alters the size of the symbol based on the value of the population (“pop”) attribute. Fig. 6.120: Attribute-based point Code * { mark: symbol(circle); :mark { fill: #0033CC; }; [pop < 50000] { mark-size: 8; }; [pop >= 50000] [pop < 100000] { mark-size: 12; }; [pop >= 100000] { mark-size: 16; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 6.4. CSS Styling 511 GeoServer User Manual, Release 2.15.1 Details Note: Refer to the Example points layer to see the attributes for this data. This example has eschewed labels in order to simplify the style, but you can refer to the example Point with styled label to see which attributes correspond to which points. This style shows how the basic mark setup (red circle, default size) can be overridden via cascading/nesting, changing the size depending on the pop attribute value, with smaller values yielding a smaller circle, and larger values yielding a larger circle. The three rules are designed as follows: Rule order 1 2 3 Population (“pop”) Less than 50,000 50,000 to 100,000 Greater than 100,000 Rule name SmallPop MediumPop LargePop Size 8 12 16 The result of this style is that cities with larger populations have larger points. In particular, the rule at Line 6 matches all features whose “pop” attribute is less than 50000, the rule at Line 9 matches all features whose “pop” attribute is between 50000 and 100000 (mind the space between the two predicates, it is equivalent to and AND, if we had used a comma it would have been an OR instead), while the rule at Line 12 matches all features with more than 100000 inhabitants. Zoom-based point This example alters the style of the points at different zoom levels. Code * { mark: symbol(circle); } 1 2 3 4 :mark { fill: #CC3300; } 5 6 7 8 [@sd < 16M] { mark-size: 12; } 9 10 11 12 [@sd > 16M] [@sd < 32M] { mark-size: 8; } 13 14 15 16 [@sd > 32M] { 17 512 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.121: Zoom-based point: Zoomed in Fig. 6.122: Zoom-based point: Partially zoomed 6.4. CSS Styling 513 GeoServer User Manual, Release 2.15.1 Fig. 6.123: Zoom-based point: Zoomed out mark-size: 4; 18 } 19 Details It is often desirable to make shapes larger at higher zoom levels when creating a natural-looking map. This example styles the points to vary in size based on the zoom level (or more accurately, scale denominator). Scale denominators refer to the scale of the map. A scale denominator of 10,000 means the map has a scale of 1:10,000 in the units of the map projection. Note: Determining the appropriate scale denominators (zoom levels) to use is beyond the scope of this example. This style contains three rules matching the scale. The three rules are designed as follows: Rule order 1 2 Rule name Large Medium 3 Small Scale denominator 1:16,000,000 or less 1:16,000,000 to 1:32,000,000 Greater than 1:32,000,000 Point size 12 8 4 The order of these rules does not matter since the scales denominated in each rule do not overlap. The rules use the “@sd” pseudo-attribute, which refers to the current scale denominator, and which can be compared using the ‘<’ and ‘>’ operators only (using any other operator or function will result in errors). The result of this style is that points are drawn larger as one zooms in and smaller as one zooms out. 514 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 While this example uses on purpose cascading to show a different possible setup, the same style could be written as: * { mark: symbol(circle); :mark { fill: #CC3300; }; [@sd < 16M] { mark-size: 12; }; [@sd > 16M] [@sd < 32M] { mark-size: 8; }; [@sd > 32M] { mark-size: 4; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Lines While lines can also seem to be simple shapes, having length but no width, there are many options and tricks for making lines display nicely. Example lines layer The lines layer used in the examples below contains road information for a fictional country. For reference, the attribute table for the points in this layer is included below. 6.4. CSS Styling 515 GeoServer User Manual, Release 2.15.1 fid (Feature ID) line.1 line.2 line.3 line.4 line.5 line.6 line.7 line.8 line.9 line.10 line.11 line.12 line.13 line.14 line.15 line.16 line.17 line.18 line.19 line.20 line.21 line.22 line.23 line.24 line.25 name (Road name) Latway Crescent Avenue Forest Avenue Longway Saxer Avenue Ridge Avenue Holly Lane Mulberry Street Nathan Lane Central Street Lois Lane Rocky Road Fleet Street Diane Court Cedar Trail Victory Road Highland Road Easy Street Hill Street Country Road Main Street Jani Lane Shinbone Alley State Street River Road type (Road class) highway secondary secondary highway secondary secondary local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road Download the lines shapefile Simple line This example specifies lines be colored black with a thickness of 3 pixels. Code * { stroke: black; stroke-width: 3px; } 1 2 3 4 Details The only rule asks for a black stroke (this attribute is mandatory to get strokes to actually show up), 3 pixels wide. 516 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.124: Simple line Line with border This example shows how to draw lines with borders (sometimes called “cased lines”). In this case the lines are drawn with a 3 pixel blue center and a 1 pixel wide gray border. Code * { stroke: #333333, #6699FF; stroke-width: 5px, 3px; stroke-linecap: round; z-index: 0, 1; } 1 2 3 4 5 6 Details Lines in CSS have no notion of a “fill”, only “stroke”. Thus, unlike points or polygons, it is not possible to style the “edge” of the line geometry. It is, however, possible to achieve this effect by drawing each line twice: once with a certain width and again with a slightly smaller width. This gives the illusion of fill and stroke by obscuring the larger lines everywhere except along the edges of the smaller lines. The style uses the “multi-valued properties” CSS support by specifying two strokes and two stroke-widths. This causes each feature to be painted twice, first with a dark gray (#333333) line 5 pixels wide, and then a thinner blue (#6699FF) line 3 pixels wide. 6.4. CSS Styling 517 GeoServer User Manual, Release 2.15.1 Fig. 6.125: Line with border Since every line is drawn twice, the order of the rendering is very important. Without the z-index indication, each feature would first draw the gray stroke and then the blue one, and then the rendering engine would move to the next feature, and so on. This would result in ugly overlaps when lines do cross. By using the z-index property (Line 3) instead, all gray lines will be painted first, and then all blue lines will painted on top, thus making sure the blue lines visually connect. The “stroke-linecap” property is the only one having a single value, this is because the value is the same for both the gray and blue line. The result is a 3 pixel blue line with a 1 pixel gray border, since the 5 pixel gray line will display 1 pixel on each side of the 3 pixel blue line. Dashed line This example alters the Simple line to create a dashed line consisting of 5 pixels of drawn line alternating with 2 pixels of blank space. Code * { stroke: blue; stroke-width: 3px; stroke-dasharray: 5 2; } 1 2 3 4 5 518 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.126: Dashed line Details In this example the we create a blue line, 3 pixels wide, and specify a dash array with value “5 2”, which creates a repeating pattern of 5 pixels of drawn line, followed by 2 pixels of omitted line. Railroad (hatching) This example uses hatching to create a railroad style. Both the line and the hatches are black, with a 2 pixel thickness for the main line and a 1 pixel width for the perpendicular hatches. Code * { stroke: #333333, symbol("shape://vertline"); stroke-width: 3px; :nth-stroke(2) { size: 12; stroke: #333333; stroke-width: 1px; } } 1 2 3 4 5 6 7 8 9 Details In this example a multi-valued stroke is used: the fist value makes the renderer paint a dark gray line (3 pixels wide, according to the 6.4. CSS Styling 519 GeoServer User Manual, Release 2.15.1 Fig. 6.127: Railroad (hatching) “stroke-width” attribute), whilst the second value makes the line be painted by repeating the “shape://vertline” symbol over and over, creating the hatching effect. In order to specify how the symbol itself should be painted, the “:nth-stroke(2)” pseudo-selector is used at Line 4 to specify the options for the repeated symbol: in particular with are instructing the renderer to create a 12px wide symbol, with a dark gray stroke 1 pixel wide. Spaced graphic symbols This example uses a graphic stroke along with dash arrays to create a “dot and space” line type. Adding the dash array specification allows to control the amount of space between one symbol and the next one. Without using the dash array the lines would be densely populated with dots, each one touching the previous one. Code * { stroke: symbol(circle); stroke-dasharray: 4 6; :stroke { size: 4; fill: #666666; stroke: #333333; stroke-width: 1px; } } 1 2 3 4 5 6 7 8 9 10 520 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.128: Spaced symbols along a line Details This example, like others before, uses symbol(circle) to place a graphic symbol along a line. The symbol details are specified in the nested rule at Line 4 using the “:stroke” pseudo-selector, creating a gray fill circle, 4 pixels wide, with a dark gray outline. The spacing between symbols is controlled with the stroke-dasharray at line 3, which specifies 4 pixels of pendown (just enough to draw the circle) and 6 pixels of pen-up, to provide the spacing. Alternating symbols with dash offsets This example shows how to create a complex line style which alternates a dashed line and a graphic symbol. The code builds on features shown in the previous examples: • stroke-dasharray controls pen-down/pen-up behavior to generate dashed lines • symbol(...) places symbols along a line combining the two allows control of symbol spacing This also shows the usage of a dash offset, which controls where rendering starts in the dash array. For example, with a dash array of 5 10 and a dash offset of 7 the renderer starts drawing the pattern 7 pixels from the beginning. It skips the 5 pixels pen-down section and 2 pixels of the pen-up section, then draws the remaining 8 pixels of pen-up, then 5 down, 10 up, and so on. The example shows how to use these features to create two synchronized sequences of dash arrays, one drawing line segments and the other symbols. 6.4. CSS Styling 521 GeoServer User Manual, Release 2.15.1 Fig. 6.129: Alternating dash and symbol Code * { stroke: blue, symbol(circle); stroke-width: 1px; stroke-dasharray: 10 10, 5 15; stroke-dashoffset: 0, 7.5; :nth-stroke(2) { stroke: #000033; stroke-width: 1px; size: 5px; } } 1 2 3 4 5 6 7 8 9 10 11 Details This example uses again multi-valued properties to create two subsequent strokes applied to the same lines. The first stroke is a solid blue line, 1 pixel wide, with a dash array of “10 10”. The second one instead is a repeated circle, using a dash array of “5 15” and with a dash offset of 7.5. This makes the sequence start with 12.5 pixels of white space, then a circle (which is then centered between the two line segments of the other pattern), then 15 pixels of white space, and so on. The circle portrayal details are specified using the pseudo selector “nth-stroke(2)” at line 6, asking for circles that are 5 pixels wide, not filled, and with a dark blue outline. 522 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Line with default label This example shows a text label on the simple line. This is how a label will be displayed in the absence of any other customization. Fig. 6.130: Line with default label Code * { stroke: red; label: [name]; font-fill: black; } 1 2 3 4 5 Details This example paints lines with a red stroke, and then adds horizontal black labels at the center of the line, using the “name” attribute to fill the label. _css_line_ Labels along line with perpendicular offset This example shows a text label on the simple line, just like the previous example, but will force the label to be parallel to the lines, and will offset them a few pixels away. 6.4. CSS Styling 523 GeoServer User Manual, Release 2.15.1 Fig. 6.131: Line with default label Code * { stroke: red; label: [name]; label-offset: 7px; font-fill: black; } 1 2 3 4 5 6 Details This example is line by line identical to the previous one, but it add a new attribute “label-offset”, which in the case of lines, when having a single value, is intepreted as a perpendicular offset from the line. The label is painted along a straight line, parallel to the line orientation in the center point of the label. Label following line This example renders the text label to follow the contour of the lines. Code * { stroke: red; label: [name]; font-fill: black; label-follow-line: true; } 1 2 3 4 5 6 524 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.132: Label following line Details As the Line with default label example showed, the default label behavior isn’t optimal. This example is similar to the Line with default label example with the exception of line 5 where the “label-follow-line” option is specified, which forces the labels to strickly follow the line. Not all labels are visible partly because of conflict resolution, and partly because the renderer cannot find a line segment long and “straight” enough to paint the label (labels are not painted over sharp turns by default). Optimized label placement This example optimizes label placement for lines such that the maximum number of labels are displayed. Code * { stroke: red; label: [name]; font-fill: black; label-follow-line: true; label-max-angle-delta: 90; label-max-displacement: 400; label-repeat: 150; } 1 2 3 4 5 6 7 8 9 6.4. CSS Styling 525 GeoServer User Manual, Release 2.15.1 Fig. 6.133: Optimized label Details This example is similar to the previous example, Label following line. The only differences are contained in lines 6-8. Line 6 sets the maximum angle that the label will follow. This sets the label to never bend more than 90 degrees to prevent the label from becoming illegible due to a pronounced curve or angle. Line 7 sets the maximum displacement of the label to be 400 pixels. In order to resolve conflicts with overlapping labels, GeoServer will attempt to move the labels such that they are no longer overlapping. This value sets how far the label can be moved relative to its original placement. Finally, line 8 sets the labels to be repeated every 150 pixels. A feature will typically receive only one label, but this can cause confusion for long lines. Setting the label to repeat ensures that the line is always labeled locally. Optimized and styled label This example improves the style of the labels from the Optimized label placement example. Code * { stroke: red; label: [name]; font-family: Arial; font-weight: bold; font-fill: black; 1 2 3 4 5 6 526 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.134: Optimized and styled label font-size: 10; halo-color: white; halo-radius: 1; label-follow-line: true; label-max-angle-delta: 90; label-max-displacement: 400; label-repeat: 150; 7 8 9 10 11 12 13 } 14 Details This example is similar to the Optimized label placement. The only differences are: • The font family and weight have been specified • In order to make the labels easier to read, a white “halo” has been added. The halo draws a thin 1 pixel white border around the text, making it stand out from the background. Attribute-based line This example styles the lines differently based on the “type” (Road class) attribute. Code [type = 'local-road'] { stroke: #009933; stroke-width: 2; z-index: 0; } 1 2 3 4 5 6 [type = 'secondary'] { stroke: #0055CC; stroke-width: 3; z-index: 1; 7 8 9 10 6.4. CSS Styling 527 GeoServer User Manual, Release 2.15.1 Fig. 6.135: Attribute-based line } 11 12 [type = 'highway'] { stroke: #FF0000; stroke-width: 6; z-index: 2; } 13 14 15 16 17 Details Note: Refer to the Example lines layer to see the attributes for the layer. This example has eschewed labels in order to simplify the style, but you can refer to the example Optimized and styled label to see which attributes correspond to which points. There are three types of road classes in our fictional country, ranging from back roads to high-speed freeways: “highway”, “secondary”, and “local-road”. In order to make sure the roads are rendered in the proper order of importance, a “z-index” attribute has been placed in each rule. The three rules are designed as follows: Rule order 1 2 3 Rule name / type local-road secondary highway Color #009933 (green) #0055CC (blue) #FF0000 (red) Size 2 3 6 Lines 1-5 comprise the first rule, the filter matches all roads that the 528 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 “type” attribute has a value of “local-road”. If this condition is true for a particular line, the rule renders it dark green, 2 pixels wide. All these lines are rendered first, and thus sit at the bottom of the final map. Lines 7-11 match the “secondary” roads, painting them dark blue, 3 pixels wide. Given the “z-index” is 1, they are rendered after the local roads, but below the highways. Lines 13-17 match the “highway” roads, painting them red 6 pixels wide. These roads are pained last, thus, on top of all others. Zoom-based line This example alters the Simple line style at different zoom levels. Fig. 6.136: Zoom-based line: Zoomed in Code * { stroke: #009933; } 1 2 3 4 [@sd < 180M] { stroke-width: 6; } 5 6 7 8 [@sd > 180M] [@sd < 360M] { stroke-width: 4; } 9 10 11 12 [@sd > 360M] { 13 6.4. CSS Styling 529 GeoServer User Manual, Release 2.15.1 Fig. 6.137: Zoom-based line: Partially zoomed Fig. 6.138: Zoom-based line: Zoomed out 530 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 stroke-width: 2; 14 } 15 Details It is often desirable to make shapes larger at higher zoom levels when creating a natural-looking map. This example varies the thickness of the lines according to the zoom level (or more accurately, scale denominator). Scale denominators refer to the scale of the map. A scale denominator of 10,000 means the map has a scale of 1:10,000 in the units of the map projection. Note: Determining the appropriate scale denominators (zoom levels) to use is beyond the scope of this example. This style contains three rules. The three rules are designed as follows: Rule order 1 2 3 Rule name Large Medium Small Scale denominator 1:180,000,000 or less 1:180,000,000 to 1:360,000,000 Greater than 1:360,000,000 Line width 6 4 2 The order of these rules does not matter since the scales denominated in each rule do not overlap. The first rule provides the stroke color used at all zoom levels, dark gray, while the other three rules cascade over it applying the different stroke widths based on the current zoom level leveraging the “@sd” pseudo attribute. The “@sd” pseudo attribute can only be compared using the “<” and “>” operators, using any other operator will result in errors. The result of this style is that lines are drawn with larger widths as one zooms in and smaller widths as one zooms out. Polygons Polygons are two dimensional shapes that contain both an outer edge (or “stroke”) and an inside (or “fill”). A polygon can be thought of as an irregularly-shaped point and is styled in similar ways to points. Example polygons layer The polygons layer used below contains county information for a fictional country. For reference, the attribute table for the polygons is included below. 6.4. CSS Styling 531 GeoServer User Manual, Release 2.15.1 fid (Feature ID) polygon.1 polygon.2 polygon.3 polygon.4 polygon.5 polygon.6 polygon.7 polygon.8 name (County name) Irony County Tracker County Dracula County Poly County Bearing County Monte Cristo County Massive County Rhombus County pop (Population) 412234 235421 135022 1567879 201989 152734 67123 198029 Download the polygons shapefile Simple polygon This example shows a polygon filled in blue. Fig. 6.139: Simple polygon Code * { fill: #000080; } 1 2 3 Details This simple rule applies a dark blue (#000080) fill to all the polygons in the dataset. 532 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Note: The light-colored borders around the polygons in the figure are artifacts of the renderer caused by the polygons being adjacent. There is no border in this style. Simple polygon with stroke This example adds a 2 pixel white stroke to the Simple polygon example. Fig. 6.140: Simple polygon with stroke Code * { fill: #000080; stroke: #FFFFFF; stroke-width: 2; } 1 2 3 4 5 Details This example is similar to the Simple polygon example above, with the addition of the “stroke” and “stroke-width” attributes, that add a white, 2 pixels wide border around each polygon. 6.4. CSS Styling 533 GeoServer User Manual, Release 2.15.1 Transparent polygon This example builds on the Simple polygon with stroke example and makes the fill partially transparent by setting the opacity to 50%. Fig. 6.141: Transparent polygon Code * { fill: #000080; fill-opacity: 0.5; stroke: #FFFFFF; stroke-width: 2; } 1 2 3 4 5 6 Details This example is similar to the Simple polygon with stroke example, save for defining the fill’s opacity in line 3. The value of 0.5 results in partially transparent fill that is 50% opaque. An opacity value of 1 would draw the fill as 100% opaque, while an opacity value of 0 would result in a completely transparent (0% opaque) fill. In this example, since the background is white, the dark blue looks lighter. Were the points imposed on a dark background, the resulting color would be darker. Graphic fill This example fills the polygons with a tiled graphic. 534 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.142: Graphic fill Code * { fill: url("colorblocks1.png"); fill-mime: 'image/png'; } 1 2 3 4 Details This style fills the polygon with a tiled graphic. The graphic is selected providing a url for the fill, which in this case is meant to the relative to the styles directory contained within the data directory (an absolute path could have been provided, as well as a internet reference). Line 3 specifies that the image itself is a png (by default the code assumes jpegs are used and will fail to parse the file unless we specify its mime type). The size of the image is not specified, meaning the native size is going to be used. In case a rescale is desired, the “fill-size” attribute can be used to force a different size. Fig. 6.143: Graphic used for fill 6.4. CSS Styling 535 GeoServer User Manual, Release 2.15.1 Hatching fill This example fills the polygons with a hatching pattern. Fig. 6.144: Hatching fill Code * { fill: symbol("shape://times"); :fill { size: 16; stroke: #990099; stroke-width: 1px; } } 1 2 3 4 5 6 7 8 Details In this example the fill is specified to be the “shape://times” symbol, which is going to be tiled creating a cross-hatch effect. The details of the hatch are specified at line 3*, where the pseudoselector “:fill” is used to match the contents of the fill, and specify that we want a symbol large 16 pixels (the larger the symbol, the coarser the cross hatch will be), and painted with a 1 pixel wide purple stroke. 536 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Polygon with default label This example shows a text label on the polygon. In the absence of any other customization, this is how a label will be displayed. Fig. 6.145: Polygon with default label Code * { fill: #40FF40; stroke: white; stroke-width: 2; label: [name]; font-fill: black; } 1 2 3 4 5 6 7 Details The single rule in the CSS applies to all feature: first it fills all polygons a light green with white outline, and thn applies the “name” attribute as the label, using the default font (Times), with black color and default font size (10 px). Label halo This example alters the look of the Polygon with default label by adding a white halo to the label. 6.4. CSS Styling 537 GeoServer User Manual, Release 2.15.1 Fig. 6.146: Label halo Code * { fill: #40FF40; stroke: white; stroke-width: 2; label: [name]; font-fill: black; halo-color: white; halo-radius: 3; } 1 2 3 4 5 6 7 8 9 Details This example builds on Polygon with default label, with the addition of a halo around the labels on lines 7-8. A halo creates a color buffer around the label to improve label legibility. Line 9 sets the radius of the halo, extending the halo 3 pixels around the edge of the label, and line 8 sets the color of the halo to white. Since halos are most useful when set to a sharp contrast relative to the text color, this example uses a white halo around black text to ensure optimum readability. Polygon with styled label This example improves the label style from the Polygon with default label example by centering the label on the polygon, specifying a different font name and size, and setting additional label placement optimizations. 538 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.147: Polygon with styled label Code * { fill: #40FF40; stroke: white; stroke-width: 2; label: [name]; font-family: Arial; font-size: 11px; font-style: normal; font-weight: bold; font-fill: black; label-anchor: 0.5 0.5; label-auto-wrap: 60; label-max-displacement: 150; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Details This example is similar to the Polygon with default label example, with additional styling options for the labels. The font is setup to be Arial, 11 pixels, “normal” (as opposed to “italic”) and bold. The “label-anchor” affects where the label is placed relative to the centroid of the polygon, centering the label by positioning it 50% (or 0.5) of the way horizontally along the centroid of the polygon, as well as vertically in exactly the same way. Finally, there are two added touches for label placement optimization: The “label-auto-wrap” attribute ensures that long labels are 6.4. CSS Styling 539 GeoServer User Manual, Release 2.15.1 split across multiple lines by setting line wrapping on the labels to 60 pixels, whilst the “label-max-displacement” allows the label to be displaced by up to 150 pixels. This ensures that labels are compacted and less likely to spill over polygon boundaries. Notice little Massive County in the corner, whose label is now displayed. Attribute-based polygon This example styles the polygons differently based on the “pop” (Population) attribute. Fig. 6.148: Attribute-based polygon Code [parseLong(pop) < 200000] { fill: #66FF66; } 1 2 3 4 [parseLong(pop) >= 200000] [parseLong(pop) < 500000] { fill: #33CC33; } 5 6 7 8 [parseLong(pop) >= 500000] { fill: #009900; } 9 10 11 Details 540 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Note: Refer to the Example polygons layer to see the attributes for the layer. This example has eschewed labels in order to simplify the style, but you can refer to the example Polygon with styled label to see which attributes correspond to which polygons. Each polygon in our fictional country has a population that is represented by the population (“pop”) attribute. This style contains three rules that alter the fill based on the value of “pop” attribute, with smaller values yielding a lighter color and larger values yielding a darker color. The three rules are designed as follows: Rule order 1 2 3 Rule name SmallPop MediumPop LargePop Population (“pop”) Less than 200,000 200,000 to 500,000 Greater than 500,000 Color #66FF66 #33CC33 #009900 The order of the rules does not matter in this case, since each shape is only rendered by a single rule. The first rule fills light green all polygons whose “pop” attribute is below 200,000, the second paints medium green all poygons whose “pop” attribute is between 200,000 and 500,000, while the third rule paints dark green the remaining polygons. What’s interesting in the filters is the use of the “parseLong” filter function: this function is necessary because the “pop” attribute is a string, leaving it as is we would have a string comparison, whilst the function turns it into a number, ensuring proper numeric comparisons instead. Zoom-based polygon This example alters the style of the polygon at different zoom levels. Code * { fill: #0000CC; stroke: black; } 1 2 3 4 5 [@sd < 100M] { stroke-width: 7; label: [name]; label-anchor: 0.5 0.5; font-fill: white; font-family: Arial; font-size: 14; font-weight: bold; } 6 7 8 9 10 11 12 13 14 6.4. CSS Styling 541 GeoServer User Manual, Release 2.15.1 Fig. 6.149: Zoom-based polygon: Zoomed in Fig. 6.150: Zoom-based polygon: Partially zoomed 542 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.151: Zoom-based polygon: Zoomed out 15 [@sd > 100M] [@sd < 200M] { stroke-width: 4; } 16 17 18 19 [@sd > 200M] { stroke-width: 1; } 20 21 22 Details It is often desirable to make shapes larger at higher zoom levels when creating a natural-looking map. This example varies the thickness of the lines according to the zoom level. Polygons already do this by nature of being two dimensional, but another way to adjust styling of polygons based on zoom level is to adjust the thickness of the stroke (to be larger as the map is zoomed in) or to limit labels to only certain zoom levels. This is ensures that the size and quantity of strokes and labels remains legible and doesn’t overshadow the polygons themselves. Zoom levels (or more accurately, scale denominators) refer to the scale of the map. A scale denominator of 10,000 means the map has a scale of 1:10,000 in the units of the map projection. Note: Determining the appropriate scale denominators (zoom levels) to use is beyond the scope of this example. This style contains three rules, defined as follows: 6.4. CSS Styling 543 GeoServer User Manual, Release 2.15.1 Rule order Rule name Scale denominator 1 2 3 Large Medium Small 1:100,000,000 or less 1:100,000,000 to 1:200,000,000 Greater than 1:200,000,000 Stroke width 7 4 2 Label play? Yes No No dis- The first rule (lines 1-4) defines the attributes that are not scale dependent: dark blue fill, black outline. The second (lines 6-14) rule provides specific overrides for the higher zoom levels, asking for a large stroke (7 pixels) and a label, which is only visible at this zoom level. The label is white, bold, Arial 14 pixels, its contents are coming form the “name” attribute. The third rule (lines 16-18) specifies a stroke width of 4 pixels for medium zoom levels, whilst for low zoom levels the stroke width is set to 1 pixel by the last rule (lines 20-22). The resulting style produces a polygon stroke that gets larger as one zooms in and labels that only display when zoomed in to a sufficient level. Rasters Rasters are geographic data displayed in a grid. They are similar to image files such as PNG files, except that instead of each point containing visual information, each point contains geographic information in numerical form. Rasters can be thought of as a georeferenced table of numerical values. One example of a raster is a Digital Elevation Model (DEM) layer, which has elevation data encoded numerically at each georeferenced data point. Example raster The raster layer that is used in the examples below contains elevation data for a fictional world. The data is stored in EPSG:4326 (longitude/latitude) and has a data range from 70 to 256. If rendered in grayscale, where minimum values are colored black and maximum values are colored white, the raster would look like this: Download the raster file Two-color gradient This example shows a two-color style with green at lower elevations and brown at higher elevations. 544 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.152: Raster file as rendered in grayscale Fig. 6.153: Two-color gradient Code * { raster-channels: auto; raster-color-map: color-map-entry(#008000, 70) color-map-entry(#663333, 256); } 1 2 3 4 5 6 Details There is a single rule which applies a color map to the raster data. The “raster-channels” attribute activates raster symbolization, the “auto” value is indicates that we are going to use the default choice of bands to symbolize the output (either gray or RBG/RGBA depending on the input data). There is also the possibility of providing a band name or a list of band names in case we want to choose specific bands out of a multiband input, e.g., “1” or “1 3 7”. The “raster-color-map” attribute builds a smooth gradient between two colors corresponding to two elevation values. Each “color-mapentry” represents one entry or anchor in the gradient: • The first argument is the color 6.4. CSS Styling 545 GeoServer User Manual, Release 2.15.1 • The second argument is the value at which we anchor the color • An optional third argument could specify the opacity of the pixels, as a value between 0 (fully transparent) and 1 (fully opaque). The default, when not specified, is 1, fully opaque. Line 4 sets the lower value of 70, which is styled a opaque dark green (#008000), and line 5 sets the upper value of 256, which is styled a opaque dark brown (#663333). All data values in between these two quantities will be linearly interpolated: a value of 163 (the midpoint between 70 and 256) will be colored as the midpoint between the two colors (in this case approximately #335717, a muddy green). Transparent gradient This example creates the same two-color gradient as in the Two-color gradient as in the example above but makes the entire layer mostly transparent by setting a 30% opacity. Fig. 6.154: Transparent gradient Code * { raster-channels: auto; raster-opacity: 0.3; raster-color-map: color-map-entry(#008000, 70) color-map-entry(#663333, 256); } 1 2 3 4 5 6 Details This example is similar to the Two-color gradient example save for the addition of line 3, which sets the opacity of the layer to 0.3 (or 30% opaque). An opacity value of 1 means that the shape is drawn 100% opaque, while an opacity value of 0 means that the shape is rendered as completely transparent. The value of 0.3 means that the the raster partially takes on the color and style of whatever is 546 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 drawn beneath it. Since the background is white in this example, the colors generated from the “raster-color-map” look lighter, but were the raster imposed on a dark background the resulting colors would be darker. Brightness and contrast This example normalizes the color output and then increases the brightness by a factor of 2. Fig. 6.155: Brightness and contrast Code * { raster-channels: auto; raster-contrast-enhancement: normalize; raster-gamma: 0.5; raster-color-map: color-map-entry(#008000, 70) color-map-entry(#663333, 256); } 1 2 3 4 5 6 7 Details This example is similar to the Two-color gradient, save for the addition of the contrast enhancement and gamma attributes on lines 3-4. Line 3 normalizes the output by increasing the contrast to its maximum extent. Line 4 then adjusts the brightness by a factor of 0.5. Since values less than 1 make the output brighter, a value of 0.5 makes the output twice as bright. Three-color gradient This example creates a three-color gradient in primary colors. In addition, we want to avoid displaying data outside of the chosen range, leading some data not to be rendered at all. 6.4. CSS Styling 547 GeoServer User Manual, Release 2.15.1 Fig. 6.156: Three-color gradient Code * { raster-channels: auto; raster-color-map: color-map-entry(black, 150, 0) color-map-entry(blue, 150) color-map-entry(yellow, 200) color-map-entry(red, 250) color-map-entry(black, 250, 0) } 1 2 3 4 5 6 7 8 9 Details This example creates a three-color gradient, with two extra rules to make ranges of color disappear. The color map behavior is such that any value below the lowest entry gets the same color as that entry, and any value above the last entry gets the same color as the last entry, while everything in between is linearly interpolated (all values must be provided from lower to higher). Line 4 associates value 150 and below with a transparent color (0 opacity, that is, fully transparent), and so does line 8, which makes transparent every value above 250. The lines in the middle create a gradient going from blue, to yellow, to red. Alpha channel This example creates an “alpha channel” effect such that higher values are increasingly transparent. Code * { raster-channels: auto; raster-color-map: color-map-entry(#008000, 70) 1 2 3 4 color-map-entry(#663333, 256, 0); ,→ } 5 548 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.157: Alpha channel Details An alpha channel is another way of referring to variable transparency. Much like how a gradient maps values to colors, each entry in a “raster-color-map” can have a value for opacity (with the default being 1.0 or completely opaque). In this example, there is a “raster-color-map” with two entries: line 3 specifies the lower bound of 70 be colored dark green (#008000), while line 4 specifies the upper bound of 256 also be colored dark green but with an opacity value of 0. This means that values of 256 will be rendered at 0% opacity (entirely transparent). Just like the gradient color, the opacity is also linearly interpolated such that a value of 163 (the midpoint between 70 and 256) is rendered at 50% opacity. Discrete colors This example shows a gradient that is not linearly interpolated but instead has values mapped precisely to one of three specific colors. Fig. 6.158: Discrete colors 6.4. CSS Styling 549 GeoServer User Manual, Release 2.15.1 Code * { raster-channels: auto; raster-color-map-type: intervals; raster-color-map: color-map-entry(#008000, 150) color-map-entry(#663333, 256); } 1 2 3 4 5 6 Details Sometimes color bands in discrete steps are more appropriate than a color gradient. The “raster-color-map-type: intervals” attribute sets the display to output discrete colors instead of a gradient. The values in each entry correspond to the upper bound for the color band such that colors are mapped to values less than the value of one entry but greater than or equal to the next lower entry. For example, line 4 colors all values less than 150 to dark green (#008000) and line 5 colors all values less than 256 but greater than or equal to 150 to dark brown (#663333). Many color gradient This example shows a gradient interpolated across eight different colors. Fig. 6.159: Many color gradient Code * { raster-channels: auto; raster-color-map: color-map-entry(black, 95) color-map-entry(blue, 110) color-map-entry(green, 135) color-map-entry(red, 160) color-map-entry(purple, 185) 1 2 3 4 5 6 7 8 550 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 color-map-entry(yellow, 210) color-map-entry(cyan, 235) color-map-entry(white, 256) 9 10 11 } 12 Details This example is similar to the previous ones, and creates a color gradient between 8 colors as reported in the following table Entry number 1 2 3 4 5 6 7 8 Value 95 110 135 160 185 210 235 256 Color Black Blue Green Red Purple Yellow Cyan White 6.4.14 Styling examples The following pages contain CSS styling examples grouped by specific topics. Fills with randomized symbols It is possible to generate fills by randomly repeating a symbol in the polygons to be filled. Please refer to the equivalent SLD chapter for details on the meaning of the various options. Simple random distribution Here is an example distributing up to 50 small “slash” symbols in a 100x100 pixel tile (in case of conflicts the symbol will be skipped), enabling random symbol rotation), and setting the seed to “5” to get a distribution different than the default one: * { fill: symbol("shape://slash"); :fill { size: 8; stroke: blue; stroke-width: 4; stroke-linecap: round; }; stroke: black; fill-random: grid; fill-random-seed: 5; fill-random-rotation: free; 6.4. CSS Styling 551 GeoServer User Manual, Release 2.15.1 fill-random-symbol-count: 50; fill-random-tile-size: 100; } Fig. 6.160: Random distribution of a diagonal line Thematic map using point density Randomized distributions can also be used for thematic mapping, for example, here is the SLD for a version of topp:states that displays the number of inhabitantìs varying the density of a random point distribution: * { fill: symbol("circle"); stroke: black; fill-random: grid; fill-random-tile-size: 100; :fill { size: 2; fill: darkgray; }; /* @title low */ [PERSONS < 2000000] { fill-random-symbol-count: 50; }; /* @title mid */ [PERSONS >= 2000000] [PERSONS < 4000000] { fill-random-symbol-count: 150; }; /* @title high */ [PERSONS >= 4000000] { fill-random-symbol-count: 500; } } 552 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.161: Thematic map via point density approach Using transformation functions The transformation functions supported described in SLD and described in the equivalent SLD chapter are also available in CSS, the following shows examples of how they can be used. Recode The Recode filter function transforms a set of discrete values for an attribute into another set of values, by applying a (input, output) mapping onto the values of the variable/expression that is provided as the first input of the function. Consider a chloropleth map of the US states dataset using the fill color to indicate the topographic regions for the states. The dataset has an attribute SUB_REGION containing the region code for each state. The Recode function is used to map each region code into a different color. Note: It is to be noted that the following example specifies colors as hex string as opposed to native CSS color names, this is because the function syntax is expressed in CQL, which does not have support for native CSS color names. * { fill: [recode(strTrim(SUB_REGION), 'N Eng', '#6495ED', 'Mid Atl', '#B0C4DE', 'S Atl', '#00FFFF', 'E N Cen', '#9ACD32', 'E S Cen', '#00FA9A', 'W N Cen', '#FFF8DC', 'W S Cen', '#F5DEB3', 'Mtn', '#F4A460', 'Pacific', '#87CEEB')]; stroke: lightgrey; label: [STATE_ABBR]; font-family: 'Arial'; font-fill: black; 6.4. CSS Styling 553 GeoServer User Manual, Release 2.15.1 label-anchor: 0.5 0.5; } Categorize The Categorize filter function transforms a continuous-valued attribute into a set of discrete values by assiging ranges of values and turning them into a color, size, width, opacity, etc. In the following example a coropleth map is build associating a color to the state population density in the ranges [ <= 20], [20 - 100], and [ > 100]. * { fill: [categorize( PERSONS / LAND_KM, '#87CEEB', 20, '#FFFACD', 100, '#F08080')]; stroke : lightgrey; label: [STATE_ABBR]; font-family: 'Arial'; font-fill: black; label-anchor: 0.5 0.5; } 554 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Interpolate The Interpolate filter function transforms a continuous-valued attribute into another continuous range of values by applying piecewise interpolation. The result will work for numeric values such as size, width, opacity when operating in numeric interpolation method (the default), and for colors when working in color mode. The type of curve fitting the specified points can be either linear (the default), cubic or cosine, these values are known as the interpolation mode. Both the interpolation method and mode are optional, and if provided, they are added at the end of the input list. In the following example the state population is mapped to a continuous color scale in a rather compact way using the interpolate function: * { fill: [Interpolate( PERSONS, 0, '#FEFEEE', 9000000, '#00FF00', 23000000, '#FF0000', 'color', 'linear')]; stroke : lightgrey; label: [STATE_ABBR]; font-family: 'Arial'; font-fill: black; label-anchor: 0.5 0.5; } KML Detecting raster to vector switch in KML GeoServer 2.4 added a new icon server that KML output uses to make sure the point symbolisers look the same as in a normal WMS call no matter what scale they are looked at. 6.4. CSS Styling 555 GeoServer User Manual, Release 2.15.1 This may pose some issue when working in the default KML generation mode, where the map is a ground overlay up to a certain scale, and switches to a vector, clickable representation once the number of features in the visualization fall below a certain scale (as controlled by the KMSCORE parameter): the end user is not informed “visually” that the switch happened. There is however a custom enviroment variable, set by the KML generator, that styles can leverage to know whether the KML generation is happening in ground overlay or vector mode. The following example leverages this function to show a larger point symbol when points become clickable: * { mark: symbol("circle"); } :mark [env('kmlOutputMode') = 'vector'] { size: 8; } :mark { size: 4; fill: yellow; stroke: black; } This will result in the following output: Fig. 6.162: Raster output, points are not yet clickable One important bit about the above CSS is that the order of the rules is important. The CSS to SLD translator uses specificity to decide which rule overrides which other one, and the specificity is driven, at the time of writing, only by scale rules and access to attributes. The filter using the kmlOutputMode filter is not actually using any feature attribute, so it has the same specificity as the catch all :mark rule. Putting it first ensures that it overrides the catch all rule anyways, while putting it second would result in the output size being always 4. 556 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.163: Vector output, points are clickable and painted as larger icons Getting KML marks similar to the old KML encoder The old KML generator (prior to GeoServer 2.4) was not able to truly respect the marks own shape, and as a result, was simply applying the mark color to a fixed bull’s eye like icon, for example: Starting with GeoServer 2.4 the KML engine has been rewritten, and among other things, it can produce an exact representation of the marks, respecting not only color, but also shape and stroking. However, what if one want to reproduce the old output look? The solution is to leverage the ability to respect marks appearance to the letter, and combine two superimposed marks to generate the desired output: * { mark: symbol('circle'), symbol('circle'); mark-size: 12, 4; } :nth-mark(1) { fill: red; stroke: black; stroke-width: 2; 6.4. CSS Styling 557 GeoServer User Manual, Release 2.15.1 } :nth-mark(2) { fill: black; } Which results in the following Google Earth output: Miscellaneous Markers sized by an attribute value The following produces square markers at each point, but these are sized such that the area of each marker is proportional to the REPORTS attribute. When zoomed in (when there are less points in view) the size of the markers is doubled to make the smaller points more noticeable. * { mark: symbol(square); } [@sd > 1M] :mark { size: [sqrt(REPORTS)]; } /* So ,→that single-report points can be more easily seen */ [@sd < 1M] :mark { size: [sqrt(REPORTS)*2]; } This example uses the sqrt function. There are many functions available for use in CSS and SLD. For more details read - Filter Func558 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 tion Reference Specifying a geometry attribute In some cases, typically when using a database table with multiple geometry columns, it’s necessary to specify which geometry to use. For example, let’s suppose you have a table containing routes start and end both containing point geometries. The following CSS will style the start with a triangle mark, and the end with a square. * { geometry: [start], [end]; mark: symbol(triangle), symbol(square); } Generating a geometry (Geometry Transformations) Taking the previous example a bit further, we can also perform computations on-the-fly to generate the geometries that will be drawn. Any operation that is available for GeoServer Geometry transformations in SLD is also available in CSS styles. To use them, we simply provide a more complex expression in the geometry property. For example, we could mark the start and end points of all the paths in a line layer (you can test this example out with any line layer, such as the sf:streams layer that is included in GeoServer’s default data directory.) * { geometry: [startPoint(the_geom)], [endPoint(the_geom)]; mark: symbol(triangle), symbol(square); ,→ } Rendering different geometry types (lines/points) with a single style As one more riff on the geometry examples, we’ll show how to render both the original line and the start/endpoints in a single style. This is accomplished by using stroke-geometry and mark-geometry to specify that different geometry expressions should be used for symbols compared with strokes. * { stroke-geometry: [the_geom]; stroke: blue; mark-geometry: ,→[startPoint(the_geom)], [endPoint(the_geom)]; mark: ,→ symbol(triangle), symbol(square); } 6.4. CSS Styling 559 GeoServer User Manual, Release 2.15.1 6.5 YSLD Styling This module adds support for the YSLD styling language. YSLD is a YAML based language which closely matches the stucture of SLD, and the internal data model that GeoServer’s renderer uses. For details on YSLD syntax see the reference below or the GeoTools documentation. YSLD is not a part of GeoServer by default, but is available as an optional install. 6.5.1 Installing the GeoServer YSLD extension 1. Download the extension from the nightly GeoServer extension builds. Warning: Make sure to match the version of the extension to the version of the GeoServer instance! 2. Extract the contents of the archive into the WEB-INF/lib directory of the GeoServer installation. 6.5.2 GeoServer Specific Extensions GeoWebCache Integration When defining rules in terms of zoom levels, you can use the zoom level from a gridset defined in the integrated GeoWebCache instance. For instance, if your GWC had a gridset named CanadaLCCQuad and you wanted a style rule to apply to levels 0-2 of that gridset you could use the following: grid: name: CanadaLCCQuad rules: - zoom: [0,2] point: ... 6.5.3 YSLD reference This section will detail the usage and syntax of the YSLD markup language. As YSLD is heavily modeled on YAML, it may be useful to refer to the YAML specification for basic syntax. 560 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Structure Here is a simple example of a YSLD style containing a single rule inside a single feature style: name: style_example title: An example of YSLD styling abstract: Used in the User Manual of GeoServer feature-styles: - rules: - name: all title: Every feature will be styled this way symbolizers: - polygon: fill-color: '#808080' fill-opacity: 0.5 stroke-color: '#000000' stroke-opacity: 0.75 This would style every polygon feature in a given layer with the given RGB color codes (a medium gray for a fill and black for the outline), with the given opacities for both fill and stroke being given in decimals indicating percentage (so 0.5 is 50% opaque). Note: For more details on syntax, please see the section on symbolizers. The structure of a typical YSLD file is as follows: 6.5. YSLD Styling 561 GeoServer User Manual, Release 2.15.1 Structure Variable definitions Scale grid / zoom levels style header Description For common style settings feature style Independent block that can contain one or many rules. rule Directive that can contain one or many symbolizers. filter A rule “includes” all features unless made to be selective by the use of a filter. symbolizers basic unit of a style containing the actual visualization instructions for individual features. Used to define style based on tile set zoom level Document name, title, and abstract followed by feature-styles The structure YSLD files is outlined using indentation. Fig. 6.164: Structure of YSLD style_example Property syntax Individual statements (or directives) in a YSLD styling document are designed as key-value, or property-value pairs of the following 562 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 form: : The is a string denoting the property name, while the can be one of a number of different types depending on context. These different types require slightly different markup, as shown in the following table: Type Integer Float Text Color Syntax Value only Value only Quotes • ‘# + six digits’ (hex) • rgb(r,g,b) (decimal) • Text (named colors) Example 12 0.75 Title • '#FF00FF' • rgb(255, 0,255) • fuchsia Tuple Brackets [0,15000] Filter or other expression ${} ${type = road} Notes Quotes allowed as well Quotes allowed as well Spaces, colons, and other special characters are allowed. If value is amiguous, use single quotes. Used when specifying RGB colors. For hex, use '#RRGGBB' with each two character pair having a value from 00 to FF. For decimal, use rgb(rrr, ggg,bbb) with each ordinate having a value from 0 to 255. Quotes are not required when using named colors. Use two single quotes to denote blank entries in the tuple (for example: ['#FFFFFF',0,0,'']). If attribute name is ambiguous, encase in brackets (for example: ${[type] = road}). If value is ambiguous, use single quotes (${type = 'road'}). Expressions Throughout the reference guide, there are references to values that are denoted by . An expression is a flexible term meaning that the value can be one of the following kinds of objects: • Literal (scalar or string) • Attribute name • Function If using a function, it must evaluate to match the type expected by the property. Mappings and lists Note: The following discussion is taken from basic YAML syntax. Please refer to the YAML specification if necessary. There are three types of objects in a YSLD document: 1. Scalar, a simple value 6.5. YSLD Styling 563 GeoServer User Manual, Release 2.15.1 2. Mapping, a collection of key-value (property-value) pairs 3. List, any collection of objects. A list can contain mappings, scalars, and even other lists. Lists require dashes for every entry, while mappings do not. For example, a symbolizer block is a list, so every entry requires its own dash: - symbolizer: - polygon: ... - text: ... The point: and text: objects (the individual symbolizers themselves) are mappings, and as such, the contents do not require dashes, only indents: - polygon: stroke-color: '#808080' fill-color: '#FF0000' The dash next to polygon means that the item itself is contained in a list, not that it contains a list. And the placement of the dash is at the same level of indentation as the list title. It is sometimes not obvious whether an object should be a list (and use dashes) or a mapping (and not use dashes), so please refer to this table if unsure: Object Feature style Rule Symbolizer Individual symbolizers (contents) Transform Color table (for raster symbolizers) Type List List List Mapping Mapping List Indentation Indentation is very important in YSLD. All directives must be indented to its proper place to ensure proper hierarchy. Improper indentation will cause a style to be rendered incorrectly, or not at all. For example, the polygon symbolizer, since it is a mapping, contains certain parameters inside it, such as the color of the fill and stroke. These must be indented such that they are “inside” the polygon block. In this example, the following markup is correct: - polygon: fill-color: '#808080' 564 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 fill-opacity: 0.5 stroke-color: black stroke-opacity: 0.75 The parameters inside the polygon (symbolizer) are indented, meaning that they are referencing the symbolizer and are not “outside it.” Compare to the following incorrect markup: - polygon: fill-color: '#808080' fill-opacity: 0.5 stroke-color: black stroke-opacity: 0.75 The parameters that are relevant to the polygon block here need to be contained inside that block. Without the parameters being indented, they are at the same “level” as the polygon block, and so will not be interpreted correctly. Note: For more details on symbolizer syntax, please see the section on symbolizers. Wrapped lines Long lines can be wrapped by indenting each subsequent line in the text block. New line characters will be converted to spaces, so each line should not end with a space. So in a situation with a long value: - name: shortname title: Longer name abstract: This is ,→a really long abstract that in no way is ever likely ,→to fit on a single line on most people's displays. This can be altered to look like: - name: shortname title: Longer name abstract: ,→This is a really long abstract that in no way ,→ is ever likely to fit on a single line on most people's displays. In both cases, the value for abstract is unchanged. Wrapped lines can be done between properties and values as well. So this single line: stroke-width: ${roadwidth / 500} Can be altered to look like: 6.5. YSLD Styling 565 GeoServer User Manual, Release 2.15.1 stroke-width: ${roadwidth / 500} The only constraint with using wrapped lines is that the subsequent lines need to be indented. Comments Comments are allowed in YSLD, both for descriptive reasons and to remove certain styling directives without deleting them outright. Comments are indicated by a # as the first non-whitespace character in a line. For example: # This is a line symbolizer - line: stroke-color: '#000000' stroke-width: 2 # stroke-width: 3 The above would display the lines with width of 2; the line showing a width of 3 is commented out. Comment blocks do not exist, so each line of a comment will need to be indicated as such: - line: stroke-color: '#000000' stroke-width: 2 #- line: # stroke-color: '#FF0000' # stroke-width: 3 Note: Comments are not preserved when converting to SLD. Feature Styles In YSLD, a Feature Style is a block of styling Rules. The Feature Style is applied to a single feature type and drawn in an off-screen buffer. Fig. 6.165: The feature style element The purpose of a Feature Style is to specify drawing order. The buffer for the first Feature Style will be drawn first, while buffer for the second Feature Style will be processed after that, etc. When 566 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 drawing is complete the buffers will composed into the final drawn map. A Feature Style is a top-level element in a YSLD style. Consider the following hierarchy: • Feature Style 1 – Rule 1a – Rule 1b • Feature Style 2 – Rule 2a – Rule 2b – Rule 2c In this case, the rules contained inside Feature Style 1 will be processed and their symbolizers drawn first. After Rule 1a and 1b are processed, the renderer will move on to Feature Style 2, where Rule 2a, 2b, and 2c will then be processed and their symbolizers drawn. Fig. 6.166: Feature style order Drawing order The order of feature styles is significant, and also the order of rules inside feature styles is significant. Rules inside a feature style are all applied to each feature at once. After all of the rules in a feature style have been applied to each feature, the next feature style will start again, applying rules to each feature. The off-screen buffer for each feature style is merged together during composition. These buffers are merged in the order defined by the feature styles. In this way, using multiple feature styles is a way of specifying z-order. Consider the same hierarchy as above. Given a layer that contains three features, the rules will be applied as follows: Feature style 1 will draw an off-screen buffer: 1. Rule 1a is applied to the first feature, followed by rule 1b 2. Rule 1a is applied to the second feature, followed by rule 1b 6.5. YSLD Styling 567 GeoServer User Manual, Release 2.15.1 3. Rule 1a is applied to the third feature, followed by rule 1b Fig. 6.167: Feature style 1 buffer Feature style 2 will draw an off-screen buffer: 1. Rule 2a is applied to the first feature, followed by rule 2b and then rule 2c 2. Rule 2a is applied to the second feature, followed by rule 2b and then rule 2c 3. Rule 2a is applied to the third feature, followed by rule 2b and then rule 2c Fig. 6.168: Feature style 2 buffer This final map is produced by composition: 1. The buffer for feature style 1 is drawn 2. The buffer for feature style 2 is drawn 3. Any labeling is drawn on top Fig. 6.169: Composition of both feature styles If you need a rule to apply on top of other rules, use a second feature style. A useful case for this is for lines representing bridges or overpasses. In order to ensure that the bridge lines always display on “top” of other lines (which in a display that includes, they would need to be applied using a second feature style.) Syntax The following is the basic syntax of a feature style. Note that the contents of the block are not all expanded here. feature-styles: - name: title: abstract: transform: ... 568 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 rules: - ... x-firstMatch: x-composite: x-composite-base: where: Property name title abstract transform rules Required?Description No Internal reference to the feature style. It is recommended that the value be lower case and contain no spaces. No Human-readable name of the feature style. Exposed as a name for the group of rules contained in the feature style. No Longer description of the feature style. No Rendering transformation information. Yes List of styling rules. Default value Blank Blank Blank N/A N/A The following properties are equivalent to SLD “vendor options”. Property x-FirstMatch Required?Description No Stops rule evaluation after the first match. Can make the rendering more efficient by reducing the number of rules that need to be traversed by features, as well as simplyfing the rule filters. x-composite No Allows for both alpha compositing and color blending options between buffers. There are many options; see below. x-composite-baseNo Allows the rendering engine to use that featurestyle as a “base”, and will compose all subsequent feature-styles and layers on top of it, until another base is found. Once the full set of layers against a base is composed, then the base itself will be composed against the next set of composed layers using its own compositing operator, if present. This is useful to fine-tune the use of x-composite, and to make sure that only the desired content is composited/blended and not all of the drawn content. Default value false N/A false Compositing and blending By default, multiple feature styles are drawn with one buffer on top of the other. However, using the x-composite and x-composite-base options, one can customize the way that buffers are displayed. The following two tables show the possible alpha compositing and color blending values for the x-composite option. Note that in the tables below, source refers to the buffer that is drawn on top, while destination refers to the buffer that the source is drawn on top of. Alpha compositing 6.5. YSLD Styling 569 GeoServer User Manual, Release 2.15.1 Alpha compositing controls how buffers are merged using the transparent areas of each buffer. 570 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Value copy Description Only the source will be present in the output. destination Only the destination will be present in the output. source-over The source is drawn over the destination, and the destination is visible where the source is transparent. Opposite of destination-over. This is the default value for x-composite. destination-overThe source is drawn below the destination, and is visible only when the destination is transparent. Opposite of source-over. source-in The source is visible only when overlapping some non-transparent pixel of the destination. This allows the background map to act as a mask for the layer/feature being drawn. Opposite of destination-in. destination-in The destination is retained only when overlapping some non transparent pixel in the source. This allows the layer/feature to be drawn to act as a mask for the background map. Opposite of source-in. source-out The source is retained only in areas where the destination is transparent. This acts as a reverse mask when compared to source-in. destination-out The destination is retained only in areas where the source is transparent. This acts as a reverse mask when compared to destination-in. source-atop 6.5. YSLD Styling The destination is drawn fully, while the source is drawn only where it intersects the destination. 571 destination-atopThe source is drawn fully, and the destination is drawn over the source only where it intersects it. GeoServer User Manual, Release 2.15.1 Color blending Color blending allows buffers to be mixed during composition. 572 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Value multiply Description The source color is multiplied by the destination color and replaces the destination. The resulting color is always at least as dark as either the source or destination color. Multiplying any color with black results in black. Multiplying any color with white preserves the original color. screen Multiplies the complements of the source and destination color values, then complements the result. The end result color is always at least as light as either of the two constituent colors. Screening any color with white produces white; screening with black leaves the original color unchanged. overlay Multiplies the colors depending on the destination color value. Source colors overlay the destination while preserving highlights and shadows. The backdrop color is not replaced but is mixed with the source color to reflect the lightness or darkness of the backdrop. darken Selects the darker of the destination and source colors. The destination is replaced with the source only where the source is darker. lighten Selects the lighter of the destination and source colors. The destination is replaced with the source only where the source is lighter. color-dodge Brightens the destination color to reflect the source color. Drawing with black produces no changes. color-burn Darkens the destination color to reflect the source color. Drawing with white produces no change. hard-light Multiplies the colors, depending on the source color value. The effect is similar to shining a harsh spotlight on the destination. 6.5. YSLD Styling soft-light 573 Darkens or lightens the colors, depending on the source color value. The effect is similar to a diffused spotlight on the destination. GeoServer User Manual, Release 2.15.1 Note: For more details about the compositing and blending options, please see the GeoServer User Manual. Short syntax When a style has a single feature style, it is possible to omit the syntax for the feature style and start at the first parameter inside. So the following complete styles are both equivalent: feature-styles: - rules: - name: rule1 scale: [min,50000] symbolizers: - line: stroke-color: '#000000' stroke-width: 2 - name: rule2 scale: [50000,max] symbolizers: - line: stroke-color: '#000000' stroke-width: 1 rules: - name: rule1 scale: [min,50000] symbolizers: - line: stroke-color: '#000000' stroke-width: 2 - name: rule2 scale: [50000,max] symbolizers: - line: stroke-color: '#000000' stroke-width: 1 Examples Road casing This example shows how a smaller line can be drawn on top of a larger line, creating the effect of lines being drawn with a border or “casing”: feature-styles: - name: outer title: Outer line rules: - name: outer_rule symbolizers: 574 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 - line: stroke-color: stroke-width: - name: inner title: Inner line rules: - name: inner_rule symbolizers: - line: stroke-color: stroke-width: '#808080' 8 '#44FF88' 6 To draw the inner lines always on top of the outer lines we need to control the z-order. The outer_rule is encased in its own feature style and drawn into a distinct “Outer line” buffer. Next the inner_rule is encased in its own feature style and drawn into a distinct “Inner line” buffer. Fig. 6.170: Feature style buffers During composition these two off-screen buffers are combined into the the final map. Fig. 6.171: Final map composition When drawn, the outer line has a width of 8 pixels and the inner line has a width of 6 pixels, so the line “border” is 1 pixel (on each side). First match Given a style that has many rules with distinct outcomes, it may be advantageous to employ x-firstMatch so as to improve rendering efficiency and simplify those rules. This first example shows the standard way of creating rules for a dataset. There are villages, towns, and cities (type = 'village', type = 'town' or type = 'city') and they have an industry which could be either fishing or other values. 6.5. YSLD Styling 575 GeoServer User Manual, Release 2.15.1 Fig. 6.172: Example showing road casing Note: In order to simplify this example, the specifics of the point symbolizers have been replaced by Variables. In a real-world example, these would need to be defined in the YSLD as well. feature-styles: - name: without_first_match rules: - name: fishing_town filter: ${type = 'town' AND industry = 'fishing'} symbolizers: - point: <<: *fishingtown - name: fishing_city filter: ${type = 'city' AND industry = 'fishing'} symbolizers: - point: <<: *fishingcity - name: other_towns_cities filter: ,→${type IN ('town', 'city') AND industry <> 'fishing'} symbolizers: - point: <<: *othertownscities - name: other else: true symbolizers: - point: <<: *allotherplaces 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Using the x-firstMatch: fied: true parameter, the style is simpli- feature-styles: - name: with_first_match x-firstMatch: true rules: - name: fishing_town filter: ${type = 'town' AND industry = 'fishing'} symbolizers: - point: 1 2 3 4 5 6 7 8 576 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 <<: *fishingtown - name: fishing_city filter: ${type = 'city' AND industry = 'fishing'} symbolizers: - point: <<: *fishingcity - name: other_towns_cities filter: ${type IN ('town', 'city')} symbolizers: - point: <<: *othertownscities - name: other else: true symbolizers: - point: <<: *allotherplaces 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Specifically, the third rule no longer needs the extra AND industry <> 'fishing', because the previous two rules imply that any features remaining by this rule have that condition. Layer mask Given two layers (in this case, two three-band rasters), one can mask or “knock out” the other, making visible what’s beneath. Fig. 6.173: Top/source layer Note: Screenshots show data provided by Natural Earth. Layer 1 (top/source): feature-styles: - rules: - title: Top/source symbolizers: - raster: 1 2 3 4 5 6.5. YSLD Styling 577 GeoServer User Manual, Release 2.15.1 Fig. 6.174: Bottom/destination layer opacity: 1.0 x-composite: xor 6 7 Layer 2 (bottom/destination): feature-styles: - rules: - title: Bottom/destination symbolizers: - raster: opacity: 1.0 1 2 3 4 5 6 Fig. 6.175: Layer as mask Color inversion Given the same two layers as the previous example, one can display the difference of the colors of layers, which can have the effect of a color “inversion”. Layer 1 (top/source): 578 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 feature-styles: - rules: - title: Top/source symbolizers: - raster: opacity: 1.0 x-composite: difference 1 2 3 4 5 6 7 Layer 2 (bottom/destination): feature-styles: - rules: - title: Bottom/destination symbolizers: - raster: opacity: 1.0 1 2 3 4 5 6 Fig. 6.176: Layer as color inversion Rules A rule is a collection of styling directives, primarily consisting of symbolizers combined with optional conditional statements. • If a conditional statement exists in a rule, then the styling directives will only be carried out if the conditional returns true. Otherwise, the rule will be skipped. • If no conditional statement exists in a rule, then the styling directive will always be carried out. The types of conditional statements available to rules are: • Filters for attribute-based rendering • Scale for scale-based rendering Rules are contained within feature styles. There is no limit on the number of rules that can be created, and there is no restriction that all rules must be mutually exclusive (as in, some rules may apply to the same features). 6.5. YSLD Styling 579 GeoServer User Manual, Release 2.15.1 Syntax The following is the basic syntax of a rule. Note that the contents of the block are not all expanded; see the other sections for the relevant syntax. rules: - name: title: filter: else: scale: [,] symbolizers: - ... where: Property name title filter Required?Description No Internal reference to the feature style. It is recommended that the value be lower case and contain no spaces. No Human-readable description of what the rule accomplishes. No Filter expression which will need to evaluate to be true for the symbolizer(s) to be applied. Cannot be used with else. else No scale No symbolizers Yes Specifies whether the rule will be an “else” rule. An else rule applies when, after scale and filters are applied, no other rule applies. To make an else rule, set this option to true. Cannot be used with filter. Scale boundaries showing at what scales (related to zoom levels) the rule will be applied. Block containing one or more symbolizers. These contain the actual visualization directives. If the filter returns true and the view is within the scale boundaries, these symbolizers will be drawn. Default value Blank Blank Blank (meaning that the rule will apply to all features) false Visible at all scales N/A Short syntax When a style has a single rule inside a single feature style, it is possible to omit the syntax for both and start at the first parameter inside. So the following complete styles are equivalent: feature-styles: - rules: - symbolizers: - line: stroke-color: '#000000' stroke-width: 2 580 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 line: stroke-color: '#000000' stroke-width: 2 Examples Else filter Using filter and else together: rules: - name: small title: Small features filter: ${type = 'small'} symbolizers: - ... - name: large title: Large features filter: ${type = 'large'} symbolizers: - ... - name: else title: All other features else: true symbolizers: - ... In the above situation: • If a feature has a value of “small” in its type attribute, it will be styled with the “small” rule. • If a feature has a value of “large” in its type attribute, it will be styled with the “large” rule. • If a feature has a value of “medium” (or anything else) in its type attribute, it will be styled with the “else” rule. Else with scale Using filter, else, and scale together: rules: - name: small_zoomin scale: [min,10000] title: Small features when zoomed in filter: ${type = 'small'} symbolizers: - ... - name: small_zoomout scale: [10000,max] title: Small features when zoomed out filter: ${type = 'small'} symbolizers: - ... 6.5. YSLD Styling 581 GeoServer User Manual, Release 2.15.1 - name: else_zoomin scale: [min,10000] title: All other features when zoomed in else: true symbolizers: - ... - name: else_zoomout scale: [10000,max] title: All other features when zoomed out else: true symbolizers: - ... In the above situation: • If a feature has a value of “small” in its type attribute, and the map is a scale level less than 10,000, it will be styled with the “small_zoomin” rule. • If a feature has a value of anything else other than “small” in its type attribute, and the map is a scale level less than 10,000, it will be styled with the “else_zoomin” rule. • If a feature has a value of “small” in its type attribute, and the map is a scale level greater than 10,000, it will be styled with the “small_zoomout” rule. • If a feature has a value of anything else other than “small” in its type attribute, and the map is a scale level greater than 10,000, it will be styled with the “else_zoomout” rule. Symbolizers The basic unit of visualization is the symbolizer. There are five types of symbolizers: Point, Line, Polygon, Raster, and Text. Symbolizers are contained inside rules. A rule can contain one or many symbolizers. Note: The most common use case for multiple symbolizers is a geometry (point/line/polygon) symbolizer to draw the features plus a text symbolizer for labeling these features. Fig. 6.177: Use of multiple symbolizers Drawing order The order of symbolizers significant, and also the order of your data. 582 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 For each feature the rules are evaluated resulting in a list of symbolizers that will be used to draw that feature. The symbolizers are drawn in the order provided. Consider the following two symbolizers: symbolizers: - point: symbols: - mark: shape: square fill-color: '#FFCC00' - point: symbols: - mark: shape: triangle fill-color: '#FF3300' When drawing three points these symbolizers will be applied in order on each feature: 1. Feature 1 is drawn as a square, followed by a triangle: Fig. 6.178: Feature 1 buffer rendering 2. Feature 2 is drawn as a square, followed by a triangle. Notice the slight overlap with Feature 1: Fig. 6.179: Feature 2 buffer rendering 3. Feature 3 is drawn as a square, followed by a triangle: Fig. 6.180: Feature 3 buffer rendering Note: In the final image, Feature 1 and Feature 2 have a slight overlap. This overlap is determined by data order which we have no control over. If you need to control the overlap review the Feature Styles section on managing “z-order”. 6.5. YSLD Styling 583 GeoServer User Manual, Release 2.15.1 Fig. 6.181: Feature style controlling z-order Matching symbolizers and geometries It is common to match the symbolizer with the type of geometries contained in the layer, but this is not required. The following table illustrates what will happen when a geometry symbolizer is matched up with another type of geometry. Point Symbolizer Line Symbolizer Polygon Symbolizer Raster Symbolizer Text Symbolizer Points Points Lines Midpoint of the lines Polygon Centroid of the polygons Outline (stroke) of the polygons Polygons Raster Centroid of the raster n/a Lines n/a Will “close” the line and style as a polygon n/a n/a n/a Transform raster values to color channels for display Label at point location Label at midpoint of lines Label at centroid of polygons Label at centroid of raster outline Outline (stroke) of the raster Will “outline” the raster and style as a polygon Syntax The following is the basic syntax common to all symbolizers. Note that the contents of the block are not all expanded here and that each kind of symbolizer provides additional syntax. geometry: uom: .. x-composite: x-composite-base: where: Property geometry Required?Description No Specifies which attribute to use as the geometry. uom No Unit of measure used for width calculations Default value First geometry attribute found (usually named geom or the_geom) pixel The following properties are equivalent to SLD “vendor options”. 584 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Property x-composite Required?Description No Allows for both alpha compositing and color blending options between symbolizers. x-composite-baseNo Allows the rendering engine to use the symbolizer mapping to define a “base” buffer for subsequent compositing and blending using x-composite. See the section on Feature Styles for more details. Default value N/A false See the following pages for details: Line symbolizer The line symbolizer is used to style linear (1-dimensional) features. It is in some ways the simplest of the symbolizers because it only contains facilities for the stroke (outline) of a feature. Syntax The full syntax of a line symbolizer is: symbolizers: - line: stroke-color: stroke-width: stroke-opacity: stroke-linejoin: stroke-linecap: stroke-dasharray: stroke-dashoffset: stroke-graphic: stroke-graphic-fill: offset: geometry: uom: x-labelObstacle: x-composite-base: x-composite: where: 6.5. YSLD Styling 585 GeoServer User Manual, Release 2.15.1 Property stroke-color Required?Description No Color of line features. stroke-width No stroke-opacity No stroke-linejoin No stroke-linecap No stroke-dasharrayNo stroke-dashoffset No stroke-graphic No stroke-graphic-fill No Property offset 586 Width of line features, measured in pixels. Opacity of line features. Valid values are a decimal value between 0 (completely transparent) and 1 (completely opaque). How line segments are joined together. Options are mitre (sharp corner), round (round corner), and bevel (diagonal corner). How line features are rendered at their ends. Options are butt (sharp square edge), round (rounded edge), and square (slightly elongated square edge). A numeric list signifying length of lines and gaps, creating a dashed effect. Units are pixels, so "2 3" would be a repeating pattern of 2 pixels of drawn line followed by 3 pixels of blank space. If only one number is supplied, this will mean equal amounts of line and gap. Number of pixels into the dasharray to offset the drawing of the dash, used to shift the location of the lines and gaps in a dash. A design or pattern to be used along the stroke. Output will always be a linear repeating pattern, and as such is not tied to the value of stroke-width. Can either be a mark consisting of a common shape or a URL that points to a graphic. The should consist of a mapping containing symbols: followed by an external: or mark:, with appropriate parameters as detailed in the Point symbolizer section. Cannot be used with stroke-graphic-fill. A design or pattern to be used for the fill of the stroke. The area that is to be filled is tied directly to the value of stroke-width. Can either be a mark consisting of a common shape or a URL that points to a graphic. The should consist of a mapping containing symbols: followed by an external: or mark:, with appropriate parameters as detailed in the Point symbolizer section. Cannot be used with stroke-graphic. Required?Description No Value in pixels for moving the drawn line relative to the location of the feature. Default value '#000000' (black) 1 1 mitre butt No dash 0 N/A N/A Default value 0 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Property geometry Required?Description No Specifies which attribute to use as the geometry. uom No Unit of measure used for width calculations Default value First geometry attribute found (usually named geom or the_geom) pixel The following properties are equivalent to SLD “vendor options”. Property Required?Description x-labelObstacle No Marks the symbolizer as an obstacle such that labels drawn via a text symbolizer will not be drawn over top of these features. Options are true or false. Note that the bounding boxes of features are used when calculating obstacles, so unintended effects may occur when marking a line or polygon symbolizer as an obstacle. Default value false Property x-composite Default value N/A Required?Description No Allows for both alpha compositing and color blending options between symbolizers. x-composite-baseNo Allows the rendering engine to use the symbolizer mapping to define a “base” buffer for subsequent compositing and blending using x-composite. See the section on Feature Styles for more details. false Examples Basic line with styled ends The linejoin and linecap properties can be used to style the joins and ends of any stroke. This example draws lines with partially transparent black lines with rounded ends and sharp (mitred) corners: feature-styles: - rules: - symbolizers: - line: stroke-color: '#000000' stroke-width: 8 stroke-opacity: 0.5 stroke-linejoin: mitre stroke-linecap: round Railroad pattern Many maps use a hatched pattern to represent railroads. This can be accomplished by using two line symbolizers, one solid and one 6.5. YSLD Styling 587 GeoServer User Manual, Release 2.15.1 Fig. 6.182: Basic line with styled ends dashed. Specifically, the stroke-dasharray property is used to create a dashed line of length 1 every 24 pixels: name: railroad feature-styles: - name: name rules: - symbolizers: - line: stroke-color: '#000000' stroke-width: 1 - line: stroke-color: '#000000' stroke-width: 12 stroke-dasharray: '1 24' Fig. 6.183: Railroad pattern Specifying sizes in units The units for stroke-width, size, and other similar attributes default to pixels, meaning that graphics remain a constant size at different zoom levels. Alternately, units (feet or meters) can be specified for values, so graphics will scale as you zoom in or out. This 588 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 example draws roads with a fixed width of 8 meters: feature-styles: - rules: - symbolizers: - line: stroke-color: '#000000' stroke-width: '8 m' Fig. 6.184: Line width measured in meters (zoomed out) Fig. 6.185: Line width measured in meters (zoomed in) The default unit of measure for the symbolizer is defined using uom. This example uses a default of meters to supply distances for stroke-width and stroke-dasharray using meters. line: uom: metre stroke-color: '#000000' stroke-width: '8' stroke-dasharray: '20 3' Polygon symbolizer The polygon symbolizer styles polygon (2-dimensional) features. It contains facilities for the stroke (outline) of a feature as well as the fill (inside) of a feature. 6.5. YSLD Styling 589 GeoServer User Manual, Release 2.15.1 Fig. 6.186: Line width and spacing in meters Syntax The full syntax of a polygon symbolizer is: symbolizers: - polygon: fill-color: fill-opacity: fill-graphic: stroke-color: stroke-width: stroke-opacity: stroke-linejoin: stroke-linecap: stroke-dasharray: stroke-dashoffset: stroke-graphic: stroke-graphic-fill: offset: displacement: geometry: uom: x-labelObstacle: x-composite-base: x-composite: where: 590 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Property stroke-color Required?Description No Color of line features. stroke-width No stroke-opacity No stroke-linejoin No stroke-linecap No stroke-dasharrayNo stroke-dashoffset No stroke-graphic No stroke-graphic-fill No 6.5. YSLD Styling Width of line features, measured in pixels. Opacity of line features. Valid values are a decimal value between 0 (completely transparent) and 1 (completely opaque). How line segments are joined together. Options are mitre (sharp corner), round (round corner), and bevel (diagonal corner). How line features are rendered at their ends. Options are butt (sharp square edge), round (rounded edge), and square (slightly elongated square edge). A numeric list signifying length of lines and gaps, creating a dashed effect. Units are pixels, so "2 3" would be a repeating pattern of 2 pixels of drawn line followed by 3 pixels of blank space. If only one number is supplied, this will mean equal amounts of line and gap. Number of pixels into the dasharray to offset the drawing of the dash, used to shift the location of the lines and gaps in a dash. A design or pattern to be used along the stroke. Output will always be a linear repeating pattern, and as such is not tied to the value of stroke-width. Can either be a mark consisting of a common shape or a URL that points to a graphic. The should consist of a mapping containing symbols: followed by an external: or mark:, with appropriate parameters as detailed in the Point symbolizer section. Cannot be used with stroke-graphic-fill. A design or pattern to be used for the fill of the stroke. The area that is to be filled is tied directly to the value of stroke-width. Can either be a mark consisting of a common shape or a URL that points to a graphic. The should consist of a mapping containing symbols: followed by an external: or mark:, with appropriate parameters as detailed in the Point symbolizer section. Cannot be used with stroke-graphic. Default value '#000000' (black) 1 1 mitre butt No dash 0 N/A N/A 591 GeoServer User Manual, Release 2.15.1 Property fill-color Required?Description No Color of inside of features. fill-opacity No fill-graphic No Opacity of the fill. Valid values are a decimal value between 0 (completely transparent) and 1 (completely opaque). A design or pattern to be used for the fill of the feature. Can either be a mark consisting of a common shape or a URL that points to a graphic. The should consist of a mapping containing symbols: followed by an external: or mark:, with appropriate parameters as detailed in the Point symbolizer section. Default value '#808080' (gray) 1 None The use of fill-graphic allows for the following extra options: Property Required?Description x-graphic-marginNo Used to specify margins (in pixels) around the graphic used in the fill. Possible values are a list of four (top, right, bottom, left), a list of three (top, right and left, bottom), a list of two (top and bottom, right and left), or a single value. x-random No Activates random distribution of symbols. Possible values are free or grid. free generates a completely random distribution, and grid will generate a regular grid of positions, and only randomize the position of the symbol around the cell centers, providing a more even distribution. x-random-tile-size No When used with x-random, determines the size of the grid (in pixels) that will contain the randomly distributed symbols. x-random-rotation No When used with x-random, activates random symbol rotation. Possible values are none or free. x-random-symbol-count No When used tih x-random, determines the number of symbols drawn. Increasing this number will generate a more dense distribution of symbols x-random-seed No Determines the “seed” used to generate the random distribution. Changing this value will result in a different symbol distribution. Default value N/A Property offset Default value 0 displacement 592 Required?Description No Value in pixels for moving the drawn line relative to the location of the feature. No Specifies a distance to which to move the symbol relative to the feature. Value is an [x,y] tuple with values expressed in pixels, so [10,5] will displace the symbol 10 pixels to the right, and 5 pixels down. N/A 256 none 16 0 [0,0] Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Property geometry Required?Description No Specifies which attribute to use as the geometry. uom No Unit of measure used for width calculations Default value First geometry attribute found (usually named geom or the_geom) pixel The following properties are equivalent to SLD “vendor options”. Property Required?Description x-labelObstacle No Marks the symbolizer as an obstacle such that labels drawn via a text symbolizer will not be drawn over top of these features. Options are true or false. Note that the bounding boxes of features are used when calculating obstacles, so unintended effects may occur when marking a line or polygon symbolizer as an obstacle. Default value false Property x-composite Default value N/A Required?Description No Allows for both alpha compositing and color blending options between symbolizers. x-composite-baseNo Allows the rendering engine to use the symbolizer mapping to define a “base” buffer for subsequent compositing and blending using x-composite. See the section on Feature Styles for more details. false Examples Basic polygon Polygon symbolizers have both a stroke and a fill, similar to marks for point symbolizers. The following example draws a polygon symbolizer with a red fill and black stroke with beveled line joins for the stroke: feature-styles: - name: name rules: - title: fill-graphic symbolizers: - polygon: fill-color: '#FF0000' fill-opacity: 0.9 stroke-color: '#000000' stroke-width: 8 stroke-opacity: 1 stroke-linejoin: bevel 6.5. YSLD Styling 593 GeoServer User Manual, Release 2.15.1 Fill with graphic The fill-graphic property is used to fill a geometry with a repeating graphic. This can be a mark or an external image. The x-graphic-margin option can be used to specify top, right, bottom, and left margins around the graphic used in the fill. This example uses two sets of repeating squares with different offset values to draw a checkerboard pattern: name: checkers feature-styles: - name: name rules: - title: fill-graphic symbolizers: - polygon: stroke-width: 1 fill-graphic: symbols: - mark: shape: square fill-color: '#000000' size: 8 x-graphic-margin: 16 16 0 0 - polygon: stroke-width: 1 fill-graphic: symbols: - mark: shape: square fill-color: '#000000' size: 8 x-graphic-margin: 0 0 16 16 Randomized graphic fill Normally, the graphic used for the fill-graphic property is tiled. Alternatively, one can scatter this image randomly across the fill area using the x-random option and associated other options. This 594 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.187: Checkered fill could be used to create a speckled pattern, as in the following example: name: speckles feature-styles: - name: name rules: - title: fill-graphic symbolizers: - polygon: stroke-width: 1 fill-graphic: symbols: - mark: shape: circle fill-color: '#000000' size: 3 x-random: grid x-random-seed: 2 x-random-tile-size: 1000 x-random-rotation: free x-random-symbol-count: 1000 Fig. 6.188: Randomized graphic fill 6.5. YSLD Styling 595 GeoServer User Manual, Release 2.15.1 Point symbolizer The point symbolizer is used to style point features or centroids of non-point features. Syntax The full syntax of a point symbolizer is: symbolizers: - point: symbols: - external: url: format: - mark: shape: fill-color: fill-opacity: fill-graphic: stroke-color: stroke-width: stroke-opacity: stroke-linejoin: stroke-linecap: stroke-dasharray: stroke-dashoffset: stroke-graphic: stroke-graphic-fill: size: anchor: displacement: opacity: rotation: geometry: uom: x-labelObstacle: x-composite-base: x-composite: where: 596 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Property stroke-color Required?Description No Color of line features. stroke-width No stroke-opacity No stroke-linejoin No stroke-linecap No stroke-dasharrayNo stroke-dashoffset No stroke-graphic No stroke-graphic-fill No 6.5. YSLD Styling Width of line features, measured in pixels. Opacity of line features. Valid values are a decimal value between 0 (completely transparent) and 1 (completely opaque). How line segments are joined together. Options are mitre (sharp corner), round (round corner), and bevel (diagonal corner). How line features are rendered at their ends. Options are butt (sharp square edge), round (rounded edge), and square (slightly elongated square edge). A numeric list signifying length of lines and gaps, creating a dashed effect. Units are pixels, so "2 3" would be a repeating pattern of 2 pixels of drawn line followed by 3 pixels of blank space. If only one number is supplied, this will mean equal amounts of line and gap. Number of pixels into the dasharray to offset the drawing of the dash, used to shift the location of the lines and gaps in a dash. A design or pattern to be used along the stroke. Output will always be a linear repeating pattern, and as such is not tied to the value of stroke-width. Can either be a mark consisting of a common shape or a URL that points to a graphic. The should consist of a mapping containing symbols: followed by an external: or mark:, with appropriate parameters as detailed in the Point symbolizer section. Cannot be used with stroke-graphic-fill. A design or pattern to be used for the fill of the stroke. The area that is to be filled is tied directly to the value of stroke-width. Can either be a mark consisting of a common shape or a URL that points to a graphic. The should consist of a mapping containing symbols: followed by an external: or mark:, with appropriate parameters as detailed in the Point symbolizer section. Cannot be used with stroke-graphic. Default value '#000000' (black) 1 1 mitre butt No dash 0 N/A N/A 597 GeoServer User Manual, Release 2.15.1 Property fill-color Required?Description No Color of inside of features. fill-opacity No fill-graphic No Opacity of the fill. Valid values are a decimal value between 0 (completely transparent) and 1 (completely opaque). A design or pattern to be used for the fill of the feature. Can either be a mark consisting of a common shape or a URL that points to a graphic. The should consist of a mapping containing symbols: followed by an external: or mark:, with appropriate parameters as detailed in the Point symbolizer section. Default value '#808080' (gray) 1 None The use of fill-graphic allows for the following extra options: Property Required?Description x-graphic-marginNo Used to specify margins (in pixels) around the graphic used in the fill. Possible values are a list of four (top, right, bottom, left), a list of three (top, right and left, bottom), a list of two (top and bottom, right and left), or a single value. x-random No Activates random distribution of symbols. Possible values are free or grid. free generates a completely random distribution, and grid will generate a regular grid of positions, and only randomize the position of the symbol around the cell centers, providing a more even distribution. x-random-tile-size No When used with x-random, determines the size of the grid (in pixels) that will contain the randomly distributed symbols. x-random-rotation No When used with x-random, activates random symbol rotation. Possible values are none or free. x-random-symbol-count No When used tih x-random, determines the number of symbols drawn. Increasing this number will generate a more dense distribution of symbols x-random-seed No Determines the “seed” used to generate the random distribution. Changing this value will result in a different symbol distribution. 598 Default value N/A N/A 256 none 16 0 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Property external url Required?Description No Specifies an image to use to style the point. Yes Location of the image. Can either be an actual URL or a file path (relative to where the style file is saved in the GeoServer data directory). Should be enclosed in single quotes. Yes Format of the image. Must be a valid MIME type (such as image/png for PNG, image/jpeg for JPG, image/svg+xml for SVG) No Specifies a regular shape to use to style the point. No Shape of the mark. Options are square, circle, triangle, cross, x, and star. No Size of the mark in pixels. If the aspect ratio of the mark is not 1:1 (square), will apply to the height of the graphic only, with the width scaled proportionally. No Specify the center of the symbol relative to the feature location. Value is an [x,y] tuple with decimal values from 0-1, with [0,0] meaning that the symbol is anchored to the top left, and [1,1] meaning anchored to bottom right. No Specifies a distance to which to move the symbol relative to the feature. Value is an [x,y] tuple with values expressed in pixels, so [10,5] will displace the symbol 10 pixels to the right and 5 pixels down. No Specifies the level of transparency. Value of 0 means entirely transparent, while 1 means entirely opaque. Only affects graphics referenced by the external parameter; the opacity of mark symbols is controled by the fill-opacity and stroke-opacity of the mark. No Value (in degrees) or rotation of the mark. Larger values increase counter-clockwise rotation. A value of 180 will make the mark upside-down. Default value N/A N/A Property geometry Required?Description No Specifies which attribute to use as the geometry. uom No Default value First geometry attribute found (usually named geom or the_geom) pixel format mark shape size anchor displacement opacity rotation Unit of measure used for width calculations N/A N/A square 16 [0.5,0.5] [0,0] 1 0 The following properties are equivalent to SLD “vendor options”. 6.5. YSLD Styling 599 GeoServer User Manual, Release 2.15.1 Property Required?Description x-labelObstacle No Marks the symbolizer as an obstacle such that labels drawn via a text symbolizer will not be drawn over top of these features. Options are true or false. Note that the bounding boxes of features are used when calculating obstacles, so unintended effects may occur when marking a line or polygon symbolizer as an obstacle. Default value false Property x-composite Default value N/A Required?Description No Allows for both alpha compositing and color blending options between symbolizers. x-composite-baseNo Allows the rendering engine to use the symbolizer mapping to define a “base” buffer for subsequent compositing and blending using x-composite. See the section on Feature Styles for more details. false Examples Basic point A point symbolizer draws a point at the center of any geometry. It is defined by an external image or a symbol, either of which can be sized and rotated. A mark is a pre-defined symbol that can be drawn at the location of a point. Similar to polygons, marks have both a fill and a stroke. This example shows a point symbolizer that draws semi-transparent red diamonds with black outlines: feature-styles: - name: name rules: - title: red point symbolizers: - point: symbols: - mark: shape: square fill-color: '#FF0000' fill-opacity: 0.75 stroke-color: '#000000' stroke-width: 1.5 stroke-opacity: 1 size: 20 rotation: 45 Point as image Sometimes it may be useful to use an image to represent certain points. This can be accomplished using the external symbol property, which requires a url and a format. The url should be enclosed in single quotes. The format property is a MIME type im600 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.189: Basic point age. This example shows a point symbolizer that draws an image centered on each point: name: point feature-styles: - name: name rules: - symbolizers: - point: symbols: - external: url: 'geoserver.png' format: image/png size: 16 Fig. 6.190: Point as image Point composition Using more than one point symbolizer allows the composition of more complex symbology. This example shows two symbolizers along with the x-composite parameter in order to subtract a shape from a square mark, allowing the background to show through. 6.5. YSLD Styling 601 GeoServer User Manual, Release 2.15.1 symbolizers: - point: symbols: - mark: shape: square fill-color: '#222222' size: 40 - point: symbols: - external: url: 'stamp.png' format: image/png x-composite: xor size: 40 Fig. 6.191: Point composition Points as arrow heads Sometimes it is useful to generate a point using a CQL expression. The following example generates a point at the end of each line in the shape of an arrow, rotated such that it matches the orientation of the line. name: arrow symbolizers: - line: stroke-color: '#808080' stroke-width: 3 - point: geometry: ${endPoint(the_geom)} symbols: - mark: shape: shape://oarrow fill-color: '#808080' size: 30 rotation: ${endAngle(the_geom)} Raster symbolizer The raster symbolizer styles raster (coverage) layers. A raster is an array of information with each cell in the array containing one or more values, stored as “bands”. 602 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.192: Point as arrow head The full syntax of a raster symbolizer is: symbolizers: - raster: opacity: channels: gray: red: green: blue: color-map: type: entries: - [color, entry_opacity, band_value, text_label] contrast-enhancement: mode: gamma: where: 6.5. YSLD Styling 603 GeoServer User Manual, Release 2.15.1 Property opacity Required?Description No Opacity of the entire display. Valid values are a decimal between 0 (completely transparent) and 1 (completely opaque). channels No Selects the band(s) to display and the display method. gray No Display a single band as a grayscale image. Cannot be used with red, green, and blue. The can be the band name or a mapping containing name: and contrast-enhancement: (optional). red No Display three bands as an RGB image. Must be used with green, and blue. Cannot be used with gray. The can be the band name or a mapping containing name: and contrast-enhancement: (optional). green No Display three bands as an RGB image. Must be used with red, and blue. Cannot be used with gray. The can be the band name or a mapping containing name: and contrast-enhancement: (optional). blue No Display three bands as an RGB image. Must be used with red, and green. Cannot be used with gray. The can be the band name or a mapping containing name: and contrast-enhancement: (optional). See examples below. color-map No Creates a mapping of colors to grid values. Can only be used with a single band. type No Type of color mapping. Options are ramp, an interpolated list of values; interval, a noninterpolated list of values; and values, where values need to match exactly to be drawn. entries No Values for the color mapping. Syntax is a list of tuples. color Yes Color for the particular color map entry. Value is a standard color value. entry_opacity Yes Opacity of the particular color map entry. Valid values are a decimal between 0 (completely transparent) and 1 (completely opaque). band_value Yes Grid value to use for the particular color map entry. Values are data-dependent. Behavior at or around this value is determined by the color ramp type. text_label No Label for the particular color map entry contrast-enhancement No Modifies the contrast of the display mode No Type of contrast enhancement. Options are normalize (stretches contrast so that the smallest and largest values are set to black and white, respectively) or histogram (produces equal number of content in the image at each brightness level). gamma No Multiplier value for contrast adjustment. A value greater than 1 will increase darkness, while a value less than 1 will decrease darkness. 604 Default value 1 N/A 1 1 2 3 N/A ramp N/A N/A N/A N/A Blank N/A normalize 1 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Examples Enhanced contrast This example takes a given raster and lightens the output by a factor of 2: symbolizers: - raster: contrast-enhancement: gamma: 0.5 Fig. 6.193: Lightened image Normalized output This example takes a given raster and adjusts the contrast so that the smallest values are darkest and the highest values are lightest: symbolizers: - raster: contrast-enhancement: mode: normalize Fig. 6.194: Normalized image Band selection This example takes a raster with multiple bands and outputs band 2 as a grayscale image (This could be used to select a single band in a multi-band image to use with color-map): name: raster feature-styles: - name: name 6.5. YSLD Styling 605 GeoServer User Manual, Release 2.15.1 rules: - symbolizers: - raster: opacity: 1.0 channels: gray: 2 Fig. 6.195: Grayscale band selection Band selection with contrast This example takes an RGB raster, doubles the intensity of the red, and normalizes the green band: name: raster feature-styles: - name: name rules: - symbolizers: - raster: channels: red: name: 1 contrast-enhancement: gamma: .5 green: name: 2 contrast-enhancement: mode: normalize blue: name: 3 Fig. 6.196: Band selection with contrast enhancement 606 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Color ramp This example shows a color ramp from red to green to blue, with raster band values from 0-200: symbolizers: - raster: color-map: type: ramp entries: - ['#FF0000', 1, 0, red] - ['#00FF00', 1, 100, green] - ['#0000FF', 1, 200, blue] In this example, the grid values will have the following colors applied: • Less than or equal to 0 will have an output color of solid red • Between 0 and 100 will have an output color interpolated between red and green • Between 100 and 200 will have an output color interpolated between green and blue • Greater than 200 will have an output color of solid blue Fig. 6.197: Color map with ramp Color intervals The same example as above, but with the color-map type set to intervals: symbolizers: - raster: color-map: type: intervals entries: - ['#FF0000', 1, 0, red] - ['#00FF00', 1, 100, green] - ['#0000FF', 1, 200, blue] In this example, the grid values will have the following colors applied: • Less than or equal to 0 will have an output color of solid red • Between 0 and 100 will have an output color of solid green • Between 100 and 200 will have an output color of solid blue 6.5. YSLD Styling 607 GeoServer User Manual, Release 2.15.1 • Greater than 200 will not be colored at all (transparent) Fig. 6.198: Color map with intervals Color values The same example as above, but with the color-map type set to values: symbolizers: - raster: color-map: type: values entries: - ['#FF0000', 1, 0, red] - ['#00FF00', 1, 100, green] - ['#0000FF', 1, 200, blue] In this example, the grid values will have the following colors applied: • Equal to 0 will have an output color of solid red • Equal to 100 will have an output color of solid green • Equal to 200 will have an output color of solid blue Any other values (even those in between the above values) will not be colored at all. Fig. 6.199: Color map with values Text symbolizer The text symbolizer styles labels of vector features. Labels can consist of text strings and/or graphics. Syntax The full syntax of a text symbolizer is: 608 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 symbolizers: - text: fill-color: fill-opacity: fill-graphic: stroke-graphic: stroke-graphic-fill: label: font-family: font-size: font-style: font-weight: placement: offset: anchor: displacement: rotation: priority: halo: radius: fill-color: fill-opacity: fill-graphic: graphic: symbols: size: opacity: rotation: geometry: uom: x-composite-base: x-composite: x-allowOverruns: x-autoWrap: x-conflictResolution: x-followLine: x-forceLeftToRight: x-goodnessOfFit: x-graphic-margin: x-graphic-resize: x-group: x-labelAllGroup: x-repeat: x-maxAngleDelta: x-maxDisplacement: x-minGroupDistance: x-partials: x-polygonAlign: x-spaceAround: x-underlineText: x-strikethroughText: x-charSpacing: x-wordSpacing: 6.5. YSLD Styling 609 GeoServer User Manual, Release 2.15.1 where: Property fill-color Required?Description No Color of inside of the label. fill-opacity No fill-graphic No stroke-graphic No stroke-graphic-fill No 610 Opacity of fill of the label text. Valid values are a decimal value between 0 (completely transparent) and 1 (completely opaque). A design to be used for the fill of the text label. Can either be a mark consisting of a common shape or a URL that points to a graphic. The should consist of a mapping containing symbols: followed by an external: or mark:, with appropriate parameters as detailed in the Point symbolizer section. A design or pattern to be used along the stroke around the label text. the output will always be a linear repeating pattern, and as such is not tied to the value of stroke-width. Can either be a mark consisting of a common shape or a URL that points to a graphic. The should consist of a mapping containing symbols: followed by an external: or mark:, with appropriate parameters. Cannot be used with stroke-graphic-fill. A design or pattern to be used for the fill of the stroke around the label text. This area that is to be filled is tied directly to the value of stroke-width. Can either be a mark consisting of a common shape or a URL that points to a graphic. The should consist of a mapping containing symbols: followed by an external: or mark:, with appropriate parameters as detailed in the Point symbolizer section. Cannot be used with stroke-graphic. Default value '#808080' (gray) 1 None N/A N/A Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Property label font-family font-size font-style font-weight placement offset anchor displacement rotation priority halo radius fill-color fill-opacity Required?Description Yes Text to display. Often taken from an attribute but any valid expression that constructs a string will do. No Type of font to be used for the label. Options are system dependent; the full list of fonts available can be found via the GeoServer Server Status page. No Size of the font. No Style of the font. Options are normal, italic, and oblique. No Weight of the font. Options are normal and bold. No Determines whether the label is to be drawn derived from a point or a line. No Value (in pixels) for moving the drawn label relative to the location of the feature. A positive value will shift the label in the direction of its top, while a negative value will shift the label in the direction of its bottom. Only valid for when type is set to line. No Specify the center of the symbol relative to the feature location (centroid for lines and polygons). Value is an [x,y] tuple with decimal values from 0-1, with [0,0] meaning that the symbol is anchored to the bottom left of the label, and [1,1] meaning anchored to the top right of the label. No Specifies a distance (in pixels) to which to move the label relative to the feature. Value is an [x,y] tuple with values expressed in pixels, so [10,5] will displace the label 10 pixels to the right and 5 pixels up. Only valid for when type is set to point. No Value (in degrees) or rotation of the label. Larger values increase counter-clockwise rotation. A value of 180 will make the label upside-down. Only valid for when type is set to point. No The priority used when choosing which labels to display during conflict resolution. Higher priority values take precedence over lower priority values. No Creates a shaded area around the label for easier legibility No Size (in pixels) of the halo No Color of the halo No Specifies the level of transparency for the halo. Value of 0 means entirely transparent, while 1 means entirely opaque. Default value N/A serif 10 normal normal point 0 [0,0] [0,0] 0 1000 No halo 1 '#808080' 1 The following properties allow for a graphic to be displayed in addition to just a label. This is used when drawing “shields” (text over top of a graphic) such as in road signs. 6.5. YSLD Styling 611 GeoServer User Manual, Release 2.15.1 Property graphic Required?Description No Specifies whether a graphic is to be drawn for the label. No The details of the graphic. Consists of an external: or mark: section, with appropriate parameters as detailed in the Point symbolizer section. No Size of the graphic in pixels. If the aspect ratio is not 1:1 (square), will apply to the height of the graphic only, with the width scaled proportionally. No Specifies the level of transparency for the graphic. Value of 0 means entirely transparent, while 1 means entirely opaque. No Value (in degrees) or rotation of the graphic. Larger values increase counter-clockwise rotation. A value of 180 will make the graphic upsidedown. Default value N/A (no graphic) Property geometry Required?Description No Specifies which attribute to use as the geometry. uom No Default value First geometry attribute found (usually named geom or the_geom) pixel symbols size opacity rotation Unit of measure used for width calculations N/A 16 1 0 The following properties are equivalent to SLD “vendor options”. 612 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Property Required?Description x-allowOverruns No Allows labels on lines to move slightly beyond the beginning or end of the line. x-autoWrap No The number of pixels beyond which a label will be wrapped over multiple lines. Cannot use with x-followLine. x-conflictResolution No Enables conflict resolution, meaning no two labels will be allowed to overlap. Without conflict resolution, symbolizers can overlap with other labels. x-followLine No On linear geometries, the label will follow the shape of the current line, as opposed to being drawn at a tangent. Will override x-forceLeftToRight No Forces labels to a readable orientation, otherwise will follow the line orientation, possibly making the label look upside-down. This setting is useful when using symbol fonts to add direction markers along a line. x-goodnessOfFit No Percentage (expressed as a decimal between 0-1) of the label that must fit inside the geometry to permit the label to be drawn. Works only on polygon features. x-graphic-marginNo Number of pixels between the stretched graphic and the text. Only applies when x-graphic-resize is set to stretch or proportional. x-graphic-resizeNo Allows for stretching the graphic underneath a label to fit the label size. Options are none, stretch or proportional. Used in conjunction with x-graphic-margin.. x-group No Geometries with identical labels will be considered a single entity to be labeled. Used to control repeated labels. x-labelAllGroup No Used in conjunction with x-group. When true all items in a group are labeled. When false, only the largest geometry in the group is labeled. Valid for lines only. x-repeat No Desired distance (in pixels) between labels drawn on a group. If zero, only one label will be drawn. Used in conjunction with x-group. Valid for lines only. x-maxAngleDelta No Maximum allowed angle (in degrees) between two characters in a curved label. Used in conjunction with x-followLine. Values higher than 30 may cause loss of legibility of the label. x-maxDisplacement No Distance (in pixels) a label can be displaced from its natural position in an attempt to eliminate conflict with other labels. x-minGroupDistance No Minimum distance (in pixels) between two labels in the same label group. Used in conjunction with displacement or repeat to avoid having two labels too close to each other x-partials No Will display partial labels (truncated on the border of the display area). x-polygonAlign No Overrides manual rotation to align label rotation automatically. Valid for polygons only. 6.5. YSLD Styling No x-spaceAround Minimum distance (in pixels) between two labels. A negative value specifies the maximum overlap between two labels. x-underlineText No Instruct the renderer to underline labels. Default value true 0 true false false 0.5 0 none false false 0 22.5 0 No minimum distance false false 0 false 613 GeoServer User Manual, Release 2.15.1 Property x-composite Required?Description No Allows for both alpha compositing and color blending options between symbolizers. x-composite-baseNo Allows the rendering engine to use the symbolizer mapping to define a “base” buffer for subsequent compositing and blending using x-composite. See the section on Feature Styles for more details. Default value N/A false Examples Basic label Text symbolizers are used to draw labels on objects. The label text is usually linked to some attribute of the layer. Font options are available in the font-family, font-size, font-style, and font-weight properties. The following example draws a label using the name attribute of the layer, and with a SansSerif font of size 12, gray color, bold and italic: feature-styles: - name: name rules: - title: fill-graphic symbolizers: - text: label: ${name} fill-color: '#555555' font-family: SansSerif font-size: 12 font-style: italic font-weight: bold Fig. 6.200: Basic label Label with wrap Wrapping long labels can improve how well they fit on maps. This can be accomplished using the x-autoWrap property. This exam614 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 ple wraps lines longer than 70 pixels: feature-styles: - name: name rules: - symbolizers: - polygon: stroke-width: 1 fill-color: '#00DD77' - text: label: ${name} font-size: 12 x-autoWrap: 70 x-maxDisplacement: 100 anchor: [0.5,-1] Fig. 6.201: Label with wrap Label with halo Surrounding labels with a halo will allow them to be visible even on complex maps with various background features. This can be accomplished using the halo family of properties. This example surrounds the label in a partially transparent white halo of radius 2: feature-styles: - name: name rules: - symbolizers: - polygon: stroke-width: 1 fill-color: '#00DD77' - text: label: ${name} font-size: 12 x-autoWrap: 70 x-maxDisplacement: 100 halo: radius: 2 fill-color: '#FFFFFF' fill-opacity: 0.8 anchor: [0.5,-1] Grouped labels Grouping and other properties can be used to better control where labels are placed. The x-group option combines all labels with 6.5. YSLD Styling 615 GeoServer User Manual, Release 2.15.1 Fig. 6.202: Label with halo identical text into a single label. This can be useful to show only a single label for a street rather than having a label on every block of the street. The x-goodnesOfFit option determines whether or not to draw labels based on how well they fit into the available space. The x-maxDisplacement option determines the maximum distance a label can be moved to avoid overlaps. The following example uses x-group to ensure only one label is drawn for each feature, and sets x-goodnesOfFit to zero so that labels will be drawn even if they have a poor fit: feature-styles: - name: name rules: - title: fill-graphic symbolizers: - text: label: ${name} fill-color: '#555555' font-family: SansSerif font-size: 12 font-style: italic font-weight: bold x-group: true x-goodnessOfFit: 0.0 x-maxDisplacement: 400 Fig. 6.203: Grouped labels 616 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Labels following lines In order to have a label follow a line (and not be drawn tangent to a line), the x-followLine option can be set. Other properties can be used in conjunction with this to achieve the best visual result. The following example has street names following the line of the street, with a maximum angle of 90 degrees, repeating every 150 pixels: feature-styles: - rules: - symbolizers: - line: stroke-color: '#EDEDFF' stroke-width: 10 - text: label: name x-followLine: true x-maxAngleDelta: 90 x-maxDisplacement: 400 x-repeat: 150 Fig. 6.204: Labels following lines Labels avoiding obstacles The x-labelObstacle option is used to mark a different symbolizer as an obstacle that labels should avoid. This example draws labels and points on a line geometry, and also uses a point symbolizer to draw the vertices of the lines as points. It is those points which are set to be treated as obstacles to be avoided: feature-styles: - rules: - symbolizers: - line: stroke-color: '#00BBDD' stroke-width: 10 - rules: 6.5. YSLD Styling 617 GeoServer User Manual, Release 2.15.1 - symbolizers: - point: geometry: ${vertices(the_geom)} x-labelObstacle: true symbols: - mark: shape: circle stroke-color: '#000000' fill-color: '#007777' - text: label: ${streetname} x-maxDisplacement: 400 x-followLine: true Fig. 6.205: Labels avoiding obstacles Road Shields The graphic option is used to display a symbol behind a label. A common use for this is to display “highway shields” behind road numbers. This example uses a circle shape to draw state shields, and an external image to draw interstate shields, then draws road names on top. The x-graphic-resize and x-graphic-margin options are used to resize the graphics to fit the label text: feature-styles: - name: state rules: - filter: ${level ilike 'State'} symbolizers: - line: stroke-color: '#AAEE00' stroke-width: 4 stroke-linecap: round - text: label: ${name} anchor: [0.5, 0.5] fill-color: black font-family: SansSerif font-weight: bold font-size: 8 x-graphic-resize: stretch 618 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 x-graphic-margin: 6 graphic: symbols: - mark: shape: circle fill-color: white stroke-color: black - name: interstate rules: - filter: ${level ilike 'Interstate'} symbolizers: - line: stroke-color: '#99CC00' stroke-width: 6 stroke-linecap: round - text: label: ${name} anchor: [0.5, 0.5] fill-color: white font-family: SansSerif font-weight: bold font-size: 8 x-graphic-resize: stretch x-graphic-margin: 6 graphic: symbols: - external: url: interstate.png format: image/png Fig. 6.206: Road Shields Scale and zoom It is common for different rules to be applied at different zoom levels on a web map. For example, on a roads layer, you would not not want to display every single road when viewing the whole world. Or perhaps you may wish to styles the same features differently depending on the zoom level. For example: a cities layer styled using points at low zoom levels (when “zoomed out”) and with polygon borders at higher zoom levels (“zoomed in”). YSLD allows rules to be applied depending on the the scale or zoom level. You can specify by scale, or you can define zoom levels in terms of scales and specify by zoom level. 6.5. YSLD Styling 619 GeoServer User Manual, Release 2.15.1 Warning: Be aware that scales for a layer (where a style is applied) may interact differently when the layer is contained in a map, if the map has a different coordinate reference system from the layer. Scale syntax The syntax for using a scale conditional parameter in a rule is: rules: - ... scale: [,] ... where: Attribute min max Required?Description Yes The minimum scale (inclusive) for which the rule will be applied. Value is a number, either decimal or integer. Yes The maximum scale (exclusive) for which the rule will be applied. Value is a number, either decimal or integer. Default value N/A N/A Note: It is not possible to use an expression for any of these values. Use the literal strings min and max to denote where there are no lower or upper scale boundaries. For example, to denote that the scale is anything less than some value: scale: [min,] To denote that the scale is anything greater than or equal to some value: scale: [,max] Note: In the above examples, min and max are always literals, entered exactly like that, while and would be replaced by actual scalar values. If the scale parameter is omitted entirely, then the rule will apply at all scales. Scale examples Three rules, all applicable at different scales: rule: - name: large_scale scale: [min,100000] 620 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 symbolizers: - line: stroke-width: 3 stroke-color: '#0165CD' - name: medium_scale scale: [100000,200000] symbolizers: - line: stroke-width: 2 stroke-color: '#0165CD' - name: small_scale scale: [200000,max] symbolizers: - line: stroke-width: 1 stroke-color: '#0165CD' This example will display lines with: • A stroke width of 3 at scales less than 100,000 (large_scale) • A stroke width of 2 at scales between 100,000 and 200,000 (medium_scale) • A stroke width of 1 at scales greater than 200,000 (small_scale) Given the rules above, the following arbitrary sample scales would map to the rules as follows: Scale 50000 100000 150000 200000 300000 Rule large_scale medium_scale medium_scale small_scale small_scale Note the edge cases, since the min value is inclusive and the max value is exclusive. Scientific notation for scales To make comprehension easier and to lessen the chance of errors, scale values can be expressed in scientific notation. So a scale of 500000000, which is equal to 5 × 10^8 (a 5 with eight zeros), can be replaced by 5e8. Relationship between scale and zoom When working with web maps, often it is more convenient to talk about zoom levels instead of scales. The relationship between zoom and scale is context dependent. For example, for EPSG:4326 with world boundaries, zoom level 0 (completely zoomed out) corresponds to a scale of approximately 6.5. YSLD Styling 621 GeoServer User Manual, Release 2.15.1 279,541,000 with each subsequent zoom level having half the scale value. For EPSG:3857 (Web Mercator) with world boundaries, zoom level 0 corresponds to a scale of approximately 559,082,000, again with each subsequent zoom level having half the scale value. But since zoom levels are discrete (0, 1, 2, etc.) and scale levels are continuous, it’s actually a range of scale levels that corresponds to a given zoom level. For example, if you have a situation where a zoom level 0 corresponds to a scale of 1,000,000 (and each subsequent zoom level is half that scale, as is common), you can set the scale values of your rules to be: • scale: [750000,1500000] (includes 1,000,000) • scale: [340000,750000] (includes 500,000) • scale: [160000,340000] (includes 250,000) • scale: [80000,160000] (includes 125,000) • etc. Also be aware of the inverse relationship between scale and zoom; as the zoom level increases, the scale decreases. Zoom syntax In certain limited cases, it can be more useful to specify scales by way of zoom levels for predefined gridsets. These can be any predefined gridsets in GeoServer. Inside a rule, the syntax for using zoom levels is: rules: - ... zoom: [, ] ... where: Attribute min max Required?Description Yes The minimum zoom level for which the rule will be applied. Value is an integer. Yes The maximum zoom level for which the rule will be applied. Value is an integer. Default value N/A N/A Note: It is not possible to use an expression for any of these values. As with scales, use the literal strings min and max to denote where there are no lower or upper scale boundaries. For example, to denote that the zoom level is anything less than some value: zoom: [min,] 622 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 To denote that the zoom level is anything greater than or equal to some value: zoom: [,max] Note: In the above examples, min and max are always literals, entered exactly like that, while and would be replaced by actual scalar values. The scale and zoom parameters should not be used together in a rule (but if used, scale takes priority over zoom). Specifying a grid While every web map can have zoom levels, the specific relationship between a zoom level and its scale is dependent on the gridset (spatial reference system, extent, etc.) used. So when specifying zoom levels in YSLD, you should also specify the grid. The grid parameter should remain at the top of the YSLD content, above any Feature Styles or Rules. The syntax is: grid: name: where: Property name Required?Description No WGS84, WebMercator, or a name of a predefined gridset in GeoServer. Default value WebMercator Note: As many web maps use “web mercator” (also known as EPSG:3857 or EPSG:900913), this is assumed to be the default if no grid is specified. Warning: As multiple gridsets can contain the same SRS, we recommend naming custom gridsets by something other than the EPSG code. Zoom examples Default gridset Given the default of web mercator (also known as EPSG:3857 or EPSG:900913), which requires no grid designation, this defines zoom levels as the following scale levels (rounded to the nearest whole number below): 6.5. YSLD Styling 623 GeoServer User Manual, Release 2.15.1 Scale 559082264 279541132 139770566 69885283 34942641 17471321 8735660 4367830 2183915 / 2 Zoom level 0 1 2 3 4 5 6 7 8 + 1 Named gridsets For the existing gridset of WGS84 (often known as EPSG:4326): grid: name: WGS84 This defines zoom levels as the following scale levels (rounded to the nearest whole number below): Scale 559082264 279541132 139770566 69885283 34942641 17471321 8735660 4367830 2183915 / 2 Zoom level 0 1 2 3 4 5 6 7 8 + 1 Given a custom named gridset called NYLongIslandFtUS, defined by a CRS of EPSG:2263 and using its full extent: grid: name: NYLongIslandFtUS This defines zoom levels as the following (rounded to the nearest whole number below): 624 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Scale 4381894 2190947 1095473 547736 273868 136934 68467 34234 17117 / 2 Zoom level 0 1 2 3 4 5 6 7 8 + 1 Note: These scale values can be verified in GeoServer on the Gridsets page under the definition for the gridset: Fig. 6.207: Gridset defined in GeoServer Specifically, note the Scale values under Tile Matrix Set. 6.5. YSLD Styling 625 GeoServer User Manual, Release 2.15.1 Filters Filters are predicates that allow rules to be applied selectively. A filter can take a great many different forms. Note: A scale is a type of filter, but is discussed separately. Note: For more information, please see the GeoTools CQL documentation and GeoServer CQL tutorial. Syntax The basic syntax of a filter is: rules: ... filter: ${} ... where is any valid CQL/ECQL filter. Note: Be aware that filters are applied to rules and so appear inside them, but outside of any symbolizers. Types of filters As mentioned above, the filter can be any valid construction made with CQL/ECQL (Extended/Contextual Query Language). CQL is written using a familiar text-based syntax with strong similarities to SQL statements. One can think of a CQL expression as the “WHERE” clause of a SQL statement. The following are all standard filter constructions: Object comparison This filter will test to see if a comparison to an attribute is true. It has the following form: ${ } where: 626 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Attribute Required?Description Yes That to which something is going to be compared. Typically an attribute name. May be case sensitive. Yes Method of comparison. Valid operators are =, <, >, <=, >=, <>, LIKE, ILIKE, BETWEEN, IS NULL, IN. NOT can be added to invert the comparison. Yes That which the is being compared to. Typically a static value such as a string or scalar, though can be an expression that evaluates to a static value. Can include mathematical operators such as +, -, *, /. Use single quotes for strings, as double-quotes will be interpreted as an attribute name. Omit quotes for scalar values. Default value N/A N/A N/A The following is a description of all available operators: Operator = < > <= >= LIKE ILIKE BETWEEN IS NULL IN NOT <> Description Equals Less than (non-inclusive) Greater than (non-inclusive) Less than or equal to (inclusive) Greater than or equal to (inclusive) Fuzzy matching for strings and other non-numeric attributes. Add % for multicharacter wildcards, and _ for single-character wildcards. Case-insensitive version of LIKE Tests if a value that is between two given values For testing against a NULL value Used when specifying a list. Must be contained in the list for the statement to be true. Negates a boolean (true/false) condition. Can be used with an additional operator such as NOT LIKE or NOT BETWEEN. Not equal (used when comparing a string or numeric value only) Note: These operators are not case sensitive, but are shown here in all caps for legibility and consistency. Spatial filters Filters can be spatial in nature. Any valid spatial construction in WKT (Well Known Text) can be used. Spatial filters include INTERSECTS, DISJOINT, CONTAINS, WITHIN, TOUCHES, CROSSES, EQUALS, DWITHIN, and BBOX. NOT can be added to negate the condition. For more details about these spatial filters and their syntax, please see the GeoServer ECQL reference or uDig CQL reference. 6.5. YSLD Styling 627 GeoServer User Manual, Release 2.15.1 Compound statements The filter can be a combination of statements. A common case is testing if the value of an attribute is greater than one value but less than another. The syntax for creating compound statements is to use standard Boolean notation such as AND, OR, and NOT along with relevant parentheses. For example, a filter where both statements need to be true would be: filter: ${ AND } A filter where either statement would need to be true would be: filter: ${ OR } Larger filters can be built up in this way: filter: ${( OR ,→) AND OR NOT } In these examples, every is a valid filter. In terms of precedence, AND is evaluated first, followed by OR, unless modified by parentheses. So, in the last example above, ( OR ) will be evaluated first, followed by the result of that AND , and finally the result of that with OR NOT . Examples Filter size based on an attribute Filters are used to style different features of a layer based on certain conditions. The ILIKE operator is used to compare two strings (ignoring case) to see if they are similar. When using LIKE or ILIKE, the % character matches any number of letters (So %hwy matches any streetname ending in hwy). This example uses filters to distinguish between Highways, Roads, and other streets, and draw them using different colors and sizes: feature-styles: - rules: - filter: ${streetname ILIKE '%hwy'} symbolizers: - line: stroke-color: '#007799' stroke-width: 8 - filter: ${streetname ILIKE '%rd'} symbolizers: - line: stroke-color: '#00AA00' stroke-width: 4 - else: true 628 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 symbolizers: - line: stroke-color: black stroke-width: 2 Fig. 6.208: Filter based on road types Filter color based on attribute value Filters can also be used to color a map based on attributes of the data. The following example uses the YEARBLT attribute to color different lots based on the year they were built. The else rule applies only if no other filter rule applies Note: The Recode function can perform the same functionality in a more compact syntax. name: Year Built Filter feature-styles: - rules: - filter: ${YEARBLT > 2000} symbolizers: - polygon: stroke-color: '#000000' stroke-width: 0.5 fill-color: '#00FF00' - filter: ${YEARBLT > 1990 AND YEARBLT < 2000} symbolizers: - polygon: stroke-color: '#000000' stroke-width: 0.5 fill-color: '#22DD00' - filter: ${YEARBLT > 1980 AND YEARBLT < 1990} symbolizers: - polygon: stroke-color: '#000000' stroke-width: 0.5 fill-color: '#44BB00' - filter: ${YEARBLT > 1970 AND YEARBLT < 1980} symbolizers: - polygon: 6.5. YSLD Styling 629 GeoServer User Manual, Release 2.15.1 stroke-color: '#000000' stroke-width: 0.5 fill-color: '#668800' - else: true symbolizers: - polygon: stroke-color: '#000000' stroke-width: 0.5 fill-color: '#DD4400' Fig. 6.209: Filter based on attribute value Filter by bounding box Spatial filters can be used to filter a layer based on its geometry. The bbox filter can be used to select features that are contained within a bounding box. This example colors polygons orange within the bounding box, and blue outside the bounding box: name: Spatial Filter feature-styles: - name: name rules: ,→filter: bbox(the_geom, -122.9, 42.36, -122.85, 42.28) symbolizers: - polygon: fill-color: '#99CC00' - else: true symbolizers: - polygon: fill-color: '#0099CC' Filter by arbitrary geometries Spatial filters can also be used to compare layer geometries against arbitrary geometries, not just bounding boxes. In this example, the within filter is used to select all buildings inside a triangular region defined using Well-Known Text (WKT) and color them green. All other features are colored blue: 630 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.210: Detail of bbox filter feature-styles: - name: name rules: - filter: ,→within(the_geom, POLYGON ((-122.9075 42.3625, -122. ,→8225 42.3625, -122.8268 42.2803, -122.9075 42.3625))) symbolizers: - polygon: fill-color: '#00CC00' - else: true symbolizers: - polygon: fill-color: '#0099CC' Fig. 6.211: Filter using within Functions Functions are additional operations that can be employed when calculating values for YSLD parameters. In most cases, a value for a parameter can be the output (result) of a function. 6.5. YSLD Styling 631 GeoServer User Manual, Release 2.15.1 Functions can be used in most places in a style document. Syntax Functions aren’t a parameter to itself, but instead are used as a part of the values of a parameter, or indeed in any expression. So the syntax is very general, for example: : ${} Functions are evaluated at rendering time, so the output is passed as the parameter value and then rendered accordingly. List of functions A reference list of functions can be found in the GeoServer User Manual and is also available in raw form in the GeoTools User Manual. The functions can be broken up loosely into categories such as geometric, math, and string functions. Theming functions There are three important functions that are often easier to use for theming than using rules, and can vastly simplify your style documents: Recode, Categorize, and Interpolate. Recode: Attribute values are directly mapped to styling properties: recode(attribute, ,→value1,result1,value2,result2,value3,result3,...) This is equivalent to creating multiple rules with similar filters: rules: - ... filter: ${attribute = value1} - ... : result1 - ... filter: ${attribute = value2} - ... : result2 - ... filter: ${attribute = value3} - ... : result3 Categorize: Categories are defined using minimum and maximum ranges, and attribute values are sorted into the appropriate category: 632 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 categorize(attribute,category0, ,→value1,category1,value2,category2,...,belongsTo) This would create a situation where the attribute value, if less than value1 will be given the result of category0; if between value1 and value2, will be given the result of category1; if between value2 and value3, will be given the result of category2, etc. Values must be in ascending order. The belongsTo argument is optional, and can be either succeeding or preceding. It defines which interval to use when the lookup value equals the attribute value. If the attribute value is equal to value1 and suceeding is used, then the result will be category1. If preceding is used then the result will be category0. The default is succeeding. This is equivalent to creating the following multiple rules: rules: - ... filter: ${attribute < value1} - ... : category0 - ... filter: ${attribute >= value1 AND attribute < value2} - ... : category1 - ... filter: ${attribute >= value2} - ... : category2 Interpolate: Used to smoothly theme quantitative data by calculating a styling property based on an attribute value. This is similar to Categorize, except that the values are continuous and not discrete: interpolate(attribute, ,→value1,entry1,value2,entry2,...,mode,method) This would create a situation where the attribute value, if equal to value1 will be given the result of entry1; if halfway between value1 and value2 will be given a result of halfway in between entry1 and entry2; if three-quarters between value1 and value2 will be given a result of three-quarters in between entry1 and entry2, etc. The mode argument is optional, and can be either linear, cosine, or cubic. It defines the interpolation algorithm to use, and defaults to linear. The method argument is optional, and can be either numeric or color. It determines whether entry1, entry2, . . . are numbers or colors, and defaults to numeric. There is no equivalent to this function in vector styling. The closest to this in raster styling is the color ramp. The three theming functions can be neatly summarized by this table: 6.5. YSLD Styling 633 GeoServer User Manual, Release 2.15.1 Function Recode Categorize Interpolate Type of input Discrete Continuous Continuous Type of output Discrete Discrete Continuous Examples Display rotated arrows at line endpoints The startPoint(geom) and endPoint(geom) functions take a geometry as an argument and returns the start and end points of the geometry respectively. The startAngle(geom) and endAngle(geom) functions take a geometry as an argument and return the angle of the line terminating at the start and end points of the geometry respectively. These functions can be used to display an arrow at the end of a line geometry, and rotate it to match the direction of the line: feature-styles: - rules: - symbolizers: - line: stroke-width: 1 - point: geometry: ${endPoint(geom)} rotation: ${endAngle(geom)} size: 24 symbols: - mark: shape: 'shape://carrow' fill-color: '#000000' Fig. 6.212: Endpoint arrows Drop shadow The offset(geom, x, y) function takes a geometry and two values, and displaces the geometry by those values in the x and y directions. This can be used to create a drop-shadow effect: feature-styles: - name: shadow rules: - symbolizers: 634 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 - polygon: stroke-width: 0.0 fill-color: '#000000' fill-opacity: 0.75 geometry: ${offset(geom, 0.0001, -0.0001)} - name: fill rules: - symbolizers: - polygon: stroke-width: 0.0 fill-color: '#00FFFF' Fig. 6.213: Drop shadow Different-colored outline The buffer(geom, buffer) function takes a geometry and a value as arguments, and returns a polygon geometry with a boundary equal to the original geometry plus the value. This can be used to generate an extended outline filled with a different color, for example to style a shoreline: feature-styles: - name: shoreline rules: - polygon: fill-color: '#00BBFF' geometry: ${buffer(geom, 0.00025)} - name: land rules: - polygon: fill-color: '#00DD00' See also: • convexHull(geom) • octagonalEnvelope(geom) • mincircle(geom) • minrectangle(geom) 6.5. YSLD Styling 635 GeoServer User Manual, Release 2.15.1 Fig. 6.214: Buffered outline • minimumdiameter(geom) Display vertices of a line The vertices(geom) function takes a geometry and returns a collection of points representing the vertices of the geometry. This can be used to convert a polygon or line geometry into a point geometry: point: geometry: vertices(geom) Fig. 6.215: Endpoint arrows See also: • boundary(geom) • centroid(geom) Angle between two points The and two ues 636 atan2(x, y) function calculates the arctangent of (y/x) so is able to determine the angle (in radians) between points. This function uses the signs of the x and y valto determine the computed angle, so it is preferable over Chapter 6. Styling GeoServer User Manual, Release 2.15.1 atan(). The getX(point_geom) and getY(point_geom) extracts the x and y ordinates from a geometry respectively, while toDegrees(value) converts from radians to degrees: point: symbols: - mark: shape: triangle rotation: ${toDegrees(atan2( getX(startPoint(the_geom))-getX(endPoint(the_geom)), getY(startPoint(the_ ,→geom))-getY(endPoint(the_geom))))} ,→ See also: • sin(value) • cos(value) • tan(value) • asin(value) • acos(value) • atan(value) • toRadians(value) • pi() Scale objects based on a large range of values The log(value) function returns the natural logarithm of the provided value. Use log(value)/log(base) to specify a different base. For example, specifying log(population)/log(2) will make the output increase by 1 when the value of population doubles. This allows one to display relative sizes on a consistent scale while still being able to represent very small and very large populations: point: symbols: - mark: shape: circle size: ${log(population)/log(2)} See also: • exp(val) • pow(base,exponent) • sqrt(val) 6.5. YSLD Styling 637 GeoServer User Manual, Release 2.15.1 Combine several strings into one The Concatenate(string1, string2, ...) function takes any number of strings and combines them to form a single string. This can be used to display more than one attribute within a single label: text: label: ${Concatenate(name, ', ', population)} Capitalize words The strCapitalize(string) function takes a single string and capitalizes the first letter of each word in the string. This could be used to capitalize labels created from lower case text: text: label: ${strCapitalize(name)} See also: • strToLowerCase(string) • strToUpperCase(string) Color based on discrete values In certain cases, theming functions can be used in place of filters to produce similar output much more simply. For example, the Recode function can take an attribute and output a different value based on an attribute value. So instead of various filters, the entire constructions can be done in a single line. For example, this could be used to color different types of buildings: feature-styles: - name: name rules: - symbolizers: - polygon: fill-color: ${recode(zone, 'I-L', '#FF7700', 'I-H', '#BB6600', 'C-H', '#0077BB', 'C-R', '#00BBDD', 'C-C', '#00DDFF', '', '#777777')} In the above example, the attribute is zone , and then each subsequent pair consists of an attribute value followed by a color. 638 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.216: Recode Function Color based on categories The Categorize function returns a different value depending on which range (category) an attribute value matches. This can also make a style much more simple by reducing the number of filters. This example uses categorize to color based on certain values of the YEARBLT attribute: feature-styles: - name: name rules: - symbolizers: - polygon: stroke-color: '#000000' stroke-width: 0.5 fill-color: ${categorize(YEARBLT, '#DD4400', 1950,'#AA4400', 1960,'#886600', 1970,'#668800', 1980,'#44BB00', 1990,'#22DD00', 2000,'#00FF00')} Fig. 6.217: Categorize Function 6.5. YSLD Styling 639 GeoServer User Manual, Release 2.15.1 Choropleth map The interpolate function can be used to create a continuous set of values by interpolating between attribute values. This can be used to create a choropleth map which shows different colors for regions based on some continuous attribute such as area or population: feature-styles: - name: name rules: - title: fill-graphic symbolizers: - polygon: stroke-width: 1 fill-color: ${interpolate(PERSONS, ,→ 0.0, '#00FF00', 1e7,'#FF0000', 'color')} Fig. 6.218: Choropleth Map Variables Variables in YSLD that allow for a certain directive or block of directives to be defined by name and later reused. This can greatly simplify the styling document. The two most-common use cases for using variables are: • To create a more-friendly name for a value (such as using myorange instead of #EE8000) • To define a block of directives to remove redundant content and to decrease file length It is customary, but not required, to place all definitions at the very top of the YSLD file, above all header information, feature styles, or rules. Syntax Single value The syntax for defining a variable as a single value is: define: &variable where: 640 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Attribute define &variable Required?Description Yes Starts the definition block. Yes The name of the variable being defined. The & is not part of the variable name. Yes A single value, such as 512 or '#DD0000' Default value N/A N/A N/A The syntax for using this variable is to prepend the variable name with a *: : *variable This variable can be used in any place where its type is expected. Directive block The syntax for defining a variable as a content block is: define: &varblock : : ... : - : : ... Any number of directives or blocks of directives can be inside the definition block. Moreover, any type of directive that is valid YSLD can be included in the definition, so long as the content block could be substituted for the variable without modification. Note: It is also possible to have nested definitions. The syntax for using this variable is to prepend the variable name with <<: *. For example: : - : <<: *varblock The line that contains the variable will be replaced with the contents of the definition. Examples The following are all examples of variable substitution Name a color: define: &myorange '#EE8000' 6.5. YSLD Styling 641 GeoServer User Manual, Release 2.15.1 stroke: *myorange Reusable text string: define: &rulename "This is my rule" title: *rulename Stroke style: define: &strokestyle stroke: '#FF0000' stroke-width: 2 stroke-opacity: 0.5 polygon: <<: *strokestyle Transforms YSLD allows for the use of rendering transformations. Rendering transformations are processes on the server that are executed inside the rendering pipeline, to allow for dynamic data transformations. In GeoServer, rendering transformations are typically exposed as WPS processes. For example, one could create a style that applies to a point layer, and applies a Heatmap process as a rendering transformation, making the output a (raster) heatmap. Because rendering transformations can change the geometry type, it is important to make sure that the symbolizer used matches the output of the rendering transformation, not the input. In the above heatmap example, the appropriate symbolizer would be a raster symbolizer, as the output of a heatmap is a raster. Syntax The full syntax for using a rendering transformation is: feature-styles ... transform: name: params: rules: ... where: 642 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Property name params Required?Description Yes Full name of the rendering transform including any prefixes (such as vec:Heatmap) Yes All input parameters for the rendering transformation. Content will vary greatly based on the amount and type of parameters needed. Default value N/A N/A The values in the params options typically include values, strings, or attributes. However, it can be useful with a transformation to include environment parameters that concern the position and size of the map when it is rendered. For example, the following are common reserved environment parameters: Environment Description parameter env('wms_bbox') The bounding box of the request env('wms_width')The width of the request env('wms_height') The height of the request With this in mind, the following params are assumed unless otherwise specified: params: ... outputBBOX: ${env('wms_bbox')} outputWidth: ${env('wms_width')} outputHeight: ${env('wms_height')} ... Note: Be aware that the transform happens outside of the rules and symbolizers, but inside the feature styles. Examples Heatmap The following uses the vec:Heatmap process to convert a point layer to a heatmap raster: title: Heatmap feature-styles: - transform: name: vec:Heatmap params: weightAttr: pop2000 radiusPixels: 100 pixelsPerCell: 10 rules: - symbolizers: - raster: opacity: 0.6 color-map: 6.5. YSLD Styling 643 GeoServer User Manual, Release 2.15.1 type: ramp entries: - ['#FFFFFF',0,0.0,nodata] - ['#4444FF',1,0.1,nodata] - ['#FF0000',1,0.5,values] - ['#FFFF00',1,1.0,values] Point Stacker The point stacker transform can be used to combine points that are close together. This transform acts on a point geometry layer, and combines any points that are within a single cell as specified by the cellSize parameter. The resulting geometry has attributes geom (the geometry), count (the number of features represented by this point) and countUnique (the number of unique features represented by this point). These attributes can be used to size and label the points based on how many points are combined together: title: pointstacker feature-styles: - transform: name: vec:PointStacker params: cellSize: 100 rules: - symbolizers: - point: size: ${8*sqrt(count)} symbols: - mark: shape: circle fill-color: '#EE0000' - filter: count > 1 symbolizers: - text: fill-color: '#FFFFFF' font-family: Arial font-size: 10 font-weight: bold label: ${count} placement: anchor: [0.5,0.75] 6.5.4 YSLD Cookbook The YSLD Cookbook is a collection of YSLD “recipes” for creating various types of map styles. Wherever possible, each example is designed to show off a single YSLD feature so that code can be copied from the examples and adapted when creating YSLDs of your own. While not an exhaustive reference like the YSLD reference the YSLD cookbook is designed to be a practical reference, showing common style templates that are easy to understand. 644 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.219: Point stacker The YSLD Cookbook is divided into four sections: the first three for each of the vector types (points, lines, and polygons) and the fourth section for rasters. Each example in every section contains a screenshot showing actual GeoServer WMS output, a snippet of the YSLD code for reference, and a link to download the full YSLD. Each section uses data created especially for the YSLD Cookbook, with shapefiles for vector data and GeoTIFFs for raster data. The projection for data is EPSG:4326. Data Type Point Line Polygon Raster Shapefile ysld_cookbook_point.zip ysld_cookbook_line.zip ysld_cookbook_polygon.zip ysld_cookbook_raster.zip Points While points are seemingly the simplest type of shape, possessing only position and no other dimensions, there are many different ways that a point can be styled in YSLD. Example points layer The points layer used for the examples below contains name and population information for the major cities of a fictional country. For reference, the attribute table for the points in this layer is included below. 6.5. YSLD Styling 645 GeoServer User Manual, Release 2.15.1 fid (Feature ID) point.1 point.2 point.3 point.4 point.5 point.6 point.7 name (City name) Borfin Supox City Ruckis Thisland Synopolis San Glissando Detrania pop (Population) 157860 578231 98159 34879 24567 76024 205609 Download the points shapefile Simple point This example specifies points be styled as red circles with a diameter of 6 pixels. Fig. 6.220: Simple point Code Download the "Simple point" YSLD title: 'YSLD Cook Book: Simple Point' feature-styles: - name: name rules: - symbolizers: - point: size: 6 symbols: - mark: shape: circle fill-color: '#FF0000' 1 2 3 4 5 6 7 8 9 10 11 646 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Details There is one rule in one feature style for this YSLD, which is the simplest possible situation. (All subsequent examples will contain one rule and one feature style unless otherwise specified.) Styling points is accomplished via the point symbolizer (lines 6-11). Line 10 specifies the shape of the symbol to be a circle, with line 11 determining the fill color to be red ('#FF0000'). Line 7 sets the size (diameter) of the graphic to be 6 pixels. Simple point with stroke This example adds a stroke (or border) around the Simple point, with the stroke colored black and given a thickness of 2 pixels. Fig. 6.221: Simple point with stroke Code Download the "Simple point with stroke" YSLD title: 'YSLD Cook Book: Simple point with stroke' feature-styles: - name: name rules: - symbolizers: - point: size: 6 symbols: - mark: shape: circle stroke-color: '#000000' stroke-width: 2 fill-color: '#FF0000' 1 2 3 4 5 6 7 8 9 10 11 12 13 6.5. YSLD Styling 647 GeoServer User Manual, Release 2.15.1 Details This example is similar to the Simple point example. Lines 1112 specify the stroke, with line 11 setting the color to black ('#000000') and line 12 setting the width to 2 pixels. Rotated square This example creates a square instead of a circle, colors it green, sizes it to 12 pixels, and rotates it by 45 degrees. Fig. 6.222: Rotated square Code Download the "Rotated square" YSLD title: 'YSLD Cook Book: Rotated square' feature-styles: - name: name rules: - symbolizers: - point: size: 12 rotation: 45 symbols: - mark: shape: square fill-color: '#009900' 1 2 3 4 5 6 7 8 9 10 11 12 Details In this example, line 11 sets the shape to be a square, with line 12 setting the color to a dark green (009900). Line 7 sets the size of the square to be 12 pixels, and line 8 sets the rotation to 45 degrees. 648 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Transparent triangle This example draws a triangle, creates a black stroke identical to the Simple point with stroke example, and sets the fill of the triangle to 20% opacity (mostly transparent). Fig. 6.223: Transparent triangle Code Download the "Transparent triangle" YSLD title: 'YSLD Cook Book: Transparent triangle' feature-styles: - name: name rules: - symbolizers: - point: size: 12 symbols: - mark: shape: triangle stroke-color: '#000000' stroke-width: 2 fill-color: '#009900' fill-opacity: 0.2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Details In this example, line 10 once again sets the shape, in this case to a triangle. Line 13 sets the fill color to a dark green ('#009900') and line 14 sets the opacity to 0.2 (20% opaque). An opacity value of 1 means that the shape is drawn 100% opaque, while an opacity value of 0 means that the shape is drawn 0% opaque, or completely transparent. The value of 0.2 (20% opaque) means that the fill of the points partially takes on the color and style of whatever is drawn beneath it. In this example, since the background is white, the dark green looks lighter. Were the points imposed on a dark background, 6.5. YSLD Styling 649 GeoServer User Manual, Release 2.15.1 the resulting color would be darker. Lines 11-12 set the stroke color to black ('#000000') and width to 2 pixels. Finally, line 7 sets the size of the point to be 12 pixels in diameter. Point as graphic This example styles each point as a graphic instead of as a simple shape. Fig. 6.224: Point as graphic Code Download the "Point as graphic" YSLD title: 'YSLD Cook Book: Point as graphic' feature-styles: - name: name rules: - symbolizers: - point: size: 32 symbols: - external: url: smileyface.png format: image/png 1 2 3 4 5 6 7 8 9 10 11 Details This style uses a graphic instead of a simple shape to render the points. In YSLD, this is known as an external, to distinguish it from the commonly-used shapes such as squares and circles that are “internal” to the renderer. Lines 9-11 specify the details of this graphic. Line 10 sets the path and file name of the graphic, while line 11 indicates the format (MIME type) of the graphic (image/png). In this example, the graphic is contained in the same directory as the YSLD, so no path information is necessary in line 10, 650 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 although a full URL could be used if desired. Line 7 determines the size of the displayed graphic; this can be set independently of the dimensions of the graphic itself, although in this case they are the same (32 pixels). Should a graphic be rectangular, the size value will apply to the height of the graphic only, with the width scaled proportionally. Fig. 6.225: Graphic used for points Point with default label This example shows a text label on the Simple point that displays the “name” attribute of the point. This is how a label will be displayed in the absence of any other customization. Fig. 6.226: Point with default label Code Download the "Point with default label" YSLD title: 'YSLD Cook Book: Point with default label' feature-styles: - name: name rules: - symbolizers: - point: size: 6 symbols: - mark: shape: circle fill-color: '#FF0000' - text: label: ${name} fill-color: '#000000' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6.5. YSLD Styling 651 GeoServer User Manual, Release 2.15.1 font-family: Serif font-size: 10 font-style: normal font-weight: normal placement: point 15 16 17 18 19 Details Lines 2-11, which contain the point symbolizer, are identical to the Simple point example above. The label is set in the text symbolizer on lines 12-19. Line 13 determines what text to display in the label, which in this case is the value of the “name” attribute. (Refer to the attribute table in the Example points layer section if necessary.) Line 15 sets the text color. All other details about the label are set to the renderer default, which here is Times New Roman font, font color black, and font size of 10 pixels. The bottom left of the label is aligned with the center of the point. Point with styled label This example improves the label style from the Point with default label example by centering the label above the point and providing a different font name and size. Fig. 6.227: Point with styled label Code Download the "Point with styled label" YSLD title: 'YSLD Cook Book: Point with styled label' feature-styles: - name: name rules: - symbolizers: - point: 1 2 3 4 5 6 652 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 size: 6 symbols: - mark: shape: circle fill-color: '#FF0000' - text: label: ${name} fill-color: '#000000' font-family: Arial font-size: 12 font-style: normal font-weight: bold placement: point anchor: [0.5,0.0] displacement: [0,5] 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 Details In this example, lines 2-11 are identical to the Simple point example above. The on lines 12-21 contains many more details about the label styling than the previous example, Point with default label. Line 13 once again specifies the “name” attribute as text to display. Lines 15-18 set the font information: line 15 sets the font family to be “Arial”, line 16 sets the font size to 12, line 17 sets the font style to “normal” (as opposed to “italic” or “oblique”), and line 18 sets the font weight to “bold” (as opposed to “normal”). Lines 19-21 determine the placement of the label relative to the point. The anchor (line 20) sets the point of intersection between the label and point, which here sets the point to be centered (0.5) horizontally axis and bottom aligned (0.0) vertically with the label. There is also displacement (line 21), which sets the offset of the label relative to the line, which in this case is 0 pixels horizontally and 5 pixels vertically . Finally, line 14 sets the font color of the label to black ('#000000'). The result is a centered bold label placed slightly above each point. Point with rotated label This example builds on the previous example, Point with styled label, by rotating the label by 45 degrees, positioning the labels farther away from the points, and changing the color of the label to purple. Code Download the "Point with rotated label" YSLD title: 'YSLD Cook Book: Point with rotated label' feature-styles: - name: name rules: - symbolizers: 1 2 3 4 5 6.5. YSLD Styling 653 GeoServer User Manual, Release 2.15.1 Fig. 6.228: Point with rotated label - point: size: 6 symbols: - mark: shape: circle fill-color: '#FF0000' - text: label: ${name} fill-color: '#990099' font-family: Arial font-size: 12 font-style: normal font-weight: bold placement: point anchor: [0.5,0.0] displacement: [0,25] rotation: -45 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Details This example is similar to the Point with styled label, but there are three important differences. Line 21 specifies 25 pixels of vertical displacement. Line 22 specifies a rotation of “-45” or 45 degrees counter-clockwise. (Rotation values increase clockwise, which is why the value is negative.) Finally, line 14 sets the font color to be a shade of purple ('#99099'). Note that the displacement takes effect before the rotation during rendering, so in this example, the 25 pixel vertical displacement is itself rotated 45 degrees. Attribute-based point This example alters the size of the symbol based on the value of the population (“pop”) attribute. 654 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.229: Attribute-based point Code Download the "Attribute-based point" YSLD title: 'YSLD Cook Book: Attribute-based point' feature-styles: - name: name rules: - name: SmallPop title: 1 to 50000 filter: ${pop < '50000'} symbolizers: - point: size: 8 symbols: - mark: shape: circle fill-color: '#0033CC' - name: MediumPop title: 50000 to 100000 filter: ${pop >= '50000' AND pop < '100000'} symbolizers: - point: size: 12 symbols: - mark: shape: circle fill-color: '#0033CC' - name: LargePop title: Greater than 100000 filter: ${pop >= '100000'} symbolizers: - point: size: 16 symbols: - mark: shape: circle fill-color: '#0033CC' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 6.5. YSLD Styling 655 GeoServer User Manual, Release 2.15.1 Details Note: Refer to the Example points layer to see the attributes for this data. This example has eschewed labels in order to simplify the style, but you can refer to the example Point with styled label to see which attributes correspond to which points. This style contains three rules. Each rule varies the style based on the value of the population (“pop”) attribute for each point, with smaller values yielding a smaller circle, and larger values yielding a larger circle. The three rules are designed as follows: Rule order 1 2 3 Rule name SmallPop MediumPop LargePop Population (pop) Less than 50,000 50,000 to 100,000 Greater than 100,000 Size 8 12 16 The order of the rules does not matter in this case, since each shape is only rendered by a single rule. The first rule, on lines 5-14, specifies the styling of those points whose population attribute is less than 50,000. Line 7 sets this filter, denoting the attribute (“pop”) to be “less than” the value of 50,000. The symbol is a circle (line 13), the color is dark blue ('#0033CC', on line 15), and the size is 8 pixels in diameter (line 18). The second rule, on lines 15-24, specifies a style for points whose population attribute is greater than or equal to 50,000 and less than 100,000. The population filter is set on line 17. This filter specifies two criteria instead of one: a “greater than or equal to” and a “less than” filter. These criteria are joined by AND, which mandates that both filters need to be true for the rule to be applicable. The size of the graphic is set to 12 pixels on line 20. All other styling directives are identical to the first rule. The third rule, on lines 25-34, specifies a style for points whose population attribute is greater than or equal to 100,000. The population filter is set on line 27, and the only other difference is the size of the circle, which in this rule (line 30) is 16 pixels. The result of this style is that cities with larger populations have larger points. Zoom-based point This example alters the style of the points at different zoom levels. Code Download the "Zoom-based point" YSLD 656 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.230: Zoom-based point: Zoomed in Fig. 6.231: Zoom-based point: Partially zoomed 6.5. YSLD Styling 657 GeoServer User Manual, Release 2.15.1 Fig. 6.232: Zoom-based point: Zoomed out title: 'YSLD Cook Book: Zoom-based point' feature-styles: - name: name rules: - name: Large scale: [min,1.6e8] symbolizers: - point: size: 12 symbols: - mark: shape: circle fill-color: '#CC3300' - name: Medium scale: [1.6e8,3.2e8] symbolizers: - point: size: 8 symbols: - mark: shape: circle fill-color: '#CC3300' - name: Small scale: [3.2e8,max] symbolizers: - point: size: 4 symbols: - mark: shape: circle fill-color: '#CC3300' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Details It is often desirable to make shapes larger at higher zoom levels when creating a natural-looking map. This example styles the points to vary in size based on the zoom level (or more accurately, scale denominator). Scale denominators refer to the scale of the map. A 658 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 scale denominator of 10,000 means the map has a scale of 1:10,000 in the units of the map projection. Note: Determining the appropriate scale denominators (zoom levels) to use is beyond the scope of this example. This style contains three rules. The three rules are designed as follows: Rule order 1 2 Rule name Large Medium 3 Small Scale denominator 1:160,000,000 or less 1:160,000,000 to 1:320,000,000 Greater than 1:320,000,000 Point size 12 8 4 The order of these rules does not matter since the scales denominated in each rule do not overlap. The first rule (lines 5-13) is for the smallest scale denominator, corresponding to when the view is “zoomed in”. The scale rule is set on line 6, so that the rule will apply to any map with a scale denominator of 160,000,000 or less. The rule draws a circle (line 12), colored red (#CC3300 on line 13) with a size of 12 pixels (line 9). The second rule (lines 14-22) is the intermediate scale denominator, corresponding to when the view is “partially zoomed”. The scale rules is set on line 15, so that the rule will apply to any map with a scale denominator between 160,000,000 and 320,000,000. (The lower bound is inclusive and the upper bound is exclusive, so a zoom level of exactly 320,000,000 would not apply here.) Aside from the scale, the only difference between this rule and the first is the size of the symbol, which is set to 8 pixels on line 18. The third rule (lines 23-31) is the largest scale denominator, corresponding to when the map is “zoomed out”. The scale rule is set on line 24, so that the rule will apply to any map with a scale denominator of 320,000,000 or more. Again, the only other difference between this rule and the others is the size of the symbol, which is set to 4 pixels on line 27. The result of this style is that points are drawn larger as one zooms in and smaller as one zooms out. Lines While lines can also seem to be simple shapes, having length but no width, there are many options and tricks for making lines display nicely. 6.5. YSLD Styling 659 GeoServer User Manual, Release 2.15.1 Example lines layer The lines layer used in the examples below contains road information for a fictional country. For reference, the attribute table for the points in this layer is included below. fid (Feature ID) line.1 line.2 line.3 line.4 line.5 line.6 line.7 line.8 line.9 line.10 line.11 line.12 line.13 line.14 line.15 line.16 line.17 line.18 line.19 line.20 line.21 line.22 line.23 line.24 line.25 name (Road name) Latway Crescent Avenue Forest Avenue Longway Saxer Avenue Ridge Avenue Holly Lane Mulberry Street Nathan Lane Central Street Lois Lane Rocky Road Fleet Street Diane Court Cedar Trail Victory Road Highland Road Easy Street Hill Street Country Road Main Street Jani Lane Shinbone Alley State Street River Road type (Road class) highway secondary secondary highway secondary secondary local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road Download the lines shapefile Simple line This example specifies lines be colored black with a thickness of 3 pixels. Code Download the "Simple line" YSLD title: 'YSLD Cook Book: Simple Line' feature-styles: - name: name rules: - symbolizers: - line: 1 2 3 4 5 6 660 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.233: Simple line stroke-color: '#000000' stroke-width: 3 7 8 Details There is one rule in one feature style for this YSLD, which is the simplest possible situation. (All subsequent examples will contain one rule and one feature style unless otherwise specified.) Styling lines is accomplished via the line symbolizer (lines 5-8). Line 7 specifies the color of the line to be black ('#000000'), while line 8 specifies the width of the lines to be 3 pixels. Line with border This example shows how to draw lines with borders (sometimes called “cased lines”). In this case the lines are drawn with a 3 pixel blue center and a 1 pixel wide gray border. Code Download the "Line with border" YSLD title: 'YSLD Cook Book: Line with border' feature-styles: - name: name rules: - symbolizers: - line: 1 2 3 4 5 6 6.5. YSLD Styling 661 GeoServer User Manual, Release 2.15.1 Fig. 6.234: Line with border stroke-color: '#333333' stroke-width: 5 stroke-linecap: round - name: name rules: - symbolizers: - line: stroke-color: '#6699FF' stroke-width: 3 stroke-linecap: round 7 8 9 10 11 12 13 14 15 16 Details Lines in YSLD have no notion of a “fill”, only “stroke”. Thus, unlike points or polygons, it is not possible to style the “edge” of the line geometry. It is, however, possible to achieve this effect by drawing each line twice: once with a certain width and again with a slightly smaller width. This gives the illusion of fill and stroke by obscuring the larger lines everywhere except along the edges of the smaller lines. Since every line is drawn twice, the order of the rendering is very important. GeoServer renders feature-styles in the order that they are presented in the YSLD. In this style, the gray border lines are drawn first via the first feature style, followed by the blue center lines in a second feature style. This ensures that the blue lines are not obscured by the gray lines, and also ensures proper rendering at intersections, so that the blue lines “connect”. In this example, lines 3-9 comprise the first feature style, which is the outer line (or “stroke”). Line 7 specifies the color of the line to be 662 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 dark gray ('#333333'), line 8 specifies the width of this line to be 5 pixels, and in line 9 a stroke-linecap parameter of round renders the ends of the line as rounded instead of flat. (When working with bordered lines using a round line cap ensures that the border connects properly at the ends of the lines.) Lines 10-16 comprise the second feature-style, which is the the inner line (or “fill”). Line 14 specifies the color of the line to be a medium blue ('#6699FF'), line 15 specifies the width of this line to be 3 pixels, and line 16 again renders the edges of the line to be rounded instead of flat. The result is a 3 pixel blue line with a 1 pixel gray border, since the 5 pixel gray line will display 1 pixel on each side of the 3 pixel blue line. Dashed line This example alters the Simple line to create a dashed line consisting of 5 pixels of drawn line alternating with 2 pixels of blank space. Fig. 6.235: Dashed line Code Download the "Dashed line" YSLD title: 'YSLD Cook Book: Dashed line' feature-styles: - name: name rules: - symbolizers: - line: 1 2 3 4 5 6 6.5. YSLD Styling 663 GeoServer User Manual, Release 2.15.1 stroke-color: '#0000FF' stroke-width: 3 stroke-dasharray: 5 2 7 8 9 Details In this example, line 8 sets the color of the lines to be blue ('#0000FF') and line 8 sets the width of the lines to be 3 pixels. Line 9 determines the composition of the line dashes. The value of 5 2 creates a repeating pattern of 5 pixels of drawn line, followed by 2 pixels of omitted line. Offset line This example alters the Simple line to add a perpendicular offset line on the left side of the line, at five pixels distance. Fig. 6.236: Dashed line Code Download the "Offset line" YSLD title: 'YSLD Cook Book: Dashed line' feature-styles: - name: name rules: - symbolizers: - line: stroke-color: '#000000' 1 2 3 4 5 6 7 664 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 stroke-width: 2 - line: stroke-color: '#0000FF' stroke-width: 3 stroke-dasharray: 5 2 offset: 3 8 9 10 11 12 13 Details In this example, lines 6-8 draw a simple black line like in the Simple line example. Lines 9-12 draw a blue dashed line like in the above Dashed line example. Line 13 modifies the dashed line with a 3 pixel offset from the line geometry. Railroad (hatching) This example uses hatching to create a railroad style. Both the line and the hatches are black, with a 2 pixel thickness for the main line and a 1 pixel width for the perpendicular hatches. Fig. 6.237: Railroad (hatching) Code Download the "Railroad (hatching)" YSLD title: 'YSLD Cook Book: Railroad (hatching)' feature-styles: - name: name rules: 1 2 3 4 6.5. YSLD Styling 665 GeoServer User Manual, Release 2.15.1 - symbolizers: - line: stroke-color: '#333333' stroke-width: 3 - line: stroke-color: '#333333' stroke-width: 1 stroke-graphic-stroke: size: 12 symbols: - mark: shape: shape://vertline stroke-color: '#333333' stroke-width: 1 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Details In this example there are two line symbolizers. The first symbolizer, on lines 6-8, draws a standard line, with line 7 drawing the lines as dark gray ('#333333') and line 8 setting the width of the lines to be 2 pixels. The hatching is invoked in the second symbolizer, on lines 9-18. Line 16 specifies that the symbolizer draw a vertical line hatch (shape://vertline) perpendicular to the line geometry. Lines 17-18 set the hatch color to dark gray ('#333333') and width to 1 pixel. Finally, line 13 specifies both the length of the hatch and the distance between each hatch to both be 12 pixels. Spaced graphic symbols This example uses a graphic stroke along with dash arrays to create a “dot and space” line type. Adding the dash array specification allows to control the amount of space between one symbol and the next one. Without using the dash array the lines would be densely populated with dots, each one touching the previous one. Code Download the "Spaced symbols" YSLD name: Default Styler title: 'YSLD Cook Book: Dash/Space line' feature-styles: - name: name rules: - symbolizers: - line: stroke-color: '#333333' stroke-width: 1 stroke-dasharray: 4 6 stroke-graphic-stroke: size: 4 1 2 3 4 5 6 7 8 9 10 11 12 666 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.238: Spaced symbols along a line symbols: - mark: shape: circle stroke-color: '#333333' stroke-width: 1 fill-color: '#666666' 13 14 15 16 17 18 Details This example, like others before, uses a stroke-graphic-stroke to place a graphic symbol along a line. The symbol, defined on lines 14-18 is a 4 pixel gray circle with a dark gray outline. The spacing between symbols is controlled with the stroke-dasharray at line 9, which specifies 4 pixels of pen-down (just enough to draw the circle) and 6 pixels of pen-up, to provide the spacing. Alternating symbols with dash offsets This example shows how to create a complex line style which alternates a dashed line and a graphic symbol. The code builds on features shown in the previous examples: • stroke-dasharray controls pen-down/pen-up behavior to generate dashed lines • stroke-graphic-stroke places symbols along a line • combining the two allows control of symbol spacing This also shows the usage of a dash offset, which controls where rendering starts in the dash array. For example, with a dash array of 5 10 and a dash offset of 7 the renderer starts drawing the pattern 7 pixels from the beginning. It skips the 5 pixels pen-down section and 2 pixels of the pen-up section, then draws the remaining 8 pixels of pen-up, then 5 down, 10 up, and so on. 6.5. YSLD Styling 667 GeoServer User Manual, Release 2.15.1 The example shows how to use these features to create two synchronized sequences of dash arrays, one drawing line segments and the other symbols. Fig. 6.239: Alternating dash and symbol Code Download the "Spaced symbols" YSLD title: 'YSLD Cook Book: Dash/Symbol line' feature-styles: - name: name rules: - symbolizers: - line: stroke-color: '#0000FF' stroke-width: 1 stroke-dasharray: 10 10 - line: stroke-color: '#000033' stroke-width: 1 stroke-dasharray: 5 15 stroke-dashoffset: 7.5 stroke-graphic-stroke: size: 5 symbols: - mark: shape: circle stroke-color: '#000033' stroke-width: 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 Details In this example two line symbolizers use stroke-dasharray and different symbology to produce a sequence of alternating dashes 668 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 and symbols. The first symbolizer (lines 6-9) is a simple dashed line alternating 10 pixels of pen-down with 10 pixels of pen-up. The second symbolizer (lines 10-21) alternates a 5 pixel empty circle with 15 pixels of white space. The circle symbol is produced by a mark element, with its symbology specified by stroke parameters (lines 20-21). The spacing between symbols is controlled with the stroke-dasharray (line 13), which specifies 5 pixels of pen-down (just enough to draw the circle) and 15 pixels of pen-up. In order to have the two sequences positioned correctly the second one uses a stroke-dashoffset of 7.5 (line 14). This makes the sequence start with 12.5 pixels of white space, then a circle (which is then centered between the two line segments of the other pattern), then 15 pixels of white space, and so on. Line with default label This example shows a text label on the simple line. This is how a label will be displayed in the absence of any other customization. Fig. 6.240: Line with default label Code Download the "Line with default label" YSLD name: Default Styler title: 'YSLD Cook Book: Line with default label' feature-styles: - name: name rules: - symbolizers: - line: stroke-color: '#FF0000' 1 2 3 4 5 6 7 8 6.5. YSLD Styling 669 GeoServer User Manual, Release 2.15.1 stroke-width: 1 - text: label: ${name} fill-color: '#000000' font-family: Serif font-size: 10 font-style: normal font-weight: normal placement: point 9 10 11 12 13 14 15 16 17 Details In this example, there is one rule with a line symbolizer and a text symbolizer. The line symbolizer (lines 6-8) draws red lines ('#FF0000'). The text symbolizer (lines 10-17) determines the labeling of the lines. Line 10 specifies that the text of the label will be determined by the value of the “name” attribute for each line. (Refer to the attribute table in the Example lines layer section if necessary.) Line 11 sets the text color to black. All other details about the label are set to the renderer default, which here is Times New Roman font, font color black, and font size of 10 pixels. Label following line This example renders the text label to follow the contour of the lines. Fig. 6.241: Label following line 670 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Code Download the "Label following line" YSLD title: 'YSLD Cook Book: Label following line' feature-styles: - name: name rules: - symbolizers: - line: stroke-color: '#FF0000' stroke-width: 1 - text: label: ${name} fill-color: '#000000' placement: line offset: 0 x-followLine: true 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Details As the Alternating symbols with dash offsets example showed, the default label behavior isn’t optimal. The label is displayed at a tangent to the line itself, leading to uncertainty as to which label corresponds to which line. This example is similar to the Alternating symbols with dash offsets example with the exception of lines 12-14. Line 14 sets the option to have the label follow the line, while lines 12-13 specify that the label is placed along a line. If placement: line is not specified in an YSLD, then placement: point is assumed, which isn’t compatible with line-specific rendering options. Note: Not all labels are shown due to label conflict resolution. See the next section on Optimized label placement for an example of how to maximize label display. Optimized label placement This example optimizes label placement for lines such that the maximum number of labels are displayed. Code Download the "Optimized label" YSLD title: 'YSLD Cook Book: Optimized label placement' feature-styles: - name: name rules: - symbolizers: - line: 1 2 3 4 5 6 6.5. YSLD Styling 671 GeoServer User Manual, Release 2.15.1 Fig. 6.242: Optimized label stroke-color: '#FF0000' stroke-width: 1 - text: label: ${name} fill-color: '#000000' placement: line offset: 0 x-followLine: true x-maxAngleDelta: 90 x-maxDisplacement: 400 x-repeat: 150 7 8 9 10 11 12 13 14 15 16 17 Details GeoServer uses “conflict resolution” to ensure that labels aren’t drawn on top of other labels, obscuring them both. This accounts for the reason why many lines don’t have labels in the previous example, Label following line. While this setting can be toggled, it is usually a good idea to leave it on and use other label placement options to ensure that labels are drawn as often as desired and in the correct places. This example does just that. This example is similar to the previous example, Label following line. The only differences are contained in lines 15-17. Line 15 sets the maximum angle that the label will follow. This sets the label to never bend more than 90 degrees to prevent the label from becoming illegible due to a pronounced curve or angle. Line 16 sets the maximum displacement of the label to be 400 pixels. In order to resolve conflicts with overlapping labels, GeoServer will attempt to move the labels such that they are no longer overlapping. This value sets how far the label can be moved relative to its original placement. Finally, 672 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 line 17 sets the labels to be repeated every 150 pixels. A feature will typically receive only one label, but this can cause confusion for long lines. Setting the label to repeat ensures that the line is always labeled locally. Optimized and styled label This example improves the style of the labels from the Optimized label placement example. Fig. 6.243: Optimized and styled label Code Download the "Optimized and styled label" YSLD title: 'YSLD Cook Book: Optimized and styled label' feature-styles: - name: name rules: - symbolizers: - line: stroke-color: '#FF0000' stroke-width: 1 - text: label: ${name} fill-color: '#000000' font-family: Arial font-size: 10 font-style: normal font-weight: bold placement: line offset: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 6.5. YSLD Styling 673 GeoServer User Manual, Release 2.15.1 x-followLine: true x-maxAngleDelta: 90 x-maxDisplacement: 400 x-repeat: 150 18 19 20 21 Details This example is similar to the Optimized label placement. The only difference is in the font information, which is contained in lines 1215. Line 12 sets the font family to be “Arial”, line 13 sets the font size to 10, line 14 sets the font style to “normal” (as opposed to “italic” or “oblique”), and line 15 sets the font weight to “bold” (as opposed to “normal”). Attribute-based line This example styles the lines differently based on the “type” (Road class) attribute. Fig. 6.244: Attribute-based line Code Download the "Attribute-based line" YSLD title: 'YSLD Cook Book: Attribute-based line' feature-styles: - name: name rules: - name: local-road 1 2 3 4 5 674 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 filter: ${type = 'local-road'} symbolizers: - line: stroke-color: '#009933' stroke-width: 2 - name: name rules: - name: secondary filter: ${type = 'secondary'} symbolizers: - line: stroke-color: '#0055CC' stroke-width: 3 - name: name rules: - name: highway filter: ${type = 'highway'} symbolizers: - line: stroke-color: '#FF0000' stroke-width: 6 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 Details Note: Refer to the Example lines layer to see the attributes for the layer. This example has eschewed labels in order to simplify the style, but you can refer to the example Optimized and styled label to see which attributes correspond to which points. There are three types of road classes in our fictional country, ranging from back roads to high-speed freeways: “highway”, “secondary”, and “local-road”. In order to handle each case separately, there is more than one feature style, each containing a single rule. This ensures that each road type is rendered in order, as each feature style is drawn based on the order in which it appears in the YSLD. The three rules are designed as follows: Rule order 1 2 3 Rule name / type local-road secondary highway Color #009933 (green) #0055CC (blue) #FF0000 (red) Size 2 3 6 Lines 3-10 comprise the first rule. Line 6 sets the filter for this rule, such that the “type” attribute has a value of “local-road”. If this condition is true for a particular line, the rule is rendered according to the line symbolizer which is on lines 8-10. Lines 9-10 set the color of the line to be a dark green ('#009933') and the width to be 2 pixels. Lines 11-18 comprise the second rule. Line 14 sets the filter for this rule, such that the “type” attribute has a value of “secondary”. If this condition is true for a particular line, the rule is rendered according to the line symbolizer which is on lines 16-18. Lines 17-18 set the 6.5. YSLD Styling 675 GeoServer User Manual, Release 2.15.1 color of the line to be a dark blue ('#0055CC') and the width to be 3 pixels, making the lines slightly thicker than the “local-road” lines and also a different color. Lines 19-26 comprise the third and final rule. Line 22 sets the filter for this rule, such that the “type” attribute has a value of “primary”. If this condition is true for a particular line, the rule is rendered according to the line symbolizer which is on lines 24-26. Lines 25-26 set the color of the line to be a bright red ('#FF0000') and the width to be 6 pixels, so that these lines are rendered on top of and thicker than the other two road classes. In this way, the “primary” roads are given priority in the map rendering. Zoom-based line This example alters the Simple line style at different zoom levels. Fig. 6.245: Zoom-based line: Zoomed in Code Download the "Zoom-based line" YSLD title: 'YSLD Cook Book: Zoom-based line' feature-styles: - name: name rules: - name: Large scale: [min,1.8e8] symbolizers: - line: stroke-color: '#009933' 1 2 3 4 5 6 7 8 9 676 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.246: Zoom-based line: Partially zoomed Fig. 6.247: Zoom-based line: Zoomed out 6.5. YSLD Styling 677 GeoServer User Manual, Release 2.15.1 stroke-width: 6 - name: Medium scale: [1.8e8,3.6e8] symbolizers: - line: stroke-color: '#009933' stroke-width: 4 - name: Small scale: [3.6e8,max] symbolizers: - line: stroke-color: '#009933' stroke-width: 2 10 11 12 13 14 15 16 17 18 19 20 21 22 Details It is often desirable to make shapes larger at higher zoom levels when creating a natural-looking map. This example varies the thickness of the lines according to the zoom level (or more accurately, scale denominator). Scale denominators refer to the scale of the map. A scale denominator of 10,000 means the map has a scale of 1:10,000 in the units of the map projection. Note: Determining the appropriate scale denominators (zoom levels) to use is beyond the scope of this example. This style contains three rules. The three rules are designed as follows: Rule order 1 2 3 Rule name Large Medium Small Scale denominator 1:180,000,000 or less 1:180,000,000 to 1:360,000,000 Greater than 1:360,000,000 Line width 6 4 2 The order of these rules does not matter since the scales denominated in each rule do not overlap. The first rule (lines 5-10) is the smallest scale denominator, corresponding to when the view is “zoomed in”. The scale rule is set on line 6, so that the rule will apply to any map with a scale denominator of 180,000,000 or less. Lines 9-10 draw the line to be dark green ('#009933') with a width of 6 pixels. The second rule (lines 11-16) is the intermediate scale denominator, corresponding to when the view is “partially zoomed”. Lines 12 set the scale such that the rule will apply to any map with scale denominators between 180,000,000 and 360,000,000. (The lower bound is inclusive and the upper bound is exclusive, so a zoom level of exactly 360,000,000 would not apply here.) Aside from the scale, the only difference between this rule and the previous is the width of the lines, which is set to 4 pixels on line 16. 678 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 The third rule (lines 17-22) is the largest scale denominator, corresponding to when the map is “zoomed out”. The scale rule is set on line 18, so that the rule will apply to any map with a scale denominator of 360,000,000 or greater. Again, the only other difference between this rule and the others is the width of the lines, which is set to 2 pixels on line 22. The result of this style is that lines are drawn with larger widths as one zooms in and smaller widths as one zooms out. Polygons Polygons are two dimensional shapes that contain both an outer edge (or “stroke”) and an inside (or “fill”). A polygon can be thought of as an irregularly-shaped point and is styled in similar ways to points. Example polygons layer The polygons layer used below contains county information for a fictional country. For reference, the attribute table for the polygons is included below. fid (Feature ID) polygon.1 polygon.2 polygon.3 polygon.4 polygon.5 polygon.6 polygon.7 polygon.8 name (County name) Irony County Tracker County Dracula County Poly County Bearing County Monte Cristo County Massive County Rhombus County pop (Population) 412234 235421 135022 1567879 201989 152734 67123 198029 Download the polygons shapefile Simple polygon This example shows a polygon filled in blue. Code Download the "Simple polygon" YSLD title: 'YSLD Cook Book: Simple polygon' feature-styles: - name: name rules: - symbolizers: - polygon: fill-color: '#000080' 1 2 3 4 5 6 7 6.5. YSLD Styling 679 GeoServer User Manual, Release 2.15.1 Fig. 6.248: Simple polygon Details There is one rule in one feature style for this style, which is the simplest possible situation. (All subsequent examples will share this characteristic unless otherwise specified.) Styling polygons is accomplished via the polygon symbolizer (lines 6-7). Line 7 specifies dark blue ('#000080') as the polygon’s fill color. Note: The light-colored borders around the polygons in the figure are artifacts of the renderer caused by the polygons being adjacent. There is no border in this style. Simple polygon with stroke This example adds a 2 pixel white stroke to the Simple polygon example. Code Download the "Simple polygon with stroke" YSLD title: 'YSLD Cook Book: Simple polygon with stroke' feature-styles: - name: name rules: - symbolizers: - polygon: stroke-color: '#FFFFFF' 1 2 3 4 5 6 7 680 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.249: Simple polygon with stroke stroke-width: 2 fill-color: '#000080' 8 9 Details This example is similar to the Simple polygon example above, with the addition of stroke parameters (lines 7-8). Line 7 sets the color of stroke to white ('#FFFFFF') and line 8 sets the width of the stroke to 2 pixels. Transparent polygon This example builds on the Simple polygon with stroke example and makes the fill partially transparent by setting the opacity to 50%. Code Download the "Transparent polygon" YSLD title: 'YSLD Cook Book: Transparent polygon' feature-styles: - name: name rules: - symbolizers: - polygon: stroke-color: '#FFFFFF' stroke-width: 2 1 2 3 4 5 6 7 8 6.5. YSLD Styling 681 GeoServer User Manual, Release 2.15.1 Fig. 6.250: Transparent polygon fill-color: '#000080' fill-opacity: 0.5 9 10 Details This example is similar to the Simple polygon with stroke example, save for defining the fill’s opacity in line 10. The value of 0.5 results in partially transparent fill that is 50% opaque. An opacity value of 1 would draw the fill as 100% opaque, while an opacity value of 0 would result in a completely transparent (0% opaque) fill. In this example, since the background is white, the dark blue looks lighter. Were the points imposed on a dark background, the resulting color would be darker. Graphic fill This example fills the polygons with a tiled graphic. Code Download the "Graphic fill" YSLD title: 'YSLD Cook Book: Graphic fill' feature-styles: - name: name rules: - symbolizers: - polygon: 1 2 3 4 5 6 682 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.251: Graphic fill fill-color: '#808080' fill-graphic: size: 93 symbols: - external: url: colorblocks.png format: image/png 7 8 9 10 11 12 13 Details This style fills the polygon with a tiled graphic. This is known as an external in YSLD, to distinguish it from commonly-used shapes such as squares and circles that are “internal” to the renderer. Lines 11-13 specify details for the graphic, with line 12 setting the path and file name of the graphic and line 13 indicating the file format (MIME type) of the graphic (image/png). Although a full URL could be specified if desired, no path information is necessary in line 12 because this graphic is contained in the same directory as the YSLD. Line 9 determines the height of the displayed graphic in pixels; if the value differs from the height of the graphic then it will be scaled accordingly while preserving the aspect ratio. Fig. 6.252: Graphic used for fill 6.5. YSLD Styling 683 GeoServer User Manual, Release 2.15.1 Hatching fill This example fills the polygons with a hatching pattern. Fig. 6.253: Hatching fill Code Download the "Hatching fill" YSLD title: 'YSLD Cook Book: Hatching fill' feature-styles: - name: name rules: - symbolizers: - polygon: fill-color: '#808080' fill-graphic: size: 16 symbols: - mark: shape: shape://times stroke-color: '#990099' stroke-width: 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Details In this example, there is a fill-graphic parameter as in the Graphic fill example, but a mark (lines 11-14) is used instead of an external. Line 12 specifies a “times” symbol (an “x”) be tiled throughout the polygon. Line 13 sets the color to purple ('#990099'), line 14 sets the width of the hatches to 1 pixel, and 684 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 line 9 sets the size of the tile to 16 pixels. Because hatch tiles are always square, the size sets both the width and the height. Polygon with default label This example shows a text label on the polygon. In the absence of any other customization, this is how a label will be displayed. Fig. 6.254: Polygon with default label Code Download the "Polygon with default label" YSLD title: 'YSLD Cook Book: Polygon with default label' feature-styles: - name: name rules: - symbolizers: - polygon: stroke-color: '#FFFFFF' stroke-width: 2 fill-color: '#40FF40' - text: label: ${name} placement: point 1 2 3 4 5 6 7 8 9 10 11 12 Details In this example there is a polygon symbolizer and a text symbolizer. Lines 6-9 comprise the polygon symbolizer. The fill of the polygon 6.5. YSLD Styling 685 GeoServer User Manual, Release 2.15.1 is set on line 7 to a light green ('#40FF40') while the stroke of the polygon is set on lines 8-9 to white ('#FFFFFF') with a thickness of 2 pixels. The label is set in the text symbolizer on lines 10-12, with line 11 determining what text to display, in this case the value of the “name” attribute. (Refer to the attribute table in the Example polygons layer section if necessary.) All other details about the label are set to the renderer default, which here is Times New Roman font, font color black, and font size of 10 pixels. Label halo This example alters the look of the Polygon with default label by adding a white halo to the label. Fig. 6.255: Label halo Code Download the "Label halo" YSLD title: 'YSLD Cook Book: Label halo' feature-styles: - name: name rules: - symbolizers: - polygon: stroke-color: '#FFFFFF' stroke-width: 2 fill-color: '#40FF40' - text: label: ${name} halo: 1 2 3 4 5 6 7 8 9 10 11 12 686 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 fill-color: '#FFFFFF' radius: 3 placement: type: point 13 14 15 16 Details This example is similar to the Polygon with default label, with the addition of a halo around the labels on lines 12-14. A halo creates a color buffer around the label to improve label legibility. Line 14 sets the radius of the halo, extending the halo 3 pixels around the edge of the label, and line 13 sets the color of the halo to white ('#FFFFFF'). Since halos are most useful when set to a sharp contrast relative to the text color, this example uses a white halo around black text to ensure optimum readability. Polygon with styled label This example improves the label style from the Polygon with default label example by centering the label on the polygon, specifying a different font name and size, and setting additional label placement optimizations. Fig. 6.256: Polygon with styled label Code Download the "Polygon with styled label" YSLD 6.5. YSLD Styling 687 GeoServer User Manual, Release 2.15.1 title: 'YSLD Cook Book: Polygon with styled label' feature-styles: - name: name rules: - symbolizers: - polygon: stroke-color: '#FFFFFF' stroke-width: 2 fill-color: '#40FF40' - text: label: ${name} fill-color: '#000000' font-family: Arial font-size: 11 font-style: normal font-weight: bold placement: point anchor: [0.5,0.5] x-autoWrap: 60 x-maxDisplacement: 150 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Details This example is similar to the Polygon with default label example, with additional styling options within the text symbolizer on lines 13-21. Lines 13-16 set the font styling. Line 13 sets the font family to be Arial, line 14 sets the font size to 11 pixels, line 15 sets the font style to “normal” (as opposed to “italic” or “oblique”), and line 16 sets the font weight to “bold” (as opposed to “normal”). The anchor parameter on line 18 centers the label by positioning it 50% (or 0.5) of the way horizontally and vertically along the centroid of the polygon. Finally, there are two added touches for label placement optimization: line 20 ensures that long labels are split across multiple lines by setting line wrapping on the labels to 60 pixels, and line 21 allows the label to be displaced by up to 150 pixels. This ensures that labels are compacted and less likely to spill over polygon boundaries. Notice little Massive County in the corner, whose label is now displayed.” Attribute-based polygon This example styles the polygons differently based on the “pop” (Population) attribute. Code Download the "Attribute-based polygon" YSLD 688 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.257: Attribute-based polygon title: 'YSLD Cook Book: Attribute-based polygon' feature-styles: - name: name rules: - name: SmallPop title: Less Than 200,000 filter: ${pop < '200000'} symbolizers: - polygon: fill-color: '#66FF66' - name: MediumPop title: 200,000 to 500,000 filter: ${pop >= '200000' AND pop < '500000'} symbolizers: - polygon: fill-color: '#33CC33' - name: LargePop title: ${Greater Than 500,000} filter: pop > '500000' symbolizers: - polygon: fill-color: '#009900' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Details Note: Refer to the Example polygons layer to see the attributes for the layer. This example has eschewed labels in order to simplify the style, but you can refer to the example Polygon with styled label to see which attributes correspond to which polygons. Each polygon in our fictional country has a population that is repre6.5. YSLD Styling 689 GeoServer User Manual, Release 2.15.1 sented by the population (“pop”) attribute. This style contains three rules that alter the fill based on the value of “pop” attribute, with smaller values yielding a lighter color and larger values yielding a darker color. The three rules are designed as follows: Rule order 1 2 3 Rule name SmallPop MediumPop LargePop Population (pop) Less than 200,000 200,000 to 500,000 Greater than 500,000 Color #66FF66 #33CC33 #009900 The order of the rules does not matter in this case, since each shape is only rendered by a single rule. The first rule, on lines 5-10, specifies the styling of polygons whose population attribute is less than 200,000. Line 7 sets this filter, denoting the attribute (“pop”), to be “less than” the value of 200,000. The color of the polygon fill is set to a light green ('#66FF66') on line 10. The second rule, on lines 11-16, is similar, specifying a style for polygons whose population attribute is greater than or equal to 200,000 but less than 500,000. The filter is set on line 13. This filter specifies two criteria instead of one: a “greater than or equal to” and a “less than” filter. These criteria are joined by AND, which mandates that both filters need to be true for the rule to be applicable. The color of the polygon fill is set to a medium green on ('#33CC33') on line 16. The third rule, on lines 17-22, specifies a style for polygons whose population attribute is greater than or equal to 500,000. The filter is set on line 19. The color of the polygon fill is the only other difference in this rule, which is set to a dark green ('#009900') on line 22. Zoom-based polygon This example alters the style of the polygon at different zoom levels. Code Download the "Zoom-based polygon" YSLD title: 'YSLD Cook Book: Zoom-based polygon' feature-styles: - name: name rules: - name: Large scale: [min,1.0e8] symbolizers: - polygon: stroke-color: '#000000' 1 2 3 4 5 6 7 8 9 690 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.258: Zoom-based polygon: Zoomed in Fig. 6.259: Zoom-based polygon: Partially zoomed 6.5. YSLD Styling 691 GeoServer User Manual, Release 2.15.1 Fig. 6.260: Zoom-based polygon: Zoomed out stroke-width: 7 fill-color: '#0000CC' - text: label: ${name} fill-color: '#FFFFFF' font-family: Arial font-size: 14 font-style: normal font-weight: bold placement: point anchor: [0.5,0.5] - name: Medium scale: [1.0e8,2.0e8] symbolizers: - polygon: stroke-color: '#000000' stroke-width: 4 fill-color: '#0000CC' - name: Small scale: [2.0e8,max] symbolizers: - polygon: stroke-color: '#000000' stroke-width: 1 fill-color: '#0000CC' 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 Details It is often desirable to make shapes larger at higher zoom levels when creating a natural-looking map. This example varies the thickness of the lines according to the zoom level. Polygons already do 692 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 this by nature of being two dimensional, but another way to adjust styling of polygons based on zoom level is to adjust the thickness of the stroke (to be larger as the map is zoomed in) or to limit labels to only certain zoom levels. This is ensures that the size and quantity of strokes and labels remains legible and doesn’t overshadow the polygons themselves. Zoom levels (or more accurately, scale denominators) refer to the scale of the map. A scale denominator of 10,000 means the map has a scale of 1:10,000 in the units of the map projection. Note: Determining the appropriate scale denominators (zoom levels) to use is beyond the scope of this example. This style contains three rules, defined as follows: Rule order Rule name Scale denominator Stroke width 1 2 3 Large Medium Small 1:100,000,000 or less 1:100,000,000 to 1:200,000,000 Greater than 1:200,000,000 7 4 2 Label play? Yes No No dis- The first rule, on lines 5-20, is for the smallest scale denominator, corresponding to when the view is “zoomed in”. The scale rule is set on line 6 such that the rule will apply only where the scale denominator is 100,000,000 or less. Line 11 defines the fill as blue ('#0000CC'). Note that the fill is kept constant across all rules regardless of the scale denominator. As in the Polygon with default label or Polygon with styled label examples, the rule also contains a text symbolizer at lines 12-20 for drawing a text label on top of the polygon. Lines 15-18 set the font information to be Arial, 14 pixels, and bold with no italics. The label is centered both horizontally and vertically along the centroid of the polygon on by setting anchor to be [0.5, 0.5] (or 50%) on line 20. Finally, the color of the font is set to white ('#FFFFFF') in line 14. The second rule, on lines 21-27, is for the intermediate scale denominators, corresponding to when the view is “partially zoomed”. The scale rules on lines 22 set the rule such that it will apply to any map with a scale denominator between 100,000,000 and 200,000,000. (The lower bound is inclusive and the upper bound is exclusive, so a zoom level of exactly 200,000,000 would not apply here.) Aside from the scale, there are two differences between this rule and the first: the width of the stroke is set to 4 pixels on line 26 and a text symbolizer is not present so that no labels will be displayed. The third rule, on lines 28-34, is for the largest scale denominator, corresponding to when the map is “zoomed out”. The scale rule is set on line 29 such that the rule will apply to any map with a scale denominator of 200,000,000 or greater. Again, the only differences between this rule and the others are the width of the lines, which is set to 1 pixel on line 33, and the absence of a text symbolizer so that no labels will be displayed. 6.5. YSLD Styling 693 GeoServer User Manual, Release 2.15.1 The resulting style produces a polygon stroke that gets larger as one zooms in and labels that only display when zoomed in to a sufficient level. Rasters Rasters are geographic data displayed in a grid. They are similar to image files such as PNG files, except that instead of each point containing visual information, each point contains geographic information in numerical form. Rasters can be thought of as a georeferenced table of numerical values. One example of a raster is a Digital Elevation Model (DEM) layer, which has elevation data encoded numerically at each georeferenced data point. Example raster The raster layer that is used in the examples below contains elevation data for a fictional world. The data is stored in EPSG:4326 (longitude/latitude) and has a data range from 70 to 256. If rendered in grayscale, where minimum values are colored black and maximum values are colored white, the raster would look like this: Fig. 6.261: Raster file as rendered in grayscale Download the raster shapefile Two-color gradient This example shows a two-color style with green at lower elevations and brown at higher elevations. Code Download the "Two-color gradient" YSLD 694 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.262: Two-color gradient title: 'YSLD Cook Book: Two color gradient' feature-styles: - name: name rules: - symbolizers: - raster: opacity: 1.0 color-map: type: ramp entries: - ['#008000',1,70,''] - ['#663333',1,256,''] 1 2 3 4 5 6 7 8 9 10 11 12 Details There is one rule in one feature style for this example, which is the simplest possible situation. All subsequent examples will share this characteristic. Styling of rasters is done via the raster symbolizer (lines 2-7). This example creates a smooth gradient between two colors corresponding to two elevation values. The gradient is created via the color-map on lines 8-12. Each entry in the color-map represents one entry or anchor in the gradient. Line 11 sets the lower value of 70 and color to a dark green ('#008000'). Line 12 sets the upper value of 256 and color to a dark brown ('#663333'). Line 9 sets the type to ramp, which means that all data values in between these two quantities will be linearly interpolated: a value of 163 (the midpoint between 70 and 256) will be colored as the midpoint between the two colors (in this case approximately '#335717', a muddy green). Transparent gradient This example creates the same two-color gradient as in the Two-color gradient as in the example above but makes the entire layer mostly transparent by setting a 30% opacity. 6.5. YSLD Styling 695 GeoServer User Manual, Release 2.15.1 Fig. 6.263: Transparent gradient Code Download the "Transparent gradient" YSLD title: 'YSLD Cook Book: Transparent gradient' feature-styles: - name: name rules: - symbolizers: - raster: opacity: 0.3 color-map: type: ramp entries: - ['#008000',1,70,''] - ['#663333',1,256,''] 1 2 3 4 5 6 7 8 9 10 11 12 Details This example is similar to the Two-color gradient example save for the addition of line 7, which sets the opacity of the layer to 0.3 (or 30% opaque). An opacity value of 1 means that the shape is drawn 100% opaque, while an opacity value of 0 means that the shape is rendered as completely transparent. The value of 0.3 means that the the raster partially takes on the color and style of whatever is drawn beneath it. Since the background is white in this example, the colors generated from the color-map look lighter, but were the raster imposed on a dark background the resulting colors would be darker. Brightness and contrast This example normalizes the color output and then increases the brightness by a factor of 2. 696 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.264: Brightness and contrast Code Download the "Brightness and contrast" YSLD title: 'YSLD Cook Book: Brightness and contrast' feature-styles: - name: name rules: - symbolizers: - raster: opacity: 1 color-map: type: ramp entries: - ['#008000',1,70,''] - ['#663333',1,256,''] contrast-enhancement: mode: normalize gamma: 0.5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Details This example is similar to the Two-color gradient, save for the addition of the contrast-enhancement parameter on lines 13-15. Line 14 normalizes the output by increasing the contrast to its maximum extent. Line 15 then adjusts the brightness by a factor of 0.5. Since values less than 1 make the output brighter, a value of 0.5 makes the output twice as bright. As with previous examples, lines 8-12 determine the color-map, with line 11 setting the lower bound (70) to be colored dark green ('#008000') and line 12 setting the upper bound (256) to be colored dark brown ('#663333'). Three-color gradient This example creates a three-color gradient in primary colors. 6.5. YSLD Styling 697 GeoServer User Manual, Release 2.15.1 Fig. 6.265: Three-color gradient Code Download the "Three-color gradient" YSLD title: 'YSLD Cook Book: Three color gradient' feature-styles: - name: name rules: - symbolizers: - raster: opacity: 1 color-map: type: ramp entries: - ['#0000FF',1,150,''] - ['#FFFF00',1,200,''] - ['#FF0000',1,250,''] 1 2 3 4 5 6 7 8 9 10 11 12 13 Details This example creates a three-color gradient based on a color-map with three entries on lines 8-13: line 11 specifies the lower bound (150) be styled in blue ('#0000FF'), line 12 specifies an intermediate point (200) be styled in yellow ('#FFFF00'), and line 13 specifies the upper bound (250) be styled in red ('#FF0000'). Since our data values run between 70 and 256, some data points are not accounted for in this style. Those values below the lowest entry in the color map (the range from 70 to 149) are styled the same color as the lower bound, in this case blue. Values above the upper bound in the color map (the range from 251 to 256) are styled the same color as the upper bound, in this case red. Alpha channel This example creates an “alpha channel” effect such that higher values are increasingly transparent. Code Download the "Alpha channel" YSLD 698 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.266: Alpha channel title: 'YSLD Cook Book: Alpha channel' feature-styles: - name: name rules: - symbolizers: - raster: opacity: 1 color-map: type: ramp entries: - ['#008000',1,70,''] - ['#008000',0,256,''] 1 2 3 4 5 6 7 8 9 10 11 12 Details An alpha channel is another way of referring to variable transparency. Much like how a gradient maps values to colors, each entry in a color-map can have a value for opacity (with the default being 1.0 or completely opaque). In this example, there is a color-map with two entries: line 11 specifies the lower bound of 70 be colored dark green ('#008000'), while line 13 specifies the upper bound of 256 also be colored dark green but with an opacity value of 0. This means that values of 256 will be rendered at 0% opacity (entirely transparent). Just like the gradient color, the opacity is also linearly interpolated such that a value of 163 (the midpoint between 70 and 256) is rendered at 50% opacity. Discrete colors This example shows a gradient that is not linearly interpolated but instead has values mapped precisely to one of three specific colors. Code Download the "Discrete colors" YSLD 6.5. YSLD Styling 699 GeoServer User Manual, Release 2.15.1 Fig. 6.267: Discrete colors title: 'YSLD Cook Book: Discrete colors' feature-styles: - name: name rules: - symbolizers: - raster: opacity: 1 color-map: type: intervals entries: - ['#008000',1,150,''] - ['#663333',1,256,''] 1 2 3 4 5 6 7 8 9 10 11 12 Details Sometimes color bands in discrete steps are more appropriate than a color gradient. The type: intervals parameter added to the color-map on line 9 sets the display to output discrete colors instead of a gradient. The values in each entry correspond to the upper bound for the color band such that colors are mapped to values less than the value of one entry but greater than or equal to the next lower entry. For example, line 11 colors all values less than 150 to dark green ('#008000') and line 12 colors all values less than 256 but greater than or equal to 150 to dark brown ('#663333'). Many color gradient This example shows a gradient interpolated across eight different colors. Code Download the "Many color gradient" YSLD title: 'YSLD Cook Book: Many color gradient' feature-styles: - name: name 1 2 3 700 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.268: Many color gradient rules: - symbolizers: - raster: opacity: 1 color-map: type: ramp entries: - ['#000000',1,95,''] - ['#0000FF',1,110,''] - ['#00FF00',1,135,''] - ['#FF0000',1,160,''] - ['#FF00FF',1,185,''] - ['#FFFF00',1,210,''] - ['#00FFFF',1,235,''] - ['#FFFFFF',1,256,''] 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Details A color-map can include up to 255 entries. This example has eight entries (lines 11-18): Entry ber 1 2 3 4 5 6 7 8 num- Value Color RGB code 95 110 135 160 185 210 235 256 Black Blue Green Red Purple Yellow Cyan White '#000000' '#0000FF' '#00FF00' '#FF0000' '#FF00FF' '#FFFF00' '#00FFFF' '#FFFFFF' 6.6 MBStyle Styling This module adds support for the MBStyle language. 6.6. MBStyle Styling 701 GeoServer User Manual, Release 2.15.1 MBStyle is a JSON based language which can be converted to SLD, the internal data model that GeoServer’s renderer uses. For details on Mapbox Style syntax see the reference below. MBStyle is not a part of GeoServer by default, but is available as an optional install. 6.6.1 Installing the GeoServer MBStyle extension 1. Download the extension from the nightly GeoServer community module builds. Warning: Make sure to match the version of the extension to the version of the GeoServer instance! 2. Extract the contents of the archive into the WEB-INF/lib directory of the GeoServer installation. 6.6.2 Publishing a GeoServer Layer for use with Mapbox Styles GeoServer can be configured to serve layers as vector tiles which can be used as sources for Mapbox styles rendered by client-side applications such as OpenLayers. 1. Enable CORS in GeoServer. 2. Install the Vector Tiles extension. 3. Follow the Vector tiles tutorial to publish your layers in application/x-protobuf;type=mapbox-vector format (You only need to do the “Publish vector tiles in GeoWebCache” step). Once these steps are complete, you will be able to use your GeoServer layers in any Mapbox-compatible client application that can access your GeoServer. The source syntax to use these GeoServer layers in your MapBox Style is: "": { "type": "vector", "tiles": [ "http://localhost:8080/geoserver/ ,→gwc/service/wmts?REQUEST=GetTile&SERVICE=WMTS &VERSION=1.0.0&LAYER= ,→:&STYLE=&TILEMATRIX=EPSG:900913:{z} &TILEMATRIXSET=EPSG:900913& ,→FORMAT=application/x-protobuf;type=mapbox-vector &TILECOL={x}&TILEROW={y}" ], "minZoom": 0, "maxZoom": 14 } 702 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Note: and should be replaced by the workspace and name of the layer in question. {x}, {y}, and {z} are placeholder values for the tile indices and should be preserved as written. Note: should be replaced by a source name of your choice. It will be used to refer to the source elsewhere in the Mapbox Style. Note: If geoserver is not being served from localhost:8080, update the domain accordingly. 6.6.3 MBStyle reference This section will detail the usage and syntax of the MBStyle language. As MBstyle is heavily modeled on JSON, it may be useful to refer to the JSON-Schema documentation for basic syntax. For an extended reference to these styles check out the Mapbox Style Specifications. Mapbox Styles Module The gs-mbstyle module is an unsupported module that provides a parser/encoder to convert between Mapbox Styles and GeoServer style objects. These docs are under active development, along with the module itself. References: • https://www.mapbox.com/mapbox-gl-style-spec MapBox Types copied from the MapBox Style Specification Color Colors are written as JSON strings in a variety of permitted formats: HTML-style hex values, rgb, rgba, hsl, and hsla. Predefined HTML colors names, like yellow and blue, are also permitted. { "line-color": "line-color": "line-color": "line-color": "line-color": "line-color": "line-color": "#ff0", "#ffff00", "rgb(255, 255, 0)", "rgba(255, 255, 0, 1)", "hsl(100, 50%, 50%)", "hsla(100, 50%, 50%, 1)", "yellow" } 6.6. MBStyle Styling 703 GeoServer User Manual, Release 2.15.1 Especially of note is the support for hsl, which can be easier to reason about than rgb(). Enum One of a fixed list of string values. Use quotes around values. { "text-transform": "uppercase" } String A string is basically just text. In Mapbox styles, you’re going to put it in quotes. Strings can be anything, though pay attention to the case of text-field - it actually will refer to features, which you refer to by putting them in curly braces, as seen in the example below. { "text-field": "{MY_FIELD}" } Boolean Boolean means yes or no, so it accepts the values true or false. { "fill-enabled": true } Number A number value, often an integer or floating point (decimal number). Written without quotes. { "text-size": 24 } Array Arrays are comma-separated lists of one or more numbers in a specific order. For example, they’re used in line dash arrays, in which the numbers specify intervals of line, break, and line again. { "line-dasharray": [2, 4] } Expressions The value for any layout property, paint property, or filter may be specified as an expression. An expression defines a formula for computing the value of the property using the operators described below. The set of expression operators provided by Mapbox GL includes: 704 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 • Mathematical operators for performing arithmetic and other operations on numeric values • Logical operators for manipulating boolean values and making conditional decisions • String operators for manipulating strings • Data operators, providing access to the properties of source features • Camera operators, providing access to the parameters defining the current map view Expressions are represented as JSON arrays. The first element of an expression array is a string naming the expression operator, e.g. "*" or "case". Subsequent elements (if any) are the arguments to the expression. Each argument is either a literal value (a string, number, boolean, or null), or another expression array. [expression_name, argument_0, argument_1, . . . ] Data expressions A data expression is any expression that access feature data – that is, any expression that uses one of the data operators: get, has, id, geometry-type, properties, or feature-state. Data expressions allow a feature’s properties or state to determine its appearance. They can be used to differentiate features within the same layer and to create data visualizations. { "circle-color": [ "rgb", // red is ,→higher when feature.properties.temperature is higher ["get", "temperature"], // green is always zero 0, // blue is ,→higher when feature.properties.temperature is lower ["-", 100, ["get", "temperature"]] ] } This example uses the get operator to obtain the temperature value of each feature. That value is used to compute arguments to the rgb operator, defining a color in terms of its red, green, and blue components. Data expressions are allowed as the value of the filter property, and as values for most paint and layout properties. However, some paint and layout properties do not yet support data expressions. The level of support is indicated by the “data-driven styling” row of the “SDK Support” table for each property. Data expressions with the feature-state operator are allowed only on paint properties. Camera expressions A camera expression is any expression that uses the zoom operator. Such expressions allow the the appearance of a layer to change with 6.6. MBStyle Styling 705 GeoServer User Manual, Release 2.15.1 the map’s zoom level. Camera expressions can be used to create the appearance of depth and to control data density. { "circle-radius": [ "interpolate", ["linear"], ["zoom"], ,→ ,→ // zoom is 5 (or less) -> circle radius will be 1px 5, 1, // zoom is 10 (or greater) -> circle radius will be 5px 10, 5 ] } This example uses the interpolate operator to define a linear relationship between zoom level and circle size using a set of inputoutput pairs. In this case, the expression indicates that the circle radius should be 1 pixel when the zoom level is 5 or below, and 5 pixels when the zoom is 10 or above. In between, the radius will be linearly interpolated between 1 and 5 pixels Camera expressions are allowed anywhere an expression may be used. However, when a camera expression used as the value of a layout or paint property, it must be in one of the following forms: [ "interpolate", interpolation, ["zoom"], ... ] Or: [ "step", ["zoom"], ... ] Or: [ "let", ... variable bindings..., [ "interpolate", interpolation, ["zoom"], ... ] ] Or: [ "let", ... variable bindings..., [ "step", ["zoom"], ... ] ] That is, in layout or paint properties, ["zoom"] may appear only as the input to an outer interpolate or step expression, or such an expression within a let expression. There is an important difference between layout and paint properties in the timing of camera expression evaluation. Paint property camera expressions are re-evaluated whenever the zoom level changes, even fractionally. For example, a paint property camera expression will be re-evaluated continuously as the map moves between zoom levels 4.1 and 4.6. On the other hand, a layout property 706 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 camera expression is evaluated only at integer zoom levels. It will not be re-evaluated as the zoom changes from 4.1 to 4.6 – only if it goes above 5 or below 4. Composition A single expression may use a mix of data operators, camera operators, and other operators. Such composite expressions allows a layer’s appearance to be determined by a combination of the zoom level and individual feature properties. { "circle-radius": [ "interpolate", ["linear"], ["zoom"], // when zoom is 0, set each feature's ,→circle radius to the value of its "rating" property 0, ["get", "rating"], // when zoom is 10, set each feature's circle radius to four times the value of its "rating" property 10, ["*", 4, ["get", "rating"]] ] ,→ ,→ } An expression that uses both data and camera operators is considered both a data expression and a camera expression, and must adhere to the restrictions described above for both. Type system The input arguments to expressions, and their result values, use the same set of types as the rest of the style specification: boolean, string, number, color, and arrays of these types. Furthermore, expressions are type safe: each use of an expression has a known result type and required argument types, and the SDKs verify that the result type of an expression is appropriate for the context in which it is used. For example, the result type of an expression in the filter property must be boolean, and the arguments to the + operator must be numbers. When working with feature data, the type of a feature property value is typically not known ahead of time by the SDK. In order to preserve type safety, when evaluating a data expression, the SDK will check that the property value is appropriate for the context. For example, if you use the expression ["get", "feature-color"] for the circle-color property, the SDK will verify that the feature-color value of each feature is a string identifying a valid color. If this check fails, an error will be indicated in an SDK-specific way (typically a log message), and the default value for the property will be used instead. In most cases, this verification will occur automatically wherever it is needed. However, in certain situations, the SDK may be unable to automatically determine the expected result type of a data expression from surrounding context. For example, it is not clear whether the expression ["<", ["get", "a"], ["get", "b"]] is attempting to compare strings or numbers. In situations like this, you can use one of the type assertion expression operators to in- 6.6. MBStyle Styling 707 GeoServer User Manual, Release 2.15.1 dicate the expected type of a data expression: ["<", ["number", ["get", "a"]], ["number", ["get", "b"]]]. A type assertion checks that the feature data actually matches the expected type of the data expression. If this check fails, it produces an error and causes the whole expression to fall back to the default value for the property being defined. The assertion operators are array, boolean, number, and string. Expressions perform only one kind of implicit type conversion: a data expression used in a context where a color is expected will convert a string representation of a color to a color value. In all other cases, if you want to convert between types, you must use one of the type conversion expression operators: to-boolean, to-number, to-string, or to-color. For example, if you have a feature property that stores numeric values in string format, and you want to use those values as numbers rather than strings, you can use an expression such as ["to-number", ["get", "property-name"]]. Function Note: As of GeoTools 20.0 / MapBox 0.41.0, functions are deprecated. Use expressions instead. The value for any layout or paint property may be specified as a function. Functions allow you to make the appearance of a map feature change with the current zoom level and/or the feature’s properties. stops Required (except for identity functions) array. Functions are defined in terms of input and output values. A set of one input value and one output value is known as a “stop.” property Optional string If specified, the function will take the specified feature property as an input. See Zoom Functions and Property Functions for more information. base Optional number. Default is 1. The exponential base of the interpolation curve. It controls the rate at which the function output increases. Higher values make the output increase more towards the high end of the range. With values close to 1 the output increases linearly. type Optional enum. One of identity, exponential, interval, categorical identity functions return their input as their output. 708 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 exponential functions generate an output by interpolating between stops just less than and just greater than the function input. The domain must be numeric. interval functions return the output value of the stop just less than the function input. The domain must be numeric. categorical functions return the output value of the stop equal to the function input. default A value to serve as a fallback function result when a value isn’t otherwise available. It is used in the following circumstances: • In categorical functions, when the feature value does not match any of the stop domain values. • In property and zoom-and-property functions, when a feature does not contain a value for the specified property. • In identity functions, when the feature value is not valid for the style property (for example, if the function is being used for a circle-color property but the feature property value is not a string or not a valid color). • In interval or exponential property and zoom-and-property functions, when the feature value is not numeric. If no default is provided, the style property’s default is used in these circumstances. colorSpace Optional enum. One of rgb, lab, hcl The color space in which colors interpolated. Interpolating colors in perceptual color spaces like LAB and HCL tend to produce color ramps that look more consistent and produce colors that can be differentiated more easily than those interpolated in RGB space. rgb Use the RGB color space to interpolate color values lab Use the LAB color space to interpolate color values. hcl Use the HCL color space to interpolate color values, interpolating the Hue, Chroma, and Luminance channels individually. Zoom Functions allow the appearance of a map feature to change with map’s zoom level. Zoom functions can be used to create the illusion of depth and control data density. Each stop is an array with two elements: the first is a zoom level and the second is a function output value. 6.6. MBStyle Styling 709 GeoServer User Manual, Release 2.15.1 { "circle-radius": { "stops": [ [5, 1], [10, 2] ] } } The rendered values of color, number, and array properties are intepolated between stops. Enum, boolean, and string property values cannot be intepolated, so their rendered values only change at the specified stops. There is an important difference between the way that zoom functions render for layout and paint properties. Paint properties are continuously re-evaluated whenever the zoom level changes, even fractionally. The rendered value of a paint property will change, for example, as the map moves between zoom levels 4.1 and 4.6. Layout properties, on the other hand, are evaluated only once for each integer zoom level. To continue the prior example: the rendering of a layout property will not change between zoom levels 4.1 and 4.6, no matter what stops are specified; but at zoom level 5, the function will be re-evaluated according to the function, and the property’s rendered value will change. (You can include fractional zoom levels in a layout property zoom function, and it will affect the generated values; but, still, the rendering will only change at integer zoom levels.) Property functions allow the appearance of a map feature to change with its properties. Property functions can be used to visually differentate types of features within the same layer or create data visualizations. Each stop is an array with two elements, the first is a property input value and the second is a function output value. Note that support for property functions is not available across all properties and platforms at this time. { "circle-color": { "property": "temperature", "stops": [ [0, "blue"], [100, "red"] ] } } Zoom-and-property functions allow the appearance of a map feature to change with both its properties and zoom. Each stop is an array with two elements, the first is an object with a property input value and a zoom, and the second is a function output value. Note that support for property functions is not yet complete. { "circle-radius": { "property": "rating", 710 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 "stops": [ [{"zoom": [{"zoom": [{"zoom": [{"zoom": ] 0, "value": 0}, 0], 0, "value": 5}, 5], 20, "value": 0}, 0], 20, "value": 5}, 20] } } Filter A filter selects specific features from a layer. A filter is an array of one of the following forms: Existential Filters [“has”, key] feature[key] exists [“!has”, key] feature[key] does not exist Comparison Filters [“==”, key, value] equality: feature[key] = value [“!=”, key, value] inequality: feature[key] value [“>”, key, value] greater than: feature[key] > value [“>=”, key, value] greater than or equal: feature[key] value [“<”, key, value] less than: feature[key] < value [“<=”, key, value] less than or equal: feature[key] value Set Membership Filters [“in”, key, v0, . . . , vn] set inclusion: feature[key] {v0, . . . , vn} [“!in”, key, v0, . . . , vn] set exclusion: feature[key] {v0, . . . , vn} Combining Filters [“all”, f0, . . . , fn] logical AND: f0 . . . fn [“any”, f0, . . . , fn] logical OR: f0 . . . fn [“none”, f0, . . . , fn] logical NOR: ¬f0 . . . ¬fn A key must be a string that identifies a feature property, or one of the following special keys: • “$type”: the feature type. This key may be used with the “==”, “!=”, “in”, and “!in” operators. Possible values are “Point”, “LineString”, and “Polygon”. • “$id”: the feature identifier. This key may be used with the “==”, “!=”, “has”, “!has”, “in”, and “!in” operators. A value (and v0, . . . , vn for set operators) must be a string, number, or boolean to compare the property value against. Set membership filters are a compact and efficient way to test whether a field matches any of multiple values. 6.6. MBStyle Styling 711 GeoServer User Manual, Release 2.15.1 The comparison and set membership filters implement strictlytyped comparisons; for example, all of the following evaluate to false: 0 < “1”, 2 == “2”, “true” in [true, false]. The “all”, “any”, and “none” filter operators are used to create compound filters. The values f0, . . . , fn must be filter expressions themselves. ["==", "$type", "LineString"] This filter requires that the class property of each feature is equal to either “street_major”, “street_minor”, or “street_limited”. ["in", "class ,→", "street_major", "street_minor", "street_limited"] The combining filter “all” takes the three other filters that follow it and requires all of them to be true for a feature to be included: a feature must have a class equal to “street_limited”, its admin_level must be greater than or equal to 3, and its type cannot be Polygon. You could change the combining filter to “any” to allow features matching any of those criteria to be included - features that are Polygons, but have a different class value, and so on. [ "all", ["==", "class", "street_limited"], [">=", "admin_level", 3], ["!in", "$type", "Polygon"] ] MapBox Style Grammar JSON does not allow for comments within the data therefore comments will be noted through the placement of the comment between open < and close > angle brackets. All properties are optional unless otherwise noted as Requried Root Properties { "version": 8, "name": "Mapbox Streets", "sprite": "mapbox://sprites/mapbox/streets-v8", "glyphs ,→": "mapbox://fonts/mapbox/{fontstack}/{range}.pbf", "sources": {...}, "layers": [...] } layers Layers are drawn in the order they appear in the layer array. Layers have two additional properties that determine how data is rendered: layout and paint Background Layer definition 712 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 { "layers" : [ { "id": "backgroundcolor", "type": "background", "source": "test-source", "source-layer": "test-source-layer", "layout": { "visibility": "visible" }, "paint": { "background-opacity": 0.45, "background-color": "#00FF00" } } ] } background-color is disabled by the presence of background-pattern Fill Layer Definition { "layers": [ { "id": "testid", "type": "fill", "source": "geoserver-states", "source-layer": "states", "layout": { "visibility": "visible" }, "paint": { "fill-antialias": "true", "fill-opacity": 0.84, "fill-color": "#FF595E", "fill-outline-color":"#1982C4", "fill-translate": [20,20], "fill-translate-anchor": "map", "fill-pattern": } } ] } Line Layer Definition { "layers": [ { "id": "test-id", "type": "line", "source": "test-source", "source-layer": "test-source-layer", "layout": { "line-cap": "square", "line-join": "round", "line-mitre,→limit": 2, 6.6. MBStyle Styling 713 GeoServer User Manual, Release 2.15.1 "line-roundlimit": 1.05, "visibility": "visible" }, "paint": { "line-color": "#0099ff", "line-opacity": 0.5, "line-translate": [3,3], "line-translate-anchor": "viewport", "line-width": 10, "line-gap-width": 8, "line-offset": 4, "line-blur": 2, "line-dasharray": [50, 50], "line-pattern": } } ], ,→ } Symbol Layer Definition { "layers": [ { "id": "test-id", "type": "symbol", "source": "test-source", "source-layer": "test-source-layer", "layout": { "symbol-placement ,→": "", "symbol-spacing": "", ,→ "symbol-avoid-edges": "", "icon-allow-overlap": "", "icon,→ignore-placement": "", "icon-optional": "", "icon-rotation-alignment": "", "icon-size": "", "icon-rotation,→alignment": "", "icon-text-fit-padding ,→": "", "icon-image": "", "icon,→rotate": "", "icon-padding ,→": "", ,→ ,→ ,→ 714 "icon-keep-upright": "", "icon-offset ,→": "", "text-pitch-alignment": "", "text-rotation-alignment": "", "text-field": "", "text,→font": "", "text-size": "", "text-max-width": "", "text-line-height": "", "text-letter-spacing": "", "text-justify": "", "text-anchor": "", ,→ "text-max,→angle": "", "text,→rotate": "", "text,→padding": "", "text-keep-upright": "", "text-transform": "", "text-offset": "", "text-allow-overlap": ,→"", "text-ignore-placement": ,→"", "text-optional": "", "visibility": "visible" }, "paint": { "icon-opacity": "", "icon-color": ,→"", "icon-halo-color": "", "icon-halo-width": "", "icon-halo-blur": "", "icon-translate": "", ,→ ,→ 6.6. MBStyle Styling 715 GeoServer User Manual, Release 2.15.1 "icon-translate-anchor": "", "text-opacity ,→": "", "text-halo-color": "", "text-halo-width": "", "text-halo-blur": "", "text-translate": "", ,→ ,→ "text-translate-anchor": "" } } ], ,→ ,→ } Raster Layer Definition { "layers": [ { "id": "test-id", "type": "raster", "source": "test-source", "source-layer": "test-source-layer", "layout": { "visibility": "visible" }, "paint": { "raster-opacity": "", "raster-hue,→rotate": "", ,→ "raster-brightness-min": "", ,→ "raster-brightness-max": "", "raster-saturation": "", "raster-contrast": "", "raster-fade-duration": ,→"" } } ], } ,→ Circle Layer definition { "layers": [ { "id": "test-id", "type": "raster", 716 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 "source": "test-source", "source-layer": "test-source-layer", "layout": { "visibility": "visible" }, "paint": { "circle,→radius": "", "circle-color": "", "circle-blur": "", "circle-opacity": "", "circle-translate ,→": "", "circle-translate-anchor": "", "circle-pitch,→scale": "", "circle-stroke,→width": "", "circle,→stroke-color": "", ,→ "circle-stroke-opacity": "", } } ], ,→ } Fill-Extrusion Layer Definition { { "layers": [ { "id": "test-id", "type": "fill-extrusion", "source": "test-source", "source-layer": "test-source-layer", "layout": { "visibility": "visible" }, "paint": { "fill-extrusion-opacity": "", "fill-extrusion-color": "", "fill-extrusion-translate ,→": "", "fill-extrusion,→translate-anchor": "", "fill-extrusion-pattern": "", "fill-extrusion,→height": "", ,→ ,→ ,→ 6.6. MBStyle Styling "fill-extrusion-base": "" 717 GeoServer User Manual, Release 2.15.1 } } ], } 6.6.4 Mapbox Style Specification A Mapbox style is a document that defines the visual appearance of a map: what data to draw, the order to draw it in, and how to style the data when drawing it. A style document is a JSON object with specific root level and nested properties. This specification defines and describes these properties. The intended audience of this quick reference includes: • Advanced designers and cartographers who want to write styles by hand • GeoTools developers using the mbstyle module • Authors of software that generates or processes Mapbox styles. • Feature support is provided for the Mapbox GL JS, the Open Layers Mapbox Style utility and the GeoTools mbstyle module. • Where appropriate examples have been changed to reference GeoWebCache. Note: The Mapbox Style Specification is generated from the BSD Mapbox GL JS github repository, reproduced here with details on this GeoTools implementation. Root Properties Root level properties of a Mapbox style specify the map’s layers, tile sources and other resources, and default values for the initial camera position when not specified elsewhere. { "version": 8, "name": "Mapbox Streets", "sprite": "sprites/streets-v8", "glyphs": "{fontstack}/{range}.pbf", "sources": {...}, "layers": [...] } version Required Enum. Style specification version number. Must be 8. 718 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 "version": 8 name Optional String. A human-readable name for the style. "name": "Bright" metadata Optional Arbitrary properties useful to track with the stylesheet, but do not influence rendering. Properties should be prefixed to avoid collisions. Note: unsupported. center Optional Array. Default map center in longitude and latitude. The style center will be used only if the map has not been positioned by other means (e.g. map options or user interaction). "center": [ -73.9749, 40.7736 ] Note: unsupported zoom Optional Number. Default zoom level. The style zoom will be used only if the map has not been positioned by other means (e.g. map options or user interaction). "zoom": 12.5 6.6. MBStyle Styling 719 GeoServer User Manual, Release 2.15.1 bearing Optional Number. Units in degrees. Defaults to 0. Default bearing, in degrees clockwise from true north. The style bearing will be used only if the map has not been positioned by other means (e.g. map options or user interaction). "bearing": 29 Note: unsupported pitch Optional Number. Units in degrees. Defaults to 0. Default pitch, in degrees. Zero is perpendicular to the surface, for a look straight down at the map, while a greater value like 60 looks ahead towards the horizon. The style pitch will be used only if the map has not been positioned by other means (e.g. map options or user interaction). "pitch": 50 light The global light source. "light": { "anchor": "viewport", "color": "white", "intensity": 0.4 } sources Required Sources. Data source specifications. "sources": { "mapbox-streets": { "type": "vector", "tiles": [ "http://localhost:8080/ ,→geoserver/gwc/service/wmts?REQUEST=GetTile &SERVICE=WMTS& ,→VERSION=1.0.0&LAYER=mapbox:streets&STYLE= &TILEMATRIX=EPSG:900913:{z}&TILEMATRIXSET=EPSG:900913 ,→ ,→ 720 &FORMAT=application/x-protobuf;type=mapbox-vector Chapter 6. Styling GeoServer User Manual, Release 2.15.1 &TILECOL={x}&TILEROW={y}" ], "minZoom": 0, "maxZoom": 14 } } sprite Optional String. A base URL for retrieving the sprite image and metadata. The extensions .png, .json and scale factor @2x.png will be automatically appended. This property is required if any layer uses the background-pattern, fill-pattern, line-pattern, fill-extrusion-pattern, or icon-image properties. "sprite" : "/geoserver/styles/mark" glyphs Optional String. A URL template for loading signed-distance-field glyph sets in PBF format. The URL must include {fontstack} and {range} tokens. This property is required if any layer uses the text-field layout property. "glyphs": "{fontstack}/{range}.pbf" transition Required Transition. A global transition definition to use as a default across properties. "transition": { "duration": 300, "delay": 0 } layers Required Array. Layers will be drawn in the order of this array. "layers": [ { "id": "water", "source": "sf:roads", 6.6. MBStyle Styling 721 GeoServer User Manual, Release 2.15.1 "source-layer": "water", "type": "fill", "paint": { "fill-color": "#00ffff" } } ] Light A style’s light property provides global light source for that style. "light": { "anchor": "viewport", "color": "white", "intensity": 0.4 } anchor Optional Enum. One of map, viewport. Defaults to viewport. Whether extruded geometries are lit relative to the map or viewport. map The position of the light source is aligned to the rotation of the map. viewport The position of the light source is aligned to the rotation of the viewport. "anchor": "map" Support basic functionality Mapbox >= 0.27.0 GeoTools Not yet supported OpenLayers Not yet supported position Optional Array. Defaults to 1.15,210,30. Position of the light source relative to lit (extruded) geometries, in [r radial coordinate, a azimuthal angle, p polar angle] where r indicates the distance from the center of the base of an object to its light, a indicates the position of the light relative to 0° (0° when light. anchor is set to viewport corresponds to the top of the viewport, or 0° when light.anchor is set to map corresponds to due north, and degrees proceed clockwise), and p indicates the height of the light (from 0°, directly above, to 180°, directly below). "position": [ 1.5, 90, 80 ] 722 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Support basic functionality Mapbox >= 0.27.0 GeoTools Not yet supported OpenLayers Not yet supported color Optional Color. Defaults to #ffffff. Color tint for lighting extruded geometries. Support basic functionality Mapbox >= 0.27.0 GeoTools Not yet supported OpenLayers Not yet supported intensity Optional Number. Defaults to 0.5. Intensity of lighting (on a scale from 0 to 1). Higher numbers will present as more extreme contrast. Support basic functionality Mapbox >= 0.27.0 GeoTools Not yet supported OpenLayers Not yet supported Sources Sources supply data to be shown on the map. The type of source is specified by the "type" property, and must be one of vector, raster, geojson, image, video, canvas. Adding a source won’t immediately make data appear on the map because sources don’t contain styling details like color or width. Layers refer to a source and give it a visual representation. This makes it possible to style the same source in different ways, like differentiating between types of roads in a highways layer. Tiled sources (vector and raster) must specify their details in terms of the TileJSON specification. This can be done in several ways: • By supplying TileJSON properties such as "tiles", "minzoom", and "maxzoom" directly in the source: "mapbox-streets": { "type": "vector", "tiles": [ "http://a.example.com/tiles/{z}/{x}/{y}.pbf", "http://b.example.com/tiles/{z}/{x}/{y}.pbf" ], "maxzoom": 14 } 6.6. MBStyle Styling 723 GeoServer User Manual, Release 2.15.1 • By providing a "url" to a TileJSON resource: "mapbox-streets": { "type": "vector", "url": "http://api.example.com/tilejson.json" } • By providing a url to a WMS server that supports EPSG:3857 (or EPSG:900913) as a source of tiled data. The server url should contain a "{bbox-epsg-3857}" replacement token to supply the bbox parameter. "wms-imagery": { "type": "raster", "tiles": [ 'http:// ,→a.example.com/wms?bbox={bbox-epsg-3857}&format=image/ ,→png&service=WMS&version=1.1.1&request=GetMap& ,→srs=EPSG:3857&width=256&height=256&layers=example' ], "tileSize": 256 } vector A vector tile source. Tiles must be in Mapbox Vector Tile format. All geometric coordinates in vector tiles must be between -1 * extent and (extent * 2) - 1 inclusive. All layers that use a vector source must specify a "source-layer" value. For vector tiles hosted by Mapbox, the "url" value should be of the form mapbox://mapid. "mapbox-streets": { "type": "vector", "tiles": [ "http://localhost:8080/geoserver/ ,→gwc/service/wmts?REQUEST=GetTile&SERVICE=WMTS &VERSION=1.0.0&LAYER=mapbox:streets& ,→STYLE=&TILEMATRIX=EPSG:900913:{z} &TILEMATRIXSET=EPSG:900913& ,→FORMAT=application/x-protobuf;type=mapbox-vector &TILECOL={x}&TILEROW={y}" ], "minZoom": 0, "maxZoom": 14 } url Optional String. A URL to a TileJSON resource. Supported protocols are http:, https:, and mapbox://. 724 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 tiles Optional Array. An array of one or more tile source URLs, as in the TileJSON spec. minzoom Optional Number. Defaults to 0. Minimum zoom level for which tiles are available, as in the TileJSON spec. maxzoom Optional Number. Defaults to 22. Maximum zoom level for which tiles are available, as in the TileJSON spec. Data from tiles at the maxzoom are used when displaying the map at higher zoom levels. Support basic functionality Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers >= 2.4.0 raster A raster tile source. For raster tiles hosted by Mapbox, the "url" value should be of the form mapbox://mapid. "mapbox-satellite": { "type": "raster", "tiles": [ "http://localhost:8080/geoserver/ ,→gwc/service/wmts?REQUEST=GetTile&SERVICE=WMTS &VERSION=1.0.0&LAYER=mapbox:satellite& ,→STYLE=&TILEMATRIX=EPSG:900913:{z} &TILEMATRIXSET=EPSG:900913& ,→FORMAT=image/png&TILECOL={x}&TILEROW={y}" ], "minzoom": 0, "maxzoom": 14 } url Optional String. A URL to a TileJSON resource. Supported protocols are http:, https:, and mapbox://. 6.6. MBStyle Styling 725 GeoServer User Manual, Release 2.15.1 tiles Optional Array. An array of one or more tile source URLs, as in the TileJSON spec. minzoom Optional Number. Defaults to 0. Minimum zoom level for which tiles are available, as in the TileJSON spec. maxzoom Optional Number. Defaults to 22. Maximum zoom level for which tiles are available, as in the TileJSON spec. Data from tiles at the maxzoom are used when displaying the map at higher zoom levels. tileSize Optional Number. Defaults to 512. The minimum visual size to display tiles for this layer. Only configurable for raster layers. Support basic functionality Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers >= 2.4.0 geojson A GeoJSON source. Data must be provided via a "data" property, whose value can be a URL or inline GeoJSON. "geojson-marker": { "type": "geojson", "data": { "type": "Feature", "geometry": { "type": "Point", "coordinates": [-77.0323, 38.9131] }, "properties": { "title": "Mapbox DC", "marker-symbol": "monument" } } } 726 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 This example of a GeoJSON source refers to an external GeoJSON document via its URL. The GeoJSON document must be on the same domain or accessible using CORS. "geojson-lines": { "type": "geojson", "data": "./lines.geojson" } data Optional A URL to a GeoJSON file, or inline GeoJSON. maxzoom Optional Number. Defaults to 18. Maximum zoom level at which to create vector tiles (higher means greater detail at high zoom levels). buffer Optional Number. Defaults to 128. Size of the tile buffer on each side. A value of 0 produces no buffer. A value of 512 produces a buffer as wide as the tile itself. Larger values produce fewer rendering artifacts near tile edges and slower performance. tolerance Optional Number. Defaults to 0.375. Douglas-Peucker simplification tolerance (higher means simpler geometries and faster performance). cluster Optional Boolean. Defaults to false. If the data is a collection of point features, setting this to true clusters the points by radius into groups. clusterRadius Optional Number. Defaults to 50. Radius of each cluster if clustering is enabled. A value of 512 indicates a radius equal to the width of a tile. 6.6. MBStyle Styling 727 GeoServer User Manual, Release 2.15.1 clusterMaxZoom Optional Number. Max zoom on which to cluster points if clustering is enabled. Defaults to one zoom less than maxzoom (so that last zoom features are not clustered). Support basic functionality clustering Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers >= 2.4.0 >= 0.14.0 Not yet supported Not yet supported image An image source. The "url" value contains the image location. The "coordinates" array contains [longitude, latitude] pairs for the image corners listed in clockwise order: top left, top right, bottom right, bottom left. "image": { "type": "image", "url": "/mapbox-gl-js/assets/radar.gif", "coordinates": [ [-80.425, 46.437], [-71.516, 46.437], [-71.516, 37.936], [-80.425, 37.936] ] } url Required String. URL that points to an image. coordinates Required Array. Corners of image specified in longitude, latitude pairs. Support basic functionality 728 Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Chapter 6. Styling GeoServer User Manual, Release 2.15.1 video A video source. The "urls" value is an array. For each URL in the array, a video element source will be created, in order to support same media in multiple formats supported by different browsers. The "coordinates" array contains [longitude, latitude] pairs for the video corners listed in clockwise order: top left, top right, bottom right, bottom left. "video": { "type": "video", "urls": [ "https://www.mapbox.com/drone/video/drone.mp4", "https://www.mapbox.com/drone/video/drone.webm" ], "coordinates": [ [-122.51596391201019, 37.56238816766053], [-122.51467645168304, 37.56410183312965], [-122.51309394836426, 37.563391708549425], [-122.51423120498657, 37.56161849366671] ] } urls Required Array. URLs to video content in order of preferred format. coordinates Required Array. Corners of video specified in longitude, latitude pairs. Support basic functionality Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported canvas A canvas source. The "canvas" value is the ID of the canvas element in the document. The "coordinates" array contains [longitude, latitude] pairs for the video corners listed in clockwise order: top left, top right, bottom right, bottom left. If an HTML document contains a canvas such as this: 6.6. MBStyle Styling 729 GeoServer User Manual, Release 2.15.1 the corresponding canvas source would be specified as follows: "canvas": { "type": "canvas", "canvas": "mycanvas", "coordinates": [ [-122.51596391201019, [-122.51467645168304, [-122.51309394836426, [-122.51423120498657, ] } 37.56238816766053], 37.56410183312965], 37.563391708549425], 37.56161849366671] coordinates Required Array. Corners of canvas specified in longitude, latitude pairs. animate Whether the canvas source is animated. If the canvas is static, animate should be set to false to improve performance. canvas Required String. HTML ID of the canvas from which to read pixels. Support basic functionality Mapbox >= 0.32.0 GeoTools Not yet supported OpenLayers Not yet yupported Sprite A style’s sprite property supplies a URL template for loading small images to use in rendering background-pattern, fill-pattern, line-pattern, and icon-image style properties. "sprite" : "/geoserver/styles/mark" A valid sprite source must supply two types of files: • An index file, which is a JSON document containing a description of each image contained in the sprite. The content of this file must be a JSON object whose keys form identifiers to be used as the values of the above style properties, and whose values are objects describing the dimensions (width and height properties) and pixel ratio (pixelRatio) of the image and its location within the sprite (x and 730 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 y). For example, a sprite containing a single image might have the following index file contents: { "poi": { "width": 32, "height": 32, "x": 0, "y": 0, "pixelRatio": 1 } } Then the style could refer to this sprite image by creating a symbol layer with the layout property "icon-image": "poi", or with the tokenized value "icon-image": "{icon}" and vector tile features with a icon property with the value poi. • Image files, which are PNG images containing the sprite data. Mapbox SDKs will use the value of the sprite property in the style to generate the URLs for loading both files. First, for both file types, it will append @2x to the URL on high-DPI devices. Second, it will append a file extension: .json for the index file, and .png for the image file. For example, if you specified "sprite": "https:/ /example.com/sprite", renderers would load https:// example.com/sprite.json and https://example.com/ sprite.png, or https://example.com/sprite@2x.json and https://example.com/sprite@2x.png. If you are using Mapbox Studio, you will use prebuilt sprites provided by Mapbox, or you can upload custom SVG images to build your own sprite. In either case, the sprite will be built automatically and supplied by Mapbox APIs. If you want to build a sprite by hand and self-host the files, you can use spritezero-cli, a command line utility that builds Mapbox GL compatible sprite PNGs and index files from a directory of SVGs. Glyphs A style’s glyphs property provides a URL template for loading signed-distance-field glyph sets in PBF format. "glyphs": "{fontstack}/{range}.pbf" This URL template should include two tokens: • {fontstack} When requesting glyphs, this token is replaced with a comma separated list of fonts from a font stack specified in the `text-font <#layout-symbol-text-font>‘__ property of a symbol layer. • {range} When requesting glyphs, this token is replaced with a range of 256 Unicode code points. For example, to load glyphs for the Unicode Basic Latin and Basic Latin-1 Supplement blocks, the range would be 0-255. The actual ranges that are loaded are determined at runtime based on what text needs to be displayed. 6.6. MBStyle Styling 731 GeoServer User Manual, Release 2.15.1 Transition A style’s transition property provides global transition defaults for that style. "transition": { "duration": 300, "delay": 0 } duration Optional Number. Units in milliseconds. Defaults to 300. Time allotted for transitions to complete. delay Optional Number. Units in milliseconds. Defaults to 0. Length of time before a transition begins. Layers A style’s layers property lists all of the layers available in that style. The type of layer is specified by the "type" property, and must be one of background, fill, line, symbol, raster, circle, fillextrusion. Except for layers of the background type, each layer needs to refer to a source. Layers take the data that they get from a source, optionally filter features, and then define how those features are styled. "layers": [ { "id": "water", "source": "sf:roads", "source-layer": "water", "type": "fill", "paint": { "fill-color": "#00ffff" } } ] Layer Properties id Required String. Unique layer name. 732 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 type Optional Enum. One of fill, line, symbol, circle, fill-extrusion, raster, background. Rendering type of this layer. fill A filled polygon with an optional stroked border. line A stroked line. symbol An icon or a text label. circle A filled circle. fill-extrusion An extruded (3D) polygon. raster Raster map textures such as satellite imagery. background The background color or pattern of the map. metadata Optional Arbitrary properties useful to track with the layer, but do not influence rendering. Properties should be prefixed to avoid collisions, like ‘mapbox:’. source Optional String. Name of a source description to be used for this layer. source-layer Optional String. Layer to use from a vector tile source. Required if the source supports multiple layers. minzoom Optional Number. The minimum zoom level on which the layer gets parsed and appears on. maxzoom Optional Number. The maximum zoom level on which the layer gets parsed and appears on. 6.6. MBStyle Styling 733 GeoServer User Manual, Release 2.15.1 filter Optional Expression. A expression specifying conditions on source features. Only features that match the filter are displayed. layout layout properties for the layer paint Optional paint properties for the layer Layers have two sub-properties that determine how data from that layer is rendered: layout and paint properties. Layout properties appear in the layer’s "layout" object. They are applied early in the rendering process and define how data for that layer is passed to the GPU. For efficiency, a layer can share layout properties with another layer via the "ref" layer property, and should do so where possible. This will decrease processing time and allow the two layers will share GPU memory and other resources associated with the layer. Paint properties are applied later in the rendering process. A layer that shares layout properties with another layer can have independent paint properties. Paint properties appear in the layer’s "paint" object. background Layout Properties visibility Optional Enum. One of visible, none, Defaults to visible. Whether this layer is displayed. visible The layer is shown. none The layer is not shown. Support basic functionality 734 Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers >= 2.4.0 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Paint Properties background-color Optional Color. Defaults to #000000. Disabled by background-pattern. The color with which the background will be drawn. Support basic functionality Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers >= 2.4.0 background-pattern Optional String. Name of image in sprite to use for drawing an image background. For seamless patterns, image width and height must be a factor of two (2, 4, 8, . . . , 512). Support basic functionality Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported background-opacity Optional Number. Defaults to 1. The opacity at which the background will be drawn. Support basic functionality Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers >= 2.4.0 fill Layout Properties visibility Optional Enum. One of visible, none. Defaults to visible. Whether this layer is displayed. visible The layer is shown. none The layer is not shown. Support basic functionality Mapbox >= 0.10.0 6.6. MBStyle Styling GeoTools >= 17.1 OpenLayers >= 2.4.0 735 GeoServer User Manual, Release 2.15.1 Paint Properties fill-antialias Optional Boolean. Defaults to true. Whether or not the fill should be antialiased. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported fill-opacity Optional Number. Defaults to 1. The opacity of the entire fill layer. In contrast to the fill-color, this value will also affect the 1px stroke around the fill, if the stroke is used. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.21.0 >= 17.1 >= 2.4.0 fill-color Optional Color. Defaults to #000000. Disabled by fill-pattern. The color of the filled part of this layer. This color can be specified as rgba with an alpha component and the color’s opacity will not affect the opacity of the 1px stroke, if it is used. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.19.0 >= 17.1 >= 2.4.0 fill-outline-color Optional Color. Disabled by fill-pattern. Requires fill-antialias = true. The outline color of the fill. Matches the value of fill-color if unspecified. 736 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.19.0 >= 17.1 >= 2.4.0 fill-translate Optional Array. Units in pixels. Defaults to 0.0. The geometry’s offset. Values are [x, y] where negatives indicate left and up, respectively. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported fill-translate-anchor Optional Enum. One of map, viewport. Defaults to map. Requires fill-translate. Controls the translation reference point. map The fill is translated relative to the map. viewport The fill is translated relative to the viewport. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported fill-pattern Optional String. Name of image in sprite to use for drawing image fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, . . . , 512). Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers Not yet supported Not yet supported >= 17.1 Not yet supported 6.6. MBStyle Styling 737 GeoServer User Manual, Release 2.15.1 line Layout Properties line-cap Optional Enum. One of butt, round, square. Defaults to butt. The display of line endings. butt A cap with a squared-off end which is drawn to the exact endpoint of the line. round A cap with a rounded end which is drawn beyond the endpoint of the line at a radius of one-half of the line’s width and centered on the endpoint of the line. square A cap with a squared-off end which is drawn beyond the endpoint of the line at a distance of one-half of the line’s width. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 Not yet supported >= 17.1 >= 2.4.0 line-join Optional Enum. One of bevel, round, miter. Defaults to miter. The display of lines when joining. bevel A join with a squared-off end which is drawn beyond the endpoint of the line at a distance of one-half of the line’s width. round A join with a rounded end which is drawn beyond the endpoint of the line at a radius of one-half of the line’s width and centered on the endpoint of the line. miter A join with a sharp, angled corner which is drawn with the outer sides beyond the endpoint of the path until they meet. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 Not yet supported >= 17.1 >= 2.4.0 line-miter-limit Optional Number. Defaults to 2. Requires line-join = miter. Used to automatically convert miter joins to bevel joins for sharp angles. 738 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers >= 2.4.0 Not yet supported Not yet supported >= 2.4.0 line-round-limit Optional Number. Defaults to 1.05. Requires line-join = round. Used to automatically convert round joins to miter joins for shallow angles. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported visibility Optional Enum. One of visible, none. Defaults to visible. Whether this layer is displayed. visible The layer is shown. none The layer is not shown. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 Not yet supported >= 17.1 >= 2.4.0 Paint Properties line-opacity Optional Number. Defaults to 1. The opacity at which the line will be drawn. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.29.0 >= 17.1 >= 2.4.0 6.6. MBStyle Styling 739 GeoServer User Manual, Release 2.15.1 line-color Optional Color. Defaults to #000000. Disabled by line-pattern. The color with which the line will be drawn. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.23.0 >= 17.1 >= 2.4.0 line-translate Optional Array. Units in pixels. Defaults to 0.0. The geometry’s offset. Values are [x, y] where negatives indicate left and up, respectively. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported line-translate-anchor Optional Enum. One of map, viewport. Defaults to map. Requires line-translate. Controls the translation reference point. map The line is translated relative to the map. viewport The line is translated relative to the viewport. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported line-width Optional Number. Units in pixels. Defaults to 1. Stroke thickness. 740 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 Not yet supported >= 17.1 >= 2.4.0 line-gap-width Optional Number. Units in pixels. Defaults to 0. Draws a line casing outside of a line’s actual path. Value indicates the width of the inner gap. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported >= 0.29.0 Not yet supported Not yet supported line-offset Optional Number. Units in pixels. Defaults to 0. The line’s offset. For linear features, a positive value offsets the line to the right, relative to the direction of the line, and a negative value to the left. For polygon features, a positive value results in an inset, and a negative value results in an outset. Support basic functionality data-driven styling Mapbox >= 0.12.1 GeoTools >= 17.1 OpenLayers Not yet supported >= 0.29.0 >= 17.1 Not yet supported line-blur Optional Number. Units in pixels. Defaults to 0. Blur applied to the line, in pixels. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported >= 0.29.0 Not yet supported Not yet supported line-dasharray Optional Array. Units in line widths. Disabled by line-pattern. 6.6. MBStyle Styling 741 GeoServer User Manual, Release 2.15.1 Specifies the lengths of the alternating dashes and gaps that form the dash pattern. The lengths are later scaled by the line width. To convert a dash length to pixels, multiply the length by the current line width. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 Not yet supported >= 17.1 >= 2.4.0 line-pattern Optional String. Name of image in sprite to use for drawing image lines. For seamless patterns, image width must be a factor of two (2, 4, 8, . . . , 512). Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers Not yet supported Not yet supported >= 17.1 Not yet supported symbol Layout Properties symbol-placement Optional Enum. One of point, line. Defaults to point. Label placement relative to its geometry. point The label is placed at the point where the geometry is located. line The label is placed along the line of the geometry. Can only be used on LineString and Polygon geometries. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.10.0 Not yet supported >= 17.1 >= 2.10.0 symbol-spacing Optional Number. Units in pixels. Defaults to 250. Requires symbolplacement = line. Distance between two symbol anchors. 742 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported symbol-avoid-edges Optional Boolean. Defaults to false. If true, the symbols will not cross tile edges to avoid mutual collisions. Recommended in layers that don’t have enough padding in the vector tile to prevent collisions, or if it is a point symbol layer placed after a line symbol layer. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported icon-allow-overlap Optional Boolean. Defaults to false. Requires icon-image. If true, the icon will be visible even if it collides with other previously drawn symbols. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported icon-ignore-placement Optional Boolean. Defaults to false. Requires icon-image. If true, other symbols can be visible even if they collide with the icon. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported 6.6. MBStyle Styling 743 GeoServer User Manual, Release 2.15.1 icon-optional Optional Boolean. Defaults to false. = 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported icon-rotation-alignment Optional Enum. One of map, viewport, auto. Defaults to auto. Requires icon-image. In combination with symbol-placement, determines the rotation behavior of icons. map When symbol-placement is set to point, aligns icons east-west. When symbol-placement is set to line, aligns icon x-axes with the line. viewport Produces icons whose x-axes are aligned with the x-axis of the viewport, regardless of the value of symbol-placement. auto When symbol-placement is set to point, this is equivalent to viewport. When symbol-placement is set to line, this is equivalent to map. Support basic functionality auto value data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported >= 0.25.0 Not yet supported Not yet supported Not yet supported Not yet supported Not yet supported icon-size Optional Number. Defaults to 1. Requires icon-image. Scale factor for icon. 1 is original size, 3 triples the size. Support basic functionality data-driven styling 744 Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers >= 2.4.0 >= 0.35.0 Not yet supported >= 2.4.0 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 icon-text-fit Optional Enum. One of none, width, height, both. Defaults to none. Requires icon-image, text-field. Scales the icon to fit around the associated text. none The icon is displayed at its intrinsic aspect ratio. width The icon is scaled in the x-dimension to fit the width of the text. height The icon is scaled in the y-dimension to fit the height of the text. both The icon is scaled in both x- and y-dimensions. Support basic functionality data-driven styling Mapbox >= 0.21.0 GeoTools >= 17.1 OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported icon-text-fit-padding Optional :ref:‘types-array‘. *Units in pixels. Defaults to 0,0,0,0. Requires icon-image, text-field, icon-text-fit = one of both, width, height. Size of the additional area added to dimensions determined by icon-text-fit, in clockwise order: top, right, bottom, left. Support basic functionality data-driven styling Mapbox >= 0.21.0 GeoTools >= 17.1 OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported icon-image Optional String. Name of image in sprite to use for drawing an image background. A string with {tokens} replaced, referencing the data property to pull from. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 Not yet supported >= 17.1 >= 2.4.0 icon-rotate Optional Number. Units in degrees. Defaults to 0. Requires icon-image. 6.6. MBStyle Styling 745 GeoServer User Manual, Release 2.15.1 Rotates the icon clockwise. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.21.0 >= 17.1 >= 2.4.0 icon-padding Optional Number. Units in pixels. Defaults to 2. Requires icon-image. Size of the additional area around the icon bounding box used for detecting symbol collisions. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported icon-keep-upright Optional Boolean. Defaults to false. Requires icon-image, icon-rotationalignment = map, symbol-placement = line. If true, the icon may be flipped to prevent it from being rendered upside-down. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported icon-offset Optional Array. Defaults to 0,0. Requires icon-image. Offset distance of icon from its anchor. Positive values indicate right and down, while negative values indicate left and up. When combined with icon-rotate the offset will be as if the rotated direction was up. Support basic functionality data-driven styling 746 Mapbox >= 0.10.0 GeoTools >= Not yet supported OpenLayers Not yet supported >= 0.29.0 >= Not yet supported Not yet supported Chapter 6. Styling GeoServer User Manual, Release 2.15.1 text-pitch-alignment Optional Enum One of map, viewport, auto. Defaults to auto. Requires text-field. Orientation of text when map is pitched. map The text is aligned to the plane of the map. viewport The text is aligned to the plane of the viewport. auto Automatically matches the value of text-rotation-alignment. Support basic functionality auto value data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported >= 0.25.0 Not yet supported Not yet supported Not yet supported Not yet supported Not yet supported text-rotation-alignment Optional Enum. One of map, viewport, auto. Defaults to auto. Requires text-field. In combination with symbol-placement, determines the rotation behavior of the individual glyphs forming the text. map When symbol-placement is set to point, aligns text east-west. When symbol-placement is set to line, aligns text x-axes with the line. viewport Produces glyphs whose x-axes are aligned with the x-axis of the viewport, regardless of the value of symbol-placement. auto When symbol-placement is set to point, this is equivalent to viewport. When symbol-placement is set to line, this is equivalent to map. Support basic functionality auto value data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported >= 0.25.0 Not yet supported Not yet supported Not yet supported Not yet supported text-field Optional String. Value to use for a text label. Feature properties are specified using tokens like {field_name}. (Token replacement is only supported for literal text-field values–not for property functions.) 6.6. MBStyle Styling 747 GeoServer User Manual, Release 2.15.1 Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.33.0 >= 17.1 >= 2.4.0 text-font Optional Array. Defaults to Open Sans Regular,Arial Unicode MS Regular. Requires text-field. Font stack to use for displaying text. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 Not yet supported Not yet supported >= 2.4.0 text-size Optional Number. Units in pixels. Defaults to 16. Requires text-field. Font size. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.35.0 >= 17.1 >= 2.4.0 text-max-width Optional Number. Units in pixels. Defaults to 10. Requires text-field. The maximum line width for text wrapping. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers >= 2.4.0 Not yet supported Not yet supported >= 2.4.0 text-line-height Optional Number. Units in ems. Defaults to 1.2. Requires text-field. Text leading value for multi-line text. 748 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported text-letter-spacing Optional Number. Units in ems. Defaults to 0. Requires text-field. Text tracking amount. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported text-justify Optional Enum. One of left, center, right. Defaults to center. Requires text-field. Text justification options. left The text is aligned to the left. center The text is centered. right The text is aligned to the right. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported text-anchor Optional Enum. One of center, left, right, top, bottom, top-left, topright, bottom-left, bottom-right. Defaults to center. Requires textfield. Part of the text placed closest to the anchor. center The center of the text is placed closest to the anchor. left The left side of the text is placed closest to the anchor. right The right side of the text is placed closest to the anchor. top The top of the text is placed closest to the anchor. bottom The bottom of the text is placed closest to the anchor. 6.6. MBStyle Styling 749 GeoServer User Manual, Release 2.15.1 top-left The top left corner of the text is placed closest to the anchor. top-right The top right corner of the text is placed closest to the anchor. bottom-left The bottom left corner of the text is placed closest to the anchor. bottom-right The bottom right corner of the text is placed closest to the anchor. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers >= 2.4.0 Not yet supported Not yet supported >= 2.4.0 text-max-angle Optional Number. Units in degrees. Defaults to 45. Requires text-field, symbol-placement = line. Maximum angle change between adjacent characters. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers >= 2.10.0 Not yet supported Not yet supported >= 2.10.0 text-rotate Optional Number. Units in degrees. Defaults to 0. Requires text-field. Rotates the text clockwise. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers >= 2.10.0 >= 0.35.0 Not yet supported >= 2.10.0 text-padding Optional Number. Units in pixels. Defaults to 2. Requires text-field. Size of the additional area around the text bounding box used for detecting symbol collisions. 750 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported text-keep-upright Optional Boolean. Defaults to true. Requires text-field, text-rotationalignment = true, symbol-placement = true. If true, the text may be flipped vertically to prevent it from being rendered upside-down. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported text-transform Optional Enum. One of none, uppercase, lowercase. Defaults to none. Requires text-field. Specifies how to capitalize text-transform property. text, similar to the CSS none The text is not altered. uppercase Forces all letters to be displayed in uppercase. lowercase Forces all letters to be displayed in lowercase. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers >= 2.4.0 >= 0.33.0 Not yet supported >= 2.4.0 text-offset Optional Array. Units in pixels. Defaults to 0,0. Requires icon-image. Offset distance of text from its anchor. Positive values indicate right and down, while negative values indicate left and up. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers >= 2.4.0 >= 0.35.0 Not yet supported >= 2.4.0 6.6. MBStyle Styling 751 GeoServer User Manual, Release 2.15.1 text-allow-overlap Optional Boolean. Defaults to false. Requires text-field. If true, the text will be visible even if it collides with other previously drawn symbols. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported text-ignore-placement Optional Boolean. Defaults to false. Requires text-field If true, other symbols can be visible even if they collide with the text. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported text-optional Optional Boolean. Defaults to false. Requires text-field, icon-image. If true, icons will display without their corresponding text when the text collides with other symbols and the icon does not. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported visibility Optional Enum. One of visible, none. Defaults to visible. Whether this layer is displayed. visible The layer is shown. none The layer is not shown. 752 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 Not yet supported >= 17.1 >= 2.4.0 Paint Properties icon-opacity Optional Number. Defaults to 1. Requires icon-image. The opacity at which the icon will be drawn. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.33.0 >= 17.1 >= 2.4.0 icon-color Optional Color. Defaults to #000000. Requires icon-image. The color of the icon. This can only be used with sdf icons. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers >= 2.10.0 >= 0.33.0 Not yet supported >= 2.10.0 icon-halo-color Optional Color. Defaults to rgba(0, 0, 0, 0). Requires icon-image. The color of the icon’s halo. Icon halos can only be used with SDF icons. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported >= 0.33.0 Not yet supported Not yet supported icon-halo-width Optional Number. Units in pixels. Defaults to 0. Requires icon-image. 6.6. MBStyle Styling 753 GeoServer User Manual, Release 2.15.1 Distance of halo to the icon outline. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported >= 0.33.0 Not yet supported Not yet supported icon-halo-blur Optional Number. Units in pixels. Defaults to 0. Requires icon-image. Fade out the halo towards the outside. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported >= 0.33.0 Not yet supported Not yet supported icon-translate Optional Array. Units in pixels. Defaults to 0,0. Requires icon-image. Distance that the icon’s anchor is moved from its original placement. Positive values indicate right and down, while negative values indicate left and up. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported icon-translate-anchor Optional Enum One of map, viewport. Defaults to map. Requires iconimage, icon-translate. Controls the translation reference point. map Icons are translated relative to the map. viewport Icons are translated relative to the viewport. Support basic functionality data-driven styling 754 Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported Chapter 6. Styling GeoServer User Manual, Release 2.15.1 text-opacity Optional Number. Defaults to 1. Requires text-field. The opacity at which the text will be drawn. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers Not yet supported >= 0.33.0 >= 17.1 Not yet supported text-color Optional Color. Defaults to #000000. Requires text-field. The color with which the text will be drawn. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.33.0 >= 17.1 >= 2.4.0 text-halo-color Optional Color. Defaults to rgba(0, 0, 0, 0). Requires text-field. The color of the text’s halo, which helps it stand out from backgrounds. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.33.0 >= 17.1 >= 2.4.0 text-halo-width Optional Number. Units in pixels. Defaults to 0. Requires text-field. Distance of halo to the font outline. Max text halo width is 1/4 of the font-size. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.33.0 >= 17.1 >= 2.4.0 6.6. MBStyle Styling 755 GeoServer User Manual, Release 2.15.1 text-halo-blur Optional Number. Units in pixels. Defaults to 0. Requires text-field. The halo’s fadeout distance towards the outside. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported >= 0.33.0 Not yet supported Not yet supported text-translate Optional Array. Units in pixels. Defaults to 0,0. Requires text-field. Distance that the text’s anchor is moved from its original placement. Positive values indicate right and down, while negative values indicate left and up. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported text-translate-anchor Optional Enum One of map, viewport. Defaults to map. Requires textfield, text-translate. Controls the translation reference point. map The text is translated relative to the map. viewport The text is translated relative to the viewport. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported raster Layout Properties visibility Optional Enum. One of visible, none. Defaults to visible. 756 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Whether this layer is displayed. visible The layer is shown. none The layer is not shown. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers Not yet supported Not yet supported >= 17.1 Not yet supported Paint Properties raster-opacity Optional Number. Defaults to 1. The opacity at which the image will be drawn. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers Not yet supported Not yet supported >= 17.1 Not yet supported raster-hue-rotate Optional Number. Units in degrees. Defaults to 0. Rotates hues around the color wheel. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported raster-brightness-min Optional Number. Defaults to 0. Increase or reduce the brightness of the image. The value is the minimum brightness. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported 6.6. MBStyle Styling 757 GeoServer User Manual, Release 2.15.1 raster-brightness-max Optional Number. Defaults to 1. Increase or reduce the brightness of the image. The value is the maximum brightness. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported raster-saturation Optional Number. Defaults to 0. Increase or reduce the saturation of the image. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported raster-contrast Optional Number. Defaults to 0. Increase or reduce the contrast of the image. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported raster-fade-duration Optional Number Units in milliseconds. Defaults to 300. Fade duration when a new tile is added. Support basic functionality data-driven styling 758 Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported Chapter 6. Styling GeoServer User Manual, Release 2.15.1 circle Layout Properties visibility Optional Enum. One of visible, none. Defaults to visible. Whether this layer is displayed. visible The layer is shown. none The layer is not shown. Support basic functionality Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 Paint Properties circle-radius Optional Number. Units in pixels. Defaults to 5. Circle radius. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.18.0 >= 17.1 >= 2.4.0 circle-color Optional Color. Defaults to #000000. The fill color of the circle. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.18.0 >= 17.1 >= 2.4.0 circle-blur Optional Number. Defaults to 0. Amount to blur the circle. 1 blurs the circle such that only the centerpoint is full opacity. 6.6. MBStyle Styling 759 GeoServer User Manual, Release 2.15.1 Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported >= 0.20.0 Not yet supported Not yet supported circle-opacity Optional Number. Defaults to 1. The opacity at which the circle will be drawn. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.10.0 >= 0.20.0 >= 17.1 >= 2.10.0 circle-translate Optional Array. Units in pixels. Defaults to 0,0. The geometry’s offset. Values are [x, y] where negatives indicate left and up, respectively. Support basic functionality data-driven styling Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers Not yet supported Not yet supported >= 17.1 Not yet supported circle-translate-anchor Optional Enum One of map, viewport. Defaults to map. Requires circle-translate. Controls the translation reference point. map The circle is translated relative to the map. viewport The circle is translated relative to the viewport. Support basic functionality data-driven styling 760 Mapbox >= 0.10.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported Chapter 6. Styling GeoServer User Manual, Release 2.15.1 circle-pitch-scale Optional Enum One of map, viewport. Defaults to map. Controls the scaling behavior of the circle when the map is pitched. map Circles are scaled according to their apparent distance to the camera. viewport Circles are not scaled. Support basic functionality data-driven styling Mapbox >= 0.21.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported circle-stroke-width Optional Number. Units in pixels. Defaults to 5. The width of the circle’s stroke. Strokes are placed outside of the circle-radius. Support basic functionality data-driven styling Mapbox >= 0.29.0 GeoTools >= 17.1 OpenLayers >= 2.10.0 >= 0.29.0 >= 17.1 >= 2.10.0 circle-stroke-color Optional Color. Defaults to #000000. The stroke color of the circle. Support basic functionality data-driven styling Mapbox >= 0.29.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.29.0 >= 17.1 >= 2.4.0 circle-stroke-opacity Optional Number. Defaults to 1. The opacity of the circle’s stroke. Support basic functionality data-driven styling Mapbox >= 0.29.0 GeoTools >= 17.1 OpenLayers Not yet supported >= 0.29.0 >= 17.1 Not yet supported 6.6. MBStyle Styling 761 GeoServer User Manual, Release 2.15.1 fill-extrusion Layout Properties visibility Optional Enum. One of visible, none. Defaults to visible. Whether this layer is displayed. visible The layer is shown. none The layer is not shown. Support basic functionality Mapbox >= 0.27.0 GeoTools >= 17.1 OpenLayers Not yet supported Paint Properties fill-extrusion-opacity Optional Number. Defaults to 1. The opacity of the entire fill extrusion layer. This is rendered on a per-layer, not per-feature, basis, and data-driven styling is not available. Support basic functionality Mapbox >= 0.27.0 GeoTools >= 17.1 OpenLayers Not yet supported fill-extrusion-color Optional Color. Defaults to #000000. Disabled by fill-extrusion-pattern. The base color of the extruded fill. The extrusion’s surfaces will be shaded differently based on this color in combination with the root light settings. If this color is specified as rgba with an alpha component, the alpha component will be ignored; use fill-extrusion-opacity to set layer opacity. Support basic functionality Mapbox >= 0.27.0 GeoTools >= 17.1 OpenLayers Not yet supported fill-extrusion-translate Optional Array. Units in pixels. Defaults to 0,0. 762 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 The geometry’s offset. Values are [x, y] where negatives indicate left and up (on the flat plane), respectively. Support basic functionality data-driven styling Mapbox >= 0.27.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported Optional Enum One of map, viewport. Defaults to map. Requires fillextrusion-translate. Controls the translation reference point. map The fill extrusion is translated relative to the map. viewport The fill extrusion is translated relative to the viewport. Support basic functionality data-driven styling Mapbox >= 0.27.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported fill-extrusion-pattern Optional String. Name of image in sprite to use for drawing images on extruded fills. For seamless patterns, image width and height must be a factor of two (2, 4, 8, . . . , 512). Support basic functionality data-driven styling Mapbox >= 0.27.0 GeoTools Not yet supported OpenLayers Not yet supported Not yet supported Not yet supported Not yet supported fill-extrusion-height Optional Number Units in meters. Defaults to 0. The height with which to extrude this layer. Support basic functionality data-driven styling Mapbox >= 0.27.0 GeoTools Not yet supported OpenLayers Not yet supported >= 0.27.0 Not yet supported Not yet supported 6.6. MBStyle Styling 763 GeoServer User Manual, Release 2.15.1 fill-extrusion-base Optional Number Units in meters. Defaults to 0. Requires fill-extrusionheight. The height with which to extrude the base of this layer. Must be less than or equal to fill-extrusion-height. Support basic functionality data-driven styling Mapbox >= 0.27.0 GeoTools Not yet supported OpenLayers Not yet supported >= 0.27.0 Not yet supported Not yet supported Types A Mapbox style contains values of various types, most commonly as values for the style properties of a layer. Color Colors are written as JSON strings in a variety of permitted formats: HTML-style hex values, rgb, rgba, hsl, and hsla. Predefined HTML colors names, like yellow and blue, are also permitted. { "line-color": "line-color": "line-color": "line-color": "line-color": "line-color": "line-color": "#ff0", "#ffff00", "rgb(255, 255, 0)", "rgba(255, 255, 0, 1)", "hsl(100, 50%, 50%)", "hsla(100, 50%, 50%, 1)", "yellow" } Especially of note is the support for hsl, which can be easier to reason about than rgb(). Enum One of a fixed list of string values. Use quotes around values. { "text-transform": "uppercase" } String A string is basically just text. In Mapbox styles, you’re going to put it in quotes. Strings can be anything, though pay attention to the case 764 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 of text-field - it actually will refer to features, which you refer to by putting them in curly braces, as seen in the example below. { "text-field": "{MY_FIELD}" } Boolean Boolean means yes or no, so it accepts the values true or false. { "fill-enabled": true } Number A number value, often an integer or floating point (decimal number). Written without quotes. { "text-size": 24 } Array Arrays are comma-separated lists of one or more numbers in a specific order. For example, they’re used in line dash arrays, in which the numbers specify intervals of line, break, and line again. { "line-dasharray": [2, 4] } Expressions The value for any layout property, paint property, or filter may be specified as an expression. An expression defines a formula for computing the value of the property using the operators described below. The set of expression operators provided by Mapbox GL includes: • Mathematical operators for performing arithmetic and other operations on numeric values • Logical operators for manipulating boolean values and making conditional decisions • String operators for manipulating strings • Data operators, providing access to the properties of source features 6.6. MBStyle Styling 765 GeoServer User Manual, Release 2.15.1 • Camera operators, providing access to the parameters defining the current map view Expressions are represented as JSON arrays. The first element of an expression array is a string naming the expression operator, e.g. "*" or "case". Subsequent elements (if any) are the arguments to the expression. Each argument is either a literal value (a string, number, boolean, or null), or another expression array. [expression_name, argument_0, argument_1, . . . ] Data expressions A data expression is any expression that access feature data – that is, any expression that uses one of the data operators: get, has, id, geometry-type, properties, or feature-state. Data expressions allow a feature’s properties or state to determine its appearance. They can be used to differentiate features within the same layer and to create data visualizations. { "circle-color": [ "rgb", // red is ,→higher when feature.properties.temperature is higher ["get", "temperature"], // green is always zero 0, // blue is ,→higher when feature.properties.temperature is lower ["-", 100, ["get", "temperature"]] ] } This example uses the get operator to obtain the temperature value of each feature. That value is used to compute arguments to the rgb operator, defining a color in terms of its red, green, and blue components. Data expressions are allowed as the value of the filter property, and as values for most paint and layout properties. However, some paint and layout properties do not yet support data expressions. The level of support is indicated by the “data-driven styling” row of the “SDK Support” table for each property. Data expressions with the feature-state operator are allowed only on paint properties. Camera expressions A camera expression is any expression that uses the zoom operator. Such expressions allow the the appearance of a layer to change with the map’s zoom level. Camera expressions can be used to create the appearance of depth and to control data density. { "circle-radius": [ "interpolate", ["linear"], ["zoom"], ,→ 766 // zoom is 5 (or less) -> circle radius will be 1px 5, 1, Chapter 6. Styling GeoServer User Manual, Release 2.15.1 ,→ // zoom is 10 (or greater) -> circle radius will be 5px 10, 5 ] } This example uses the interpolate operator to define a linear relationship between zoom level and circle size using a set of inputoutput pairs. In this case, the expression indicates that the circle radius should be 1 pixel when the zoom level is 5 or below, and 5 pixels when the zoom is 10 or above. In between, the radius will be linearly interpolated between 1 and 5 pixels Camera expressions are allowed anywhere an expression may be used. However, when a camera expression used as the value of a layout or paint property, it must be in one of the following forms: [ "interpolate", interpolation, ["zoom"], ... ] Or: [ "step", ["zoom"], ... ] Or: [ "let", ... variable bindings..., [ "interpolate", interpolation, ["zoom"], ... ] ] Or: [ "let", ... variable bindings..., [ "step", ["zoom"], ... ] ] That is, in layout or paint properties, ["zoom"] may appear only as the input to an outer interpolate or step expression, or such an expression within a let expression. There is an important difference between layout and paint properties in the timing of camera expression evaluation. Paint property camera expressions are re-evaluated whenever the zoom level changes, even fractionally. For example, a paint property camera expression will be re-evaluated continuously as the map moves between zoom levels 4.1 and 4.6. On the other hand, a layout property camera expression is evaluated only at integer zoom levels. It will not be re-evaluated as the zoom changes from 4.1 to 4.6 – only if it goes above 5 or below 4. Composition A single expression may use a mix of data operators, camera operators, and other operators. Such composite expressions allows a 6.6. MBStyle Styling 767 GeoServer User Manual, Release 2.15.1 layer’s appearance to be determined by a combination of the zoom level and individual feature properties. { "circle-radius": [ "interpolate", ["linear"], ["zoom"], // when zoom is 0, set each feature's ,→circle radius to the value of its "rating" property 0, ["get", "rating"], // when zoom is 10, set each feature's circle radius to four times the value of its "rating" property 10, ["*", 4, ["get", "rating"]] ] ,→ ,→ } An expression that uses both data and camera operators is considered both a data expression and a camera expression, and must adhere to the restrictions described above for both. Type system The input arguments to expressions, and their result values, use the same set of types as the rest of the style specification: boolean, string, number, color, and arrays of these types. Furthermore, expressions are type safe: each use of an expression has a known result type and required argument types, and the SDKs verify that the result type of an expression is appropriate for the context in which it is used. For example, the result type of an expression in the filter property must be boolean, and the arguments to the + operator must be numbers. When working with feature data, the type of a feature property value is typically not known ahead of time by the SDK. In order to preserve type safety, when evaluating a data expression, the SDK will check that the property value is appropriate for the context. For example, if you use the expression ["get", "feature-color"] for the circle-color property, the SDK will verify that the feature-color value of each feature is a string identifying a valid color. If this check fails, an error will be indicated in an SDK-specific way (typically a log message), and the default value for the property will be used instead. In most cases, this verification will occur automatically wherever it is needed. However, in certain situations, the SDK may be unable to automatically determine the expected result type of a data expression from surrounding context. For example, it is not clear whether the expression ["<", ["get", "a"], ["get", "b"]] is attempting to compare strings or numbers. In situations like this, you can use one of the type assertion expression operators to indicate the expected type of a data expression: ["<", ["number", ["get", "a"]], ["number", ["get", "b"]]]. A type assertion checks that the feature data actually matches the expected type of the data expression. If this check fails, it produces an error and causes the whole expression to fall back to the default value for the property being defined. The assertion operators are array, boolean, number, and string. 768 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Expressions perform only one kind of implicit type conversion: a data expression used in a context where a color is expected will convert a string representation of a color to a color value. In all other cases, if you want to convert between types, you must use one of the type conversion expression operators: to-boolean, to-number, to-string, or to-color. For example, if you have a feature property that stores numeric values in string format, and you want to use those values as numbers rather than strings, you can use an expression such as ["to-number", ["get", "property-name"]]. Expression reference Types The expressions in this section are provided for the purpose of testing for and converting between different data types like strings, numbers, and boolean values. Often, such tests and conversions are unnecessary, but they may be necessary in some expressions where the type of a certain subexpression is ambiguous. They can also be useful in cases where your feature data has inconsistent types; for example, you could use to-number to make sure that values like "1.5" (instead of 1.5) are treated as numeric values. array Asserts that the input is an array (optionally with a specific item type and length). If, when the input expression is evaluated, it is not of the asserted type, then this assertion will cause the whole expression to be aborted. ["array", value]: array ["array", type: ,→"string" | "number" | "boolean", value]: array ["array", type: "string" | "number" | "boolean", N: number (literal), value ]: array Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 boolean Asserts that the input value is a boolean. If multiple values are provided, each one is evaluated in order until a boolean is obtained. If 6.6. MBStyle Styling 769 GeoServer User Manual, Release 2.15.1 none of the inputs are booleans, the expression is an error. ["boolean", value]: boolean ["boolean", value, ,→ fallback: value, fallback: value, ...]: boolean Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 collator Returns a collator for use in locale-dependent comparison operations. The case-sensitive and diacritic-sensitive options default to false. The locale argument specifies the IETF language tag of the locale to use. If none is provided, the default locale is used. If the requested locale is not available, the collator will use a system-defined fallback locale. Use resolved-locale to test the results of locale fallback behavior. ["collator", { "case-sensitive": boolean, ,→ "diacritic-sensitive": boolean, "locale": string } ]: collator Support basic functionality Mapbox >= 0.45.0 GeoTools >= Not yet supported OpenLayers >= Not yet supported format Returns formatted text containing annotations for use in mixedformat text-field entries. If set, the text-font argument overrides the font specified by the root layout properties. If set, the font-scale argument specifies a scaling factor relative to the text-size specified in the root layout properties. ["format", input_1: string, options_1: ,→{ "font-scale": number, "text-font": array }, ..., input_n: string, options_n: ,→{ "font-scale": number, "text-font": array } ]: formatted Support basic functionality 770 Mapbox >= 0.48.0 GeoTools >= Not yet supported OpenLayers >= Not yet supported Chapter 6. Styling GeoServer User Manual, Release 2.15.1 literal Provides a literal array or object value. ["literal", [...] (JSON array literal)]: array ["literal", {...} (JSON object literal)]: Object Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 number Asserts that the input value is a number. If multiple values are provided, each one is evaluated in order until a number is obtained. If none of the inputs are numbers, the expression is an error. ["number", value]: number ["number", ,→value, fallback: value, fallback: value, ...]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 object Asserts that the input value is an object. If multiple values are provided, each one is evaluated in order until an object is obtained. If none of the inputs are objects, the expression is an error. ["object", value]: object ["object", ,→value, fallback: value, fallback: value, ...]: object Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 string Asserts that the input value is a string. If multiple values are provided, each one is evaluated in order until a string is obtained. If none of the inputs are strings, the expression is an error. 6.6. MBStyle Styling 771 GeoServer User Manual, Release 2.15.1 ["string", value]: string ["string", ,→value, fallback: value, fallback: value, ...]: string Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 to-boolean Converts the input value to a boolean. The result is false when then input is an empty string, 0, false, null, or NaN; otherwise it is true. ["to-boolean", value]: boolean Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 to-color Converts the input value to a color. If multiple values are provided, each one is evaluated in order until the first successful conversion is obtained. If none of the inputs can be converted, the expression is an error. ["to-color", ,→ value, fallback: value, fallback: value, ...]: color Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 to-number Converts the input value to a number, if possible. If the input is null or false, the result is 0. If the input is true, the result is 1. If the input is a string, it is converted to a number as specified by the “ToNumber Applied to the String Type” algorithm of the ECMAScript Language Specification. If multiple values are provided, each one is evaluated in order until the first successful conversion is obtained. If none of the inputs can be converted, the expression is an error. ["to-number", ,→value, fallback: value, fallback: value, ...]: number 772 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 to-string Converts the input value to a string. If the input is null, the result is "". If the input is a boolean, the result is "true" or "false". If the input is a number, it is converted to a string as specified by the “NumberToString” algorithm of the ECMAScript Language Specification. If the input is a color, it is converted to a string of the form "rgba(r,g,b,a)", where r, g, and b are numerals ranging from 0 to 255, and a ranges from 0 to 1. Otherwise, the input is converted to a string in the format specified by the JSON.stringify function of the ECMAScript Language Specification. ["to-string", value]: string Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 typeof Returns a string describing the type of the given value. ["typeof", value]: string Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 Feature data feature-state Retrieves a property value from the current feature’s state. Returns null if the requested property is not present on the feature’s state. A feature’s state is not part of the GeoJSON or vector tile data, and must be set programmatically on each feature. Note that ["feature-state"] can only be used with paint properties that support data-driven styling. ["feature-state", string]: value Support basic functionality Mapbox >= 0.46.0 6.6. MBStyle Styling GeoTools >= Not yet supported OpenLayers >= Not yet supported 773 GeoServer User Manual, Release 2.15.1 geometry-type Gets the feature’s geometry type: Point, MultiPoint, LineString, MultiLineString, Polygon, MultiPolygon. ["geometry-type"]: string Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 id Gets the feature’s id, if it has one. ["id"]: value Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 line-progress Gets the progress along a gradient line. Can only be used in the line-gradient property. ["line-progress"]: number Support basic functionality Mapbox >= 0.45.0 GeoTools >= Not yet supported OpenLayers >= Not yet supported properties Gets the feature properties object. Note that in some cases, it may be more efficient to use [“get”, “property_name”] directly. ["properties"]: object Support basic functionality 774 Mapbox >= 0.41.0 GeoTools >= Not yet supported OpenLayers >= 3.0.0 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Lookup at Retrieves an item from an array. ["at", number, array]: ItemType Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 get Retrieves a property value from the current feature’s properties, or from another object if a second argument is provided. Returns null if the requested property is missing. ["get", string]: value ["get", string, object]: value Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 has Tests for the presence of an property value in the current feature’s properties, or from another object if a second argument is provided. ["has", string]: boolean ["has", string, object]: boolean Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 length Gets the length of an array or string. ["length", string | array | value]: number Support basic functionality Mapbox >= 0.41.0 6.6. MBStyle Styling GeoTools >= 20.0 OpenLayers >= 3.0.0 775 GeoServer User Manual, Release 2.15.1 Decision The expressions in this section can be used to add conditional logic to your styles. For example, the 'case' expression provides basic “if/then/else” logic, and 'match' allows you to map specific values of an input expression to different output expressions. ! Logical negation. Returns true if the input is false, and false if the input is true. ["!", boolean]: boolean Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 != Returns true if the input values are not equal, false otherwise. The comparison is strictly typed: values of different runtime types are always considered unequal. Cases where the types are known to be different at parse time are considered invalid and will produce a parse error. Accepts an optional collator argument to control locale-dependent string comparisons. ["!=", value, value]: boolean ["!=", value, value, collator]: boolean Support basic functionality collator Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 >= 0.45.0 >= Not yet supported >= Not yet supported < Returns true if the first input is strictly less than the second, false otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional collator argument to control localedependent string comparisons. ["<", value, value]: boolean 776 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 ["<", value, value, collator]: boolean Support basic functionality collator Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 >= 0.45.0 >= Not yet supported >= Not yet supported <= Returns true if the first input is less than or equal to the second, false otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional collator argument to control locale-dependent string comparisons. ["<=", value, value]: boolean ["<=", value, value, collator]: boolean Support basic functionality collator Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 >= 0.45.0 >= Not yet supported >= Not yet supported == Returns true if the input values are equal, false otherwise. The comparison is strictly typed: values of different runtime types are always considered unequal. Cases where the types are known to be different at parse time are considered invalid and will produce a parse error. Accepts an optional collator argument to control locale-dependent string comparisons. ["==", value, value]: boolean ["==", value, value, collator]: boolean Support basic functionality collator Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 >= 0.45.0 >= Not yet supported >= Not yet supported > Returns true if the first input is strictly greater than the second, false otherwise. The arguments are required to be either both 6.6. MBStyle Styling 777 GeoServer User Manual, Release 2.15.1 strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional collator argument to control locale-dependent string comparisons. [">", value, value]: boolean [">", value, value, collator]: boolean Support basic functionality collator Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 >= 0.45.0 >= Not yet supported >= Not yet supported >= Returns true if the first input is greater than or equal to the second, false otherwise. The arguments are required to be either both strings or both numbers; if during evaluation they are not, expression evaluation produces an error. Cases where this constraint is known not to hold at parse time are considered in valid and will produce a parse error. Accepts an optional collator argument to control locale-dependent string comparisons. [">=", value, value]: boolean [">=", value, value, collator]: boolean Support basic functionality collator Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 >= 0.45.0 >= Not yet supported >= Not yet supported all Returns true if all the inputs are true, false otherwise. The inputs are evaluated in order, and evaluation is short-circuiting: once an input expression evaluates to false, the result is false and no further input expressions are evaluated. ["all", boolean, boolean]: boolean ["all", boolean, boolean, ...]: boolean Support basic functionality 778 Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 any Returns true if any of the inputs are true, false otherwise. The inputs are evaluated in order, and evaluation is short-circuiting: once an input expression evaluates to true, the result is true and no further input expressions are evaluated. ["any", boolean, boolean]: boolean ["any", boolean, boolean, ...]: boolean Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 case Selects the first output whose corresponding test condition evaluates to true. ["case", condition: boolean, output: OutputType, ,→ condition: boolean, output: OutputType, ..., default: OutputType ]: OutputType Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 coalesce Evaluates each expression in turn until the first non-null value is obtained, and returns that value. ["coalesce", OutputType, OutputType, ...]: OutputType Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 match Selects the output whose label value matches the input value, or the fallback value if no match is found. The input can be any expression (e.g. ["get", "building_type"]). Each label must either be a single literal value or an array of literal values (e.g. "a" or ["c", "b"]), and those values must be all strings or all numbers. (The values "1" and 1 cannot both be labels in the same match expression.) 6.6. MBStyle Styling 779 GeoServer User Manual, Release 2.15.1 Each label must be unique. If the input type does not match the type of the labels, the result will be the fallback value. ["match", input: InputType (number or string), label_1: InputType ,→| [InputType, InputType, ...], output_1: OutputType, label_n: InputType | [InputType, ,→ InputType, ...], output_n: OutputType, ..., default: OutputType ]: OutputType Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 Ramps, scales, curves interpolate Produces continuous, smooth results by interpolating between pairs of input and output values (“stops”). The input may be any numeric expression (e.g., ["get", "population"]). Stop inputs must be numeric literals in strictly ascending order. The output type must be number, array, or color. Interpolation types: • ["linear"]: interpolates linearly between the pair of stops just less than and just greater than the input. • ["exponential", base]: interpolates exponentially between the stops just less than and just greater than the input. base controls the rate at which the output increases: higher values make the output increase more towards the high end of the range. With values close to 1 the output increases linearly. • ["cubic-bezier", x1, y1, x2, y2]: interpolates using the cubic bezier curve defined by the given control points. ["interpolate", interpolation: ["linear"] | ["exponential ,→", base] | ["cubic-bezier", x1, y1, x2, y2 ], input: number, stop_input_1: number, stop_output_1: OutputType, ,→ stop_input_n: number, stop_output_n: OutputType, ... ]: OutputType (number, array, or Color) Support basic functionality 780 Mapbox >= 0.42.0 GeoTools >= Not yet supported OpenLayers >= 3.0.0 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 interpolate-hcl Produces continuous, smooth results by interpolating between pairs of input and output values (“stops”). Works like interpolate, but the output type must be color, and the interpolation is performed in the Hue-Chroma-Luminance color space. ["interpolate-hcl", interpolation: ["linear"] | ["exponential ,→", base] | ["cubic-bezier", x1, y1, x2, y2 ], input: number, stop_input_1: number, stop_output_1: Color, stop_input_n: number, stop_output_n: Color, ... ]: Color Support basic functionality Mapbox >= 0.49.0 GeoTools >= Not yet supported OpenLayers >= 3.0.0 interpolate-lab Produces continuous, smooth results by interpolating between pairs of input and output values (“stops”). Works like interpolate, but the output type must be color, and the interpolation is performed in the CIELAB color space. ["interpolate-lab", interpolation: ["linear"] | ["exponential ,→", base] | ["cubic-bezier", x1, y1, x2, y2 ], input: number, stop_input_1: number, stop_output_1: Color, stop_input_n: number, stop_output_n: Color, ... ]: Color Support basic functionality Mapbox >= 0.49.0 GeoTools >= Not yet supported OpenLayers >= 3.0.0 step Produces discrete, stepped results by evaluating a piecewiseconstant function defined by pairs of input and output values (“stops”). The input may be any numeric expression (e.g., ["get", "population"]). Stop inputs must be numeric literals in strictly ascending order. Returns the output value of the stop just less than the input, or the first input if the input is less than the first stop. ["step", input: number, stop_output_0: OutputType, 6.6. MBStyle Styling 781 GeoServer User Manual, Release 2.15.1 stop_input_1: number, stop_output_1: OutputType, ,→ stop_input_n: number, stop_output_n: OutputType, ... ]: OutputType Support basic functionality Mapbox >= 0.42.0 GeoTools >= Not yet supported OpenLayers >= 3.0.0 Variable binding let Binds expressions to named variables, which can then be referenced in the result expression using [“var”, “variable_name”]. ["let", string (alphanumeric literal), ,→ any, string (alphanumeric literal), any, ..., OutputType ]: OutputType Support basic functionality Mapbox >= 0.41.0 GeoTools >= Not yet supported OpenLayers >= 3.0.0 var References variable bound using “let”. ["var", previously bound ,→variable name]: the type of the bound expression Support basic functionality Mapbox >= 0.41.0 GeoTools >= Not yet supported OpenLayers >= 3.0.0 String concat Returns a string consisting of the concatenation of the inputs. Each input is converted to a string as if by to-string. ["concat", value, value, ...]: string 782 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 downcase Returns the input string converted to lowercase. Follows the Unicode Default Case Conversion algorithm and the locale-insensitive case mappings in the Unicode Character Database. ["downcase", string]: string Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= Not yet supported is-supported-script Returns true if the input string is expected to render legibly. Returns false if the input string contains sections that cannot be rendered without potential loss of meaning (e.g. Indic scripts that require complex text shaping, or right-to-left scripts if the the mapbox-gl-rtl-text plugin is not in use in Mapbox GL JS). ["is-supported-script", string]: boolean resolved-locale Returns the IETF language tag of the locale being used by the provided collator. This can be used to determine the default system locale, or to determine if a requested locale was successfully loaded. ["resolved-locale", collator]: string Support basic functionality Mapbox >= 0.45.0 GeoTools >= Not yet supported OpenLayers >= Not yet supported upcase Returns the input string converted to uppercase. Follows the Unicode Default Case Conversion algorithm and the locale-insensitive case mappings in the Unicode Character Database. ["upcase", string]: string 6.6. MBStyle Styling 783 GeoServer User Manual, Release 2.15.1 Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= Not yet supported Color rgb Creates a color value from red, green, and blue components, which must range between 0 and 255, and an alpha component of 1. If any component is out of range, the expression is an error. ["rgb", number, number, number]: color Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 rgba Creates a color value from red, green, blue components, which must range between 0 and 255, and an alpha component which must range between 0 and 1. If any component is out of range, the expression is an error. ["rgba", number, number, number, number]: color Support basic functionality Mapbox >= 0.41.0 GeoTools >= Not yet supported OpenLayers >= 3.0.0 to-rgba Returns a four-element array containing the input color’s red, green, blue, and alpha components, in that order. ["to-rgba", color]: array Support basic functionality 784 Mapbox >= 0.41.0 GeoTools >= Not yet supported OpenLayers >= 3.0.0 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Math For two inputs, returns the result of subtracting the second input from the first. For a single input, returns the result of subtracting it from 0. ["-", number, number]: number ["-", number]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 * Returns the product of the inputs. ["*", number, number, ...]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 / Returns the result of floating point division of the first input by the second. ["/", number, number]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 % Returns the remainder after integer division of the first input by the second. ["%", number, number]: number Support basic functionality Mapbox >= 0.41.0 6.6. MBStyle Styling GeoTools >= 20.0 OpenLayers >= 3.0.0 785 GeoServer User Manual, Release 2.15.1 ^ Returns the result of raising the first input to the power specified by the second. ["^", number, number]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 + Returns the sum of the inputs. ["+", number, number, ...]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 abs Returns the absolute value of the input. ["abs", number]: number Support basic functionality Mapbox >= 0.45.0 GeoTools >= Not yet supported OpenLayers >= 3.0.0 acos Returns the arccosine of the input. ["acos", number]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 asin Returns the arcsine of the input. ["asin", number]: number 786 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 atan Returns the arctangent of the input. ["atan", number]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 ceil Returns the smallest integer that is greater than or equal to the input. ["ceil", number]: number Support basic functionality Mapbox >= 0.45.0 GeoTools >= Not yet supported OpenLayers >= 3.0.0 cos Returns the cosine of the input. ["cos", number]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 e Returns the mathematical constant e. ["e"]: number Support basic functionality Mapbox >= 0.41.0 6.6. MBStyle Styling GeoTools >= 20.0 OpenLayers >= 3.0.0 787 GeoServer User Manual, Release 2.15.1 floor Returns the largest integer that is less than or equal to the input. ["floor", number]: number Support basic functionality Mapbox >= 0.45.0 GeoTools >= Not yet supported OpenLayers >= 3.0.0 ln Returns the natural logarithm of the input. ["ln", number]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 ln2 Returns mathematical constant ln(2). ["ln2"]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 log10 Returns the base-ten logarithm of the input. ["log10", number]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 log2 Returns the base-two logarithm of the input. ["log2", number]: number 788 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 max Returns the maximum value of the inputs. ["max", number, number, ...]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 min Returns the minimum value of the inputs. ["min", number, number, ...]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 pi Returns the mathematical constant pi. ["pi"]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 round Rounds the input to the nearest integer. Halfway values are rounded away from zero. For example, ["round", -1.5] evaluates to -2. ["round", number]: number Support basic functionality Mapbox >= 0.45.0 6.6. MBStyle Styling GeoTools >= Not yet supported OpenLayers >= 3.0.0 789 GeoServer User Manual, Release 2.15.1 sin Returns the sine of the input. ["sin", number]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 sqrt Returns the square root of the input. ["sqrt", number]: number Support basic functionality Mapbox >= 0.42.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 tan Returns the tangent of the input. ["tan", number]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 Zoom zoom Gets the current zoom level. Note that in style layout and paint properties, [“zoom”] may only appear as the input to a top-level “step” or “interpolate” expression. ["zoom"]: number Support basic functionality 790 Mapbox >= 0.41.0 GeoTools >= 20.0 OpenLayers >= 3.0.0 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Heatmap heatmap-density Gets the kernel density estimation of a pixel in a heatmap layer, which is a relative measure of how many data points are crowded around a particular pixel. Can only be used in the heatmap-color property. ["heatmap-density"]: number Support basic functionality Mapbox >= 0.41.0 GeoTools >= Not yet supported OpenLayers >= Not yet supported Other Function The value for any layout or paint property may be specified as a function. Functions allow you to make the appearance of a map feature change with the current zoom level and/or the feature’s properties. stops Required (except for identity functions) :ref:‘types-array‘. Functions are defined in terms of input and output values. A set of one input value and one output value is known as a “stop.” property Optional String. If specified, the function will take the specified feature property as an input. See Zoom Functions and Property Functions for more information. base Optional Number. Default is 1. The exponential base of the interpolation curve. It controls the rate at which the function output increases. Higher values make the output increase more towards the high end of the range. With values close to 1 the output increases linearly. 6.6. MBStyle Styling 791 GeoServer User Manual, Release 2.15.1 type Optional Enum. One of identity, exponential, interval, categorical. identity functions return their input as their output. exponential functions generate an output by interpolating between stops just less than and just greater than the function input. The domain must be numeric. This is the default for properties marked with , the “exponential” symbol. interval functions return the output value of the stop just less than the function input. The domain must be numeric. This is the default for properties marked with , the “interval” symbol. categorical functions return the output value of the stop equal to the function input. default A value to serve as a fallback function result when a value isn’t otherwise available. It is used in the following circumstances: • In categorical functions, when the feature value does not match any of the stop domain values. • In property and zoom-and-property functions, when a feature does not contain a value for the specified property. • In identity functions, when the feature value is not valid for the style property (for example, if the function is being used for a circle-color property but the feature property value is not a string or not a valid color). • In interval or exponential property and zoom-and-property functions, when the feature value is not numeric. If no default is provided, the style property’s default is used in these circumstances. colorSpace Optional Enum. One of rgb, lab, hcl. The color space in which colors interpolated. Interpolating colors in perceptual color spaces like LAB and HCL tend to produce color ramps that look more consistent and produce colors that can be differentiated more easily than those interpolated in RGB space. rgb Use the RGB color space to interpolate color values lab Use the LAB color space to interpolate color values. hcl Use the HCL color space to interpolate color values, interpolating the Hue, Chroma, and Luminance channels individually. 792 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Support basic functionality property type exponential type interval type categorical type identity type default type colorSpace type Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.18.0 >= 0.18.0 >= 0.18.0 >= 17.1 >= 17.1 >= 17.1 >= 2.4.0 >= 2.4.0 >= 2.4.0 >= 0.18.0 >= 0.18.0 >= 17.1 >= 17.1 >= 2.4.0 >= 2.4.0 >= 0.18.0 >= 0.18.0 >= 0.26.0 >= 17.1 >= 17.1 Not yet supported >= 2.4.0 >= 2.4.0 >= 2.4.0 Zoom functions allow the appearance of a map feature to change with map’s zoom level. Zoom functions can be used to create the illusion of depth and control data density. Each stop is an array with two elements: the first is a zoom level and the second is a function output value. { "circle-radius": { "stops": [ // zoom is 5 -> circle radius will be 1px [5, 1], // zoom is 10 -> circle radius will be 2px [10, 2] ] } } The rendered values of Color, Number, and Array properties are intepolated between stops. Enum, Boolean, and String property values cannot be intepolated, so their rendered values only change at the specified stops. There is an important difference between the way that zoom functions render for layout and paint properties. Paint properties are continuously re-evaluated whenever the zoom level changes, even fractionally. The rendered value of a paint property will change, for example, as the map moves between zoom levels 4.1 and 4.6. Layout properties, on the other hand, are evaluated only once for each integer zoom level. To continue the prior example: the rendering of a layout property will not change between zoom levels 4.1 and 4.6, no matter what stops are specified; but at zoom level 5, the function will be re-evaluated according to the function, and the property’s rendered value will change. (You can include fractional zoom levels in a layout property zoom function, and it will affect the generated values; but, still, the rendering will only change at integer zoom levels.) 6.6. MBStyle Styling 793 GeoServer User Manual, Release 2.15.1 Property functions allow the appearance of a map feature to change with its properties. Property functions can be used to visually differentate types of features within the same layer or create data visualizations. Each stop is an array with two elements, the first is a property input value and the second is a function output value. Note that support for property functions is not available across all properties and platforms at this time. { "circle-color": { "property": "temperature", "stops": [ ,→ ,→ // "temperature" is 0 [0, 'blue'], -> circle color will be blue // "temperature" is 100 -> circle color will be red [100, 'red'] ] } } Zoom-and-property functions allow the appearance of a map feature to change with both its properties and zoom. Each stop is an array with two elements, the first is an object with a property input value and a zoom, and the second is a function output value. Note that support for property functions is not yet complete. { "circle-radius": { "property": "rating", "stops": [ // zoom is 0 and "rating" is 0 -> circle radius will be 0px [{zoom: 0, value: 0}, 0], ,→ // zoom is 0 and "rating" is 5 -> circle radius will be 5px [{zoom: 0, value: 5}, 5], ,→ // zoom is 20 and "rating" is 0 -> circle radius will be 0px [{zoom: 20, value: 0}, 0], ,→ // zoom is 20 and "rating" is 5 -> circle radius will be 20px [{zoom: 20, value: 5}, 20] ,→ ] } } 794 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Filter A filter selects specific features from a layer. A filter is an array of one of the following forms: Existential Filters ["has", key] feature[key] exists ["!has", key] feature[key] does not exist Comparison Filters ["==", key, value] equality: feature[key] = value ["!=", key, value] inequality: feature[key] value [">", key, value] greater than: feature[key] > value [">=", key, value] greater than or equal: feature[key] value ["<", key, value] less than: feature[key] < value ["<=", key, value] less than or equal: feature[key] value Set Membership Filters ["in", key, v0, ..., vn] set inclusion: feature[key] {v0, . . . , vn} ["!in", key, v0, ..., vn] set exclusion: feature[key] {v0, . . . , vn} Combining Filters ["all", f0, ..., fn] logical AND: f0 . . . fn ["any", f0, ..., fn] logical OR: f0 . . . fn ["none", f0, ..., fn] logical NOR: ¬f0 . . . ¬fn A key must be a string that identifies a feature property, or one of the following special keys: • "$type": the feature type. This key may be used with the "==", "!=", "in", and "!in" operators. Possible values are "Point", "LineString", and "Polygon". • "$id": the feature identifier. This key may be used with the "==", "!=", "has", "!has", "in", and "!in" operators. A value (and v0, . . . , vn for set operators) must be a String, Number, or Boolean to compare the property value against. Set membership filters are a compact and efficient way to test whether a field matches any of multiple values. The comparison and set membership filters implement strictlytyped comparisons; for example, all of the following evaluate to false: 0 < "1", 2 == "2", "true" in [true, false]. 6.6. MBStyle Styling 795 GeoServer User Manual, Release 2.15.1 The "all", "any", and "none" filter operators are used to create compound filters. The values f0, . . . , fn must be filter expressions themselves. ["==", "$type", "LineString"] This filter requires that the class property of each feature is equal to either “street_major”, “street_minor”, or “street_limited”. ["in", "class ,→", "street_major", "street_minor", "street_limited"] The combining filter “all” takes the three other filters that follow it and requires all of them to be true for a feature to be included: a feature must have a class equal to “street_limited”, its admin_level must be greater than or equal to 3, and its type cannot be Polygon. You could change the combining filter to “any” to allow features matching any of those criteria to be included - features that are Polygons, but have a different class value, and so on. [ "all", ["==", "class", "street_limited"], [">=", "admin_level", 3], ["!in", "$type", "Polygon"] ] Support basic functionality has/!has Mapbox >= 0.10.0 GeoTools >= 17.1 OpenLayers >= 2.4.0 >= 0.19.0 >= 17.1 >= 2.4.0 6.6.5 MBStyle Cookbook The MBStyle Cookbook is a collection of MBStyle “recipes” for creating various types of map styles. Wherever possible, each example is designed to show off a single MBStyle layer so that code can be copied from the examples and adapted when creating MBStyles of your own. While not an exhaustive reference like the MBStyle reference the MBStyle cookbook is designed to be a practical reference, showing common style templates that are easy to understand. The MBStyle Cookbook is divided into four sections: the first three for each of the vector types (points, lines, and polygons) and the fourth section for rasters to come. Each example in every section contains a screenshot showing actual GeoServer WMS output, a snippet of the MBStyle code for reference, and a link to download the full MBStyle. Each section uses data created especially for the MBStyle Cookbook, with shapefiles for vector data and GeoTIFFs for raster data. 796 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Data Type Point Line Polygon Shapefile mbstyle_cookbook_point.zip mbstyle_cookbook_line.zip mbstyle_cookbook_polygon.zip Points Points are seemingly the simplest type of shape, possessing only position and no other dimensions. MBStyle has a circle type that can be styled to represent a point. Example points layer The points layer used for the examples below contains name and population information for the major cities of a fictional country. For reference, the attribute table for the points in this layer is included below. fid (Feature ID) point.1 point.2 point.3 point.4 point.5 point.6 point.7 name (City name) Borfin Supox City Ruckis Thisland Synopolis San Glissando Detrania pop (Population) 157860 578231 98159 34879 24567 76024 205609 Download the points shapefile Simple point This example specifies points be styled as red circles with a diameter of 6 pixels. Fig. 6.269: Simple point 6.6. MBStyle Styling 797 GeoServer User Manual, Release 2.15.1 Code Download the "Simple point" MBStyle JSON { 1 "version": 8, "name": "point-circle-test", "layers": [ { "id": "point", "type": "circle", "paint": { "circle-radius": 3, "circle-color": "#FF0000", "circle-pitch-scale": "map" } } ] 2 3 4 5 6 7 8 9 10 11 12 13 14 } 15 Details There is one layer in this MBStyle, which is the simplest possible situation. The “version” must always be set to 8. Layers is required for any MBStyle as an array. “id” is required and is a unique name for that layer. For our examples we will be setting the “type” to “circle”. Simple point with stroke This example adds a stroke (or border) around the Simple point, with the stroke colored black and given a thickness of 2 pixels. Fig. 6.270: Simple point with stroke 798 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Code Download the "Simple point with stroke" MBStyle JSON { 1 "version": 8, "name": "point-circle-test", "layers": [ { "id": "point", "type": "circle", "paint": { "circle-radius": 3, "circle-color": "#FF0000", "circle-pitch-scale": "map", "circle-stroke-color": "#000000", "circle-stroke-width": 2 } } ] 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 } 17 Details This example is similar to the Simple point example. Lines 1213 specify the stroke, with line 12 setting the color to black ('#000000') and line 13 setting the width to 2 pixels. Lines While lines can also seem to be simple shapes, having length but no width, there are many options and tricks for making lines display nicely. Example lines layer The lines layer used in the examples below contains road information for a fictional country. For reference, the attribute table for the points in this layer is included below. 6.6. MBStyle Styling 799 GeoServer User Manual, Release 2.15.1 fid (Feature ID) line.1 line.2 line.3 line.4 line.5 line.6 line.7 line.8 line.9 line.10 line.11 line.12 line.13 line.14 line.15 line.16 line.17 line.18 line.19 line.20 line.21 line.22 line.23 line.24 line.25 name (Road name) Latway Crescent Avenue Forest Avenue Longway Saxer Avenue Ridge Avenue Holly Lane Mulberry Street Nathan Lane Central Street Lois Lane Rocky Road Fleet Street Diane Court Cedar Trail Victory Road Highland Road Easy Street Hill Street Country Road Main Street Jani Lane Shinbone Alley State Street River Road type (Road class) highway secondary secondary highway secondary secondary local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road local-road Download the lines shapefile Simple line This example specifies lines be colored black with a thickness of 3 pixels. Code Download the "Simple line" MBStyle { 1 "version": 8, "name": "simple-line", "layers": [ { "id": "simple-line", "type": "line", "paint": { "line-color": "#000000", "line-width": 3 } } 2 3 4 5 6 7 8 9 10 11 12 800 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.271: Simple line ] 13 } 14 Details There is one layer style for this MBStyle, which is the simplest possible situation. Styling lines is accomplished using the line layer. Line 9 specifies the color of the line to be black ("#000000"), while line 10 specifies the width of the lines to be 3 pixels. Line with border This example shows how to draw lines with borders (sometimes called “cased lines”). In this case the lines are drawn with a 3 pixel blue center and a 1 pixel wide gray border. Code Download the "Line with border" MBStyle { 1 "version": 8, "name": "simple-borderedline", "layers": [ { "id": "simple-borderedline", "type": "line", "layout": { 2 3 4 5 6 7 8 6.6. MBStyle Styling 801 GeoServer User Manual, Release 2.15.1 Fig. 6.272: Line with border "line-cap": "round" }, "paint": { "line-color": "#333333", "line-width": 5 } }, { "id": "simple-line", "type": "line", "layout": { "line-cap": "round" }, "paint": { "line-color": "#6699FF", "line-width": 3 } } 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ] 27 } 28 Details In this example we are drawing the lines twice to achieve the appearance of a line with a border. Since every line is drawn twice, the order of the rendering is very important. GeoServer renders layers in the order that they are presented in the MBStyle. In this style, the gray border lines are drawn first via the first layer style, followed by the blue center lines in a second layer style. This ensures that the blue lines are not obscured by the gray lines, and also ensures proper rendering at intersections, so that the blue lines “connect”. 802 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 In this example, lines 5-15 comprise the first layer style, which is the outer line (or “stroke”). Line 12 specifies the color of the line to be dark gray ("#333333"), line 13 specifies the width of this line to be 5 pixels, and in the layout line 9 a line-cap parameter of round renders the ends of the line as rounded instead of flat. (When working with bordered lines using a round line cap ensures that the border connects properly at the ends of the lines.) Lines 16-26 comprise the second layer, which is the the inner line (or “fill”). Line 23 specifies the color of the line to be a medium blue ("#6699FF"), line 24 specifies the width of this line to be 3 pixels, and in the layout line 20 again renders the edges of the line to be rounded instead of flat. The result is a 3 pixel blue line with a 1 pixel gray border, since the 5 pixel gray line will display 1 pixel on each side of the 3 pixel blue line. Dashed line This example alters the Simple line to create a dashed line consisting of 5 pixels of drawn line alternating with 2 pixels of blank space. Fig. 6.273: Dashed line Code Download the "Dashed line" MBStyle { 1 "version": 8, "name": "simple-dashedline", 2 3 6.6. MBStyle Styling 803 GeoServer User Manual, Release 2.15.1 "layers": [ { "id": "simple-dashedline", "type": "line", "paint": { "line-color": "#0000FF", "line-width": 3, "line-dasharray": [5, 2] } } ] 4 5 6 7 8 9 10 11 12 13 14 } 15 Details In this example, line 9 sets the color of the lines to be blue ("#0000FF") and line 10 sets the width of the lines to be 3 pixels. Line 11 determines the composition of the line dashes. The value of [5, 2] creates a repeating pattern of 5 pixels of drawn line, followed by 2 pixels of omitted line. Offset line This example alters the Simple line to add a perpendicular offset line on the left side of the line, at five pixels distance. Fig. 6.274: Dashed line 804 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Code Download the "Offset line" MBStlye { 1 "version": 8, "name": "simple-offsetline", "layers": [ { "id": "simple-line", "type": "line", "paint": { "line-color": "#000000", "line-width": 1 } }, { "id": "simple-offsetline", "type": "line", "paint": { "line-color": "#FF0000", "line-width": 1, "line-dasharray": [5, 2], "line-offset": 5 } } ] 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 } 24 Details In this example, lines 5-11 draw a simple black line like in the Simple line example. Lines 13-21 draw a red dashed line like in the above Dashed line example. Line 20 modifies the dashed line with a 5 pixel offset from the line geometry. Polygons Polygons are two dimensional shapes that contain both an outer stroke (or “outline”) and an inside (or “fill”). A polygon can be thought of as an irregularly-shaped point and is styled in similar ways to circles. Example polygons layer The polygons layer used below contains county information for a fictional country. For reference, the attribute table for the polygons is included below. 6.6. MBStyle Styling 805 GeoServer User Manual, Release 2.15.1 fid (Feature ID) polygon.1 polygon.2 polygon.3 polygon.4 polygon.5 polygon.6 polygon.7 polygon.8 name (County name) Irony County Tracker County Dracula County Poly County Bearing County Monte Cristo County Massive County Rhombus County pop (Population) 412234 235421 135022 1567879 201989 152734 67123 198029 Download the polygons shapefile Simple polygon This example shows a polygon filled in blue. Fig. 6.275: Simple polygon Code Download the "Simple polygon" MBStyle { 1 "version": 8, "name": "simple-polygon", "layers": [ { "id": "polygon", "type": "fill", "paint": { "fill-color": "#000080" 2 3 4 5 6 7 8 9 806 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 } 10 } 11 ] 12 } 13 Details There is one layer for this style, which is the simplest possible situation. Styling polygons is accomplished via the fill type (line 7). Line 9 specifies dark blue ('#000080') as the polygon’s fill color. Note: The light-colored outlines around the polygons in the figure are artifacts of the renderer caused by the polygons being adjacent. There is no outline in this style. Simple polygon with stroke This example adds a 1 pixel white outline to the Simple polygon example. Fig. 6.276: Simple polygon with stroke Code Download the "Simple polygon with stroke" MBStyle { 1 "version": 8, "name": "simple-polygon-outline", 2 3 6.6. MBStyle Styling 807 GeoServer User Manual, Release 2.15.1 "layers": [ { "id": "polygon-outline", "type": "fill", "paint": { "fill-outline-color": "#FFFFFF", "fill-color": "#000080" } } ] 4 5 6 7 8 9 10 11 12 13 } 14 Details This example is similar to the Simple polygon example above, with the addition of fill-outline paint parameter (line 9). Line 9 also sets the color of stroke to white ('#FFFFFF'), the "fill-outline-color" can only be 1 pixel, a limitation of MBStyle. Transparent polygon This example builds on the Simple polygon with stroke example and makes the fill partially transparent by setting the opacity to 50%. Fig. 6.277: Transparent polygon Code Download the "Transparent polygon" MBStyle 808 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 { 1 "version": 8, "name": "simple-polygon-transparent", "layers": [ { "id": "polygon-transparent", "type": "fill", "paint": { "fill-outline-color": "#FFFFFF", "fill-color": "#000080", "fill-opacity": 0.5 } } ] 2 3 4 5 6 7 8 9 10 11 12 13 14 } 15 Details This example is similar to the Simple polygon with stroke example, save for defining the fill’s opacity in line 11. The value of 0.5 results in partially transparent fill that is 50% opaque. An opacity value of 1 would draw the fill as 100% opaque, while an opacity value of 0 would result in a completely transparent (0% opaque) fill. In this example, since the background is white, the dark blue looks lighter. Were the fill imposed on a dark background, the resulting color would be darker. 6.7 Styling Workshop This workshop will explore how GeoServer styling can be used for a range of creative effects. This workshop also introduces both the CSS and YSLD extensions, which provide alternate styling languages to SLD. The following material will be covered in this workshop: Workshop Setup Workshop materials and setup Design Overview of map design (i.e. cartography) considerations. Select color palette with colorbrewer. CSS Styling Workbook Introduction to GeoServer styling followed by easy styling with the CSS module. YSLD Styling Workbook Introduction to GeoServer styling followed by easy styling with the YSLD module. MBStyle Styling Workbook Introduction to GeoServer styling followed by easy styling with the MBStyle module. 6.7.1 Workshop Setup Content: 6.7. Styling Workshop 809 GeoServer User Manual, Release 2.15.1 Extension Install This workshop course requires GeoServer with a few additional extensions. • CSS Styling: Quickly and easily generate SLD files • YSLD Styling: An alternative styling language to SLD • Importer: Wizard for bulk import of data On Windows the following is recommended: • FireFox • Notepad++ The CSS extension is distributed as a supported GeoServer extension. Extensions are unpacked into the libs folder of the GeoServer application. The YSLD extension is a new addition to geoserver and is distributed as an unsupported GeoServer extension. Note: In a classroom setting these extensions have already been installed. Manual Install To download and install the required extensions by hand: 1. Download geoserver-2.10-M0-css-plugin.zip and geoserver-2.10M0-css-plugin.zip from: • Development Release (GeoServer WebSite) It is important to download the version that matches the GeoServer you are running. 2. Download the geoserver-2.10-SNAPSHOT-ysld-plugin.zip from: • Community Builds (GeoServer WebSite) 3. Stop the GeoServer application. 4. Navigate into the webapps/geoserver/WEB-INF/lib folder. These files make up the running GeoServer application. 5. Unzip the contents of the three zip files into the lib folder. 6. Restart the Application Server. 7. Login to the Web Administration application. Select Styles from the naviagion menu. Click Create a new style and ensure both CSS and YSLD are available in the formats dropdown. Click Cancel to return to the Styles page without saving. 810 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Course Data Natural Earth The Natural Earth dataset is a free collection of vector and raster data published by the North American Cartographic Information Society to encourage mapping. For this course we will be using the Natural Earth cultural and physical vector layers backed by a raster shaded relief dataset. Fig. 6.278: Natural Earth The quickstart Natural Earth styling has been exported from QGIS and cleaned up in uDig for use in GeoServer. Digital Elevation Model A digital elevation model records height information for visualisation and analysis. We are using a dataset derived from the USGS GTOPO30 dataset. Fig. 6.279: Digital Elevation Model The GeoServer “dem” styling has been used for this dataset. Configuration Note: In a classroom setting GeoServer has been preconfigured with the appropriate data directory. To set up GeoServer yourself: 1. Download and unzip the following into your data directory: • styling-workshop-vector.zip • styling-workshop-raster.zip This will produce a raster and vector folder referenced in the following steps. Optional default SLD styles: • styling-workshop-sld.zip 6.7. Styling Workshop 811 GeoServer User Manual, Release 2.15.1 2. Use the Importer to add and publish the following TIF Coverage Stores: • dem/W100N40.TIF • ne/ne1/NE1_HR_LC_SR.tif the following directories of shape files: • ne/ne1/physical • ne/ne1/cultural 3. Cleaning up the published vector layers: • Layer names have been shortened for publication - the ne_10m_admin_1_states_provinces_lines_ship.shp is published named states_provinces_shp • Use EPSG:4326 as the spatial reference system • Optional: Appropriate SLD styles have been provided (from the uDig project) 4. To clean up the published raster layers: • The NE1 GeoTiff is styled with the default raster style • The usgs:dem GeoTiff is styled with the default DEM style 5. Optional: create a basemap group layer consisting of: This offers a combined layer, forming a cohesive base map. 812 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 6.7.2 Design This section introduces mapping as a tool for visual communication. Symbology In cartography, symbology is the practice of representing information using shapes, colors and symbols on a map. A map legend, offers a quick summary of the symbology used for a map. The symbology for each layer should be distinct, allowing readers to clearly understand the information being presented. Care should be taken to consider the situation in which the map will be used, such as: • Screen size of the output device • Ability of target device to reproduce color • Allowances for disabilities such as color blindness Theme For thematic maps, the symbology is changed on a feature-byfeature basis in order to illustrate the attribute values being presented. The same data set may be represented in different maps, themed by a different attribute each time. 6.7. Styling Workshop 813 GeoServer User Manual, Release 2.15.1 Using Multiple Themes A single map can be produced showing two datasets (each themed by a different attribute) allowing readers to look for any interesting patterns. As an example there may be a relationship between a country’s growing region and annual rainfall. Map Icons The use of map icons (pictograms, glyphs or symbology sets) is a special case where we have a gap in terminology between Cartography and GIS. As an example we may wish to represent a point-of-interest data set with each location marked by a different symbol. In cartography, each “type” is presented to the user as a clearly distinct data set with its own visual representation in the map legend. This is contrasted with GIS, where the “points of interest” are managed as a single layer and complex styling is used to produce the desired cartographic output. Technically the data set is themed by an attribute to produce this effect: • Often an attribute named type is introduced, and styling rules are used to associated each value with a distinct graphic mark. • Another common solution is to distribute the “symbology set” as TrueType font. A character attribute is introduced, the value of which is the appropriate letter to draw. Map Design The choice of how to present content is the subject of map design. Cartography, like any venue for design, is a human endeavor between art and science. In this exercise we are going to explore the trade offs in the use of color for effective communication. It is a challenge to explore cartography without getting stuck in the details of configuring style (which we will cover next). In order to side-step these details, we will be using a web application for this section: Color Brewer by Cynthia Brewer of Pennsylvania State University. Selection of an appropriate color palette is difficult, with a tension between what looks good and what can be understood. The research project that produced the color palettes used by Color Brewer was based on comprehension tests. 814 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 1. Navigate to: http://colorbrewer2.org/ The website provides a generic data set which we can use to determine how effective each choice is in communicating attribute differences. We will be using this website to explore how to effectively theme an attribute. Fig. 6.280: Color Brewer 2. The decisions we make when theming depend entirely on what point we are trying to communicate. In this scenario, we are going to communicate a vaccination schedule, county by county. Care should be taken to ensure each county appears equally important, and we should stay clear of red for anyone squeamish about needles. We need to ensure readers can quickly locate their county and look at the appropriate calendar entry. 3. The first step is determining how many attribute values you are looking to communicate. Set Number of data classes to 5. 4. Color brewer offers palettes using three different color schemes: 6.7. Styling Workshop 815 GeoServer User Manual, Release 2.15.1 Fig. 6.281: Number of data classes Sequential Diverging Qualitative The nature of our data is qualitative (each attribute value is attached an equal importance, and there is no implied order that wish to communicate with color). 5. Set Nature of your data to Qualitative. This change drastically reduces the number of color schemes listed. Fig. 6.282: Qualitative color scheme 6. The initial 5-class Accent color scheme does reasonably well. Fig. 6.283: 5-class accent 816 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 7. One of our requirements is to help readers locate their county. To assist with that let’s turn on roads and cities. Fig. 6.284: Adding context 8. The map is now starting to look a little busy: Fig. 6.285: Lots of context 9. Now that we have seen what we are up against, we can try a strategy to help the text and roads stand out while still communicating our vaccination schedule. Change to one of the pastel color schemes. Fig. 6.286: Pastel color scheme 10. Change the borders and roads to gray. 11. The result is fairly clear symbology and provides context. 12. Using our current “pastel” design, set the Number of data classes to 9. At values larger than this, the distinctions between colors becomes so subtle that readers will have trouble clearly distinguishing the content. 13. Make a note of these colors (we will be using them in the exercise on styling next). 6.7. Styling Workshop 817 GeoServer User Manual, Release 2.15.1 Fig. 6.287: Gray borders and roads Fig. 6.288: Finished with context Category 1 2 3 4 5 6 7 8 9 Color #fbb4ae #b3cde3 #ccebc5 #decbe4 #fed9a6 #ffffcc #e5d8bd #fddaec #f2f2f2 Bonus Finished early? While waiting take a moment to explore this topic in more detail, and if you are feeling creative there is a challenge to try. Note: In a classroom setting please divide the challenges between teams. This allows us to work through all the material in the time available. Explore Device Differences 1. Different output devices provide limitations in the amount of color information they can portray. 2. Explore: How does changing to a printed map affect the number of classes you can communicate using the current “pastel” approach? Explore Accessibility 818 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.289: Color palette 6.7. Styling Workshop 819 GeoServer User Manual, Release 2.15.1 1. Communication is a two way street, both in presenting information through design choices, and also perceiving information. Disabled readers will have a diminished ability to comprehend maps based on color. 2. Explore: What approach can be used to cater to color-blind map readers? Explore Color Choice 1. The Color Brewer application provides a lot of helpful information using the small “information” icons in each section. Fig. 6.290: Information icons 2. Explore: Using this information which color scheme would you choose for a digital elevation model? Challenge Adjusted Colour Scheme 1. Some datasets included a critical value or threshold that should be communicated clearly. 2. Challenge: How would you adjust a diverging color scheme to be suitable for a digital elevation model that includes bathymetry information (ocean depth)? Hint: For a target audience of humans sea-level would be considered a critical value. Style The design choices made to represent content is a key aspect of cartography. The style used when rendering data into a visualisation is the result of these choices. The Open Geospatial Consortium standard for recording style is divided into two parts: • Symbology Encoding (SE): Records a “feature type style” documenting how individual features are drawn using a series of rules. • Style Layer Descriptor (SLD): Records which “feature type styles” may be used with a layer. 820 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 The Symbology Encoding standard provides the terms we will be using to describe style: • Stroke: borders and outlines of shapes • Fill: interior of shapes Line symbolizer A line symbolizer documents how individual strokes are used to draw a line string, including color and line width. The SLD specification provides a default stroke used when drawing line strings. These values for color and width will be used if needed. GeoServer includes a default line.sld file providing a blue stroke. This file is used when you initially set up a linestring layer. From GeoServer’s line.sld style: #0000FF Polygon symbolizer A polygon symbolizer documents both the the stroke in addition to the fill used to draw a polygon. A fill can consist of a color, pattern, or other texture: The SLD specification provides a default gray fill, but does not supply a stroke. These values will be used if you do not provide an alternative. GeoServer includes a default polygon.sld file providing a gray fill and a black outline. This file will be used when you initially create a polygon layer. From GeoServer’s polygon.sld style: #AAAAAA #000000 1 6.7. Styling Workshop 821 GeoServer User Manual, Release 2.15.1 Point symbolizer A point symbolizer documents the “mark” used to represent a point. A mark may be defined by a glyph (icon) or a common mark (circle, square, etc.). The point symbolizer records the stroke and fill used to draw the mark. From GeoServer’s default point.sld style: square #FF0000 6 ,→ Text symbolizer A text symbolizer provides details on how labels are to be drawn, including font, size, and color information. From the populated_places.sld style: NAME Arial 10.0 normal bold 1 #FFFFFF 822 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 #000000 Note: The Style Layer Descriptor standard makes use of the Filter Encoding specification to create small expressions as shown above to access the NAME of each city: NAME This same approach can be used to dynamically generate any values needed for styling. Raster symbolizer A raster symbolizer provides a mapping from raster values to colors displayed. This can be provided by a color table, function, or directly mapping bands of data to use for the display channels. From GeoServer’s dem.sld style: 1.0 Note: This section uses Open Geospatial Consortium (OGC) terminology in our description of geometry and spatial data. While the terms we use here are general purpose, they may differ slightly from those you are familiar with. References: • Geographic Markup Language • OGC Reference Model (OGC Portal) • ISO 19107 Geographic information – Spatial schema (ISO) 6.7. Styling Workshop 823 GeoServer User Manual, Release 2.15.1 6.7.3 CSS Styling Workbook GeoServer styling can be used for a range of creative effects. This section introduces the CSS Extension which can be used to quickly generate SLD files. CSS Quickstart In the last section, we saw how the OGC defines style using XML documents (called SLD files). We will now explore GeoServer styling in greater detail using a tool to generate our SLD files. The Cascading Style Sheet (CSS) GeoServer extension is used to generate SLD files using a syntax more familiar to web developers. Using the CSS extension to define styles results in shorter examples that are easier to understand. At any point we will be able to review the generated SLD file. Syntax This section provides a quick introduction to CSS syntax for mapping professionals who may not be familiar with web design. Key properties As we work through CSS styling examples you will note the use of key properties. These properties are required to trigger the creation of an appropriate symbolizer in SLD. stroke fill mark label halo-radius Color (or graphic) for LineString or Polygon border Color (or graphic) for Polygon Fill Well-known Mark or graphic used for Point Text expression labeling Size of halo used to outline label Using just these key properties and the selector *, you will be able to visualize vector data. For example, here is the key property stroke providing a gray representation for line or polygon data: * { stroke: gray; } Here is the key property fill providing a blue fill for polygon data: * { fill: #2020ED; } 824 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Here is the key property mark showing the use of the well-known symbol square: * { mark: symbol(square); } Here is the key property label generating labels using the CITY_NAME feature attribute: * { label: [CITY_NAME]; } Here is the key property halo-radius providing an outline around generated label: * { label: [NAME]; halo-radius: 1; } Reference: • CSS Cookbook • CSS Examples Rules We have already seen a CSS style composed of a single rule: * { mark: symbol(circle); } We can also make a rule that only applies to a specific FeatureType: populated_places { mark: symbol(triangle); } We can make a style consisting of more than one rule, carefully choosing the selector for each rule. In this case we are using a selector to style capital cities with a star, and non-capital with a circle: [ FEATURECLA = 'Admin-0 capital' ] { mark: symbol(star); mark-size: 6px; } [ FEATURECLA <> 'Admin-0 capital' ] { mark: symbol(circle); mark-size: 6px; } 6.7. Styling Workshop 825 GeoServer User Manual, Release 2.15.1 The feature attribute test performed above uses Constraint Query Language (CQL). This syntax can be used to define filters to select content, similar to how the SQL WHERE statement is used. It can also be used to define expressions to access attribute values allowing their use when defining style properties. Rule selectors can also be triggered based on the state of the rendering engine. In this example we are only applying labels when zoomed in: [@scale < 20000000] { label: [ NAME ]; } In the above example the label is defined using the CQL Expression NAME. This results in a dynamic style that generates each label on a case-by-case basis, filling in the label with the feature attribute NAME. Reference: • Filter Syntax • ECQL Reference Cascading In the above example feature attribute selection we repeated information. An alternate approach is to make use of CSS Cascading and factor out common properties into a general rule: [ FEATURECLA = 'Admin-0 capital' ] { mark: symbol(star); } [ FEATURECLA <> 'Admin-0 capital' ] { mark: symbol(circle); } * { mark-size: 6px; } Pseudo-selector Up to this point we have been styling individual features, documenting how each shape is represented. When a shape is represented using a symbol, we have a second challenge: documenting the colors and appearance of the symbol. The CSS extension provides a pseudo-selector allowing further properties to be applied to a symbol. Example of using a pseudo-selector: * { mark: symbol(circle); 826 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 } :mark { fill: black; stroke: white; } In this example the :mark pseudo-selector is used select the circle mark, and provides a fill and stroke for use when rendering. Pseudo-selector :mark :stroke :fill :shield :symbol Use of symbol point markers stroke patterns fill patterns label shield any use The above pseudo-selectors apply to all symbols, but to be specific the syntax nth-symbol(1) can be used: * { mark: symbol(circle); } :nth-mark(1) { fill: black; stroke: white; } Reference: • Styled Marks (User Guide) Compare CSS to SLD The CSS extension is built with the same GeoServer rendering engine in mind, providing access to all the functionality of SLD (along with vendor options for fine control of labeling). The two approaches use slightly different terminology: SLD uses terms familiar to mapping professionals, CSS uses ideas familiar to web developers. SLD Style SLD makes use of a series of Rules to select content for display. Content is selected using filters that support attribute, spatial and temporal queries. Once selected, content is transformed into a shape and drawn using symbolizers. Symbolizers are configured using CSS Properties to document settings such as “fill” and “opacity”. Content can be drawn by more than one rule, allowing for a range of effects. 6.7. Styling Workshop 827 GeoServer User Manual, Release 2.15.1 Here is an example SLD file for reference: airports Airports airports Airports image/svg image/png ,→ triangle ,→ #000000 #FFFFFF 0.50 16 ,→ CSS Style CSS also makes use of rules, each rule making use of selectors to shortlist content for display. Each selector uses a CQL filter that 828 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 suports attribute, spatial and temporal queries. Once selected, CSS Properties are used to describe how content is rendered. Content is not drawn by more than one rule. When content satisfies the conditions of more than one rule the resulting properties are combined using a process called inheritance. This technique of having a generic rule that is refined for specific cases is where the Cascading in Cascading Style Sheet comes from. Here is an example using CSS: * { mark: url(airport.svg); mark-mime: "image/svg"; } In this rule the selector * is used to match all content. The rule defines properties indicating how this content is to be styled. The property mark is used to indicate we want this content drawn as a Point. The value url(airport.svg) is a URL reference to the image file used to represent each point. The mark-mime property indicates the expected format of this image file. Tour To confirm everything works, let’s reproduce the airports style above. 1. Navigate to the Styles page. 2. Each time we edit a style, the contents of the associated SLD file are replaced. Rather then disrupt any of our existing styles we will create a new style. Click Add a new style and choose the following: Name: Workspace: Format: airport0 (none specified) CSS 3. Replace the initial YSLD definition with with our airport CSS example and click Apply: * { mark: url(airport.svg); mark-mime: "image/svg"; } 4. Click the Layer Preview tab to preview the style. We want to preview on the aiports layer, so click the name of the current layer and select ne:airports from the list that appears. You can use the mouse buttons to pan and scroll wheel to change scale. 5. Click Layer Data for a summary of the selected data. 6.7. Styling Workshop 829 GeoServer User Manual, Release 2.15.1 Fig. 6.291: Choosing the airports layer Fig. 6.292: Layer preview 830 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.293: Layer attributes Bonus Finished early? For now please help your neighbour so we can proceed with the workshop. If you are really stuck please consider the following challenge rather than skipping ahead. Explore Data 1. Return to the Data tab and use the Compute link to determine the minimum and maximum for the scalerank attribute. Challenge Compare SLD Generation # The rest API can be used to review your CSS file directly. Browser: • view-source:http://localhost:8080/geoserver/rest/styles/airport0.css Command line: curl -v -u admin:geoserver -XGET http:/ ,→/localhost:8080/geoserver/rest/styles/airports0.css 1. The REST API can also be used generate an SLD file: Browser: • view-source:http://localhost:8080/geoserver/rest/styles/airport0.sld?pretty=true Command line: 6.7. Styling Workshop 831 GeoServer User Manual, Release 2.15.1 curl -v -u admin:geoserver -XGET http://localhost:8080/ ,→geoserver/rest/styles/airports0.sld?pretty=true 1. Compare the generated SLD differ above with the hand written SLD file used as an example? Challenge: What differences can you spot? Lines We will start our tour of CSS styling by looking at the representation of lines. Fig. 6.294: LineString Geometry Review of line symbology: • Lines are used to represent physical details that are too small to be represented at the current scale. Line work can also be used to model non-physical ideas such as network connectivity, or the boundary between land-use classifications. The visual width of lines do not change depending on scale. • Lines are recording as LineStrings or Curves depending on the geometry model used. • SLD uses a LineSymbolizer record how the shape of a line is drawn. The primary characteristic documented is the Stroke used to draw each segment between vertices. • Labeling of line work is anchored to the mid-point of the line. GeoServer provides an option to allow label rotation aligned with line segments. For our exercises we are going to be using simple CSS documents, often consisting of a single rule, in order to focus on the properties used for line symbology. Each exercise makes use of the ne:roads layer. Reference: • Line Symbology (User Manual | CSS Property Listing) • Lines (User Manual | CSS Cookbook) • LineString (User Manual | SLD Reference ) Stroke The only mandatory property for representation of linework is stroke. This is a key property; its presence triggers the generation of an appropriate LineSymbolizer. The use of stroke as a key property prevents CSS from having the idea of a default line color (as the stroke information must be supplied each time). 832 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Fig. 6.295: Basic Stroke Properties 1. Navigate to the CSS Styles page. 2. Click Choose a different layer and select ne:roads from the list. 3. Click Create a new style and choose the following: Workspace for new layer: New style name: No workspace line_example 4. Replace the generated CSS definition with the following stroke example: /* @title Line * @abstract Example line symbolization */ * { stroke: blue; } 5. Click Submit and then the Map tab for an initial preview. You can use this tab to follow along as the style is edited, it will refresh each time Submit is pressed. 6. You can look at the SLD tab at any time to see the generated SLD. Currently it is showing a straight forward LineSymbolizer generated from the CSS stroke property: Default Styler name Line ,→Example line symboloization #0000ff 6.7. Styling Workshop 833 GeoServer User Manual, Release 2.15.1 7. Additional properties cane be used fine-tune appearance. stroke-width to specify the width of the line. Use /* @title Line * @abstract Example line symbolization */ * { stroke: blue; stroke-width: 2px; } 8. The stroke-dasharray is used to define breaks rendering the line as a dot dash pattern. /* @title Line * @abstract Example line symbolization */ * { stroke: blue; stroke-width: 2px; stroke-dasharray: 5 2; } 9. Check the Map tab to preview the result. Note: The GeoServer rendering engine is quite sophisticated and allows the use of units of measure (such as m or ft). While we are using pixels in this example, real world units will be converted using the current scale. Z-Index The next exercise shows how to work around a limitation when using multiple strokes to render a line. Fig. 6.296: Use of Z-Index 1. Providing two strokes is often used to provide a contrasting edge (called casing) to thick line work. 834 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Update line_example with the following: * { stroke: black, #8080E6; stroke-width: 5px, 3px; } 2. If you look carefully you can see a problem with our initial attempt. The junctions of each line show that the casing outlines each line individually, making the lines appear randomly overlapped. Ideally we would like to control this process, only making use of this effect for overpasses. 3. The z-index parameter allows a draw order to be supplied. This time all the thick black lines are dawn first (at z-index 0) followed by the thinner blue lines (at z-index 1). * { stroke: black, #8080E6; stroke-width: 5px, 3px; z-index: 0, 1; } 4. If you look carefully you can see the difference. 5. By using z-index we have been able to simulate line casing. 6.7. Styling Workshop 835 GeoServer User Manual, Release 2.15.1 Label Our next example is significant as it introduces the how text labels are generated. Fig. 6.297: Use of Label Property This is also our first example making use of a dynamic style (where the value of a property is defined by an attribute from your data). 1. To enable LineString labeling we will need to use the key properties for both stroke and label. Update line_example with the following: * { stroke: blue; label: [name]; } 2. The SLD standard documents the default label position for each kind of Geometry. For LineStrings the initial label is positioned on the midway point of the line. 3. We have used an expression to calculate a property value for label. The label property is generated dynamically from the name attribute. Expressions are supplied within square brackets, making use of Constraint Query Language (CQL) syntax. * { stroke: blue; label: [name]; } 4. Additional properties can be supplied to fine-tune label presentation: * { stroke: blue; label: [name]; font-fill: black; 836 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 label-offset: 7px; } 5. The font-fill property is set to black provides the label color. * { stroke: blue; label: [name]; font-fill: black; label-offset: 7px; } 6. The label-offset property is used to adjust the starting position used for labeling. Normally the displacement offset is supplied using two numbers (allowing an x and y offset from the the midway point used for LineString labeling). When labeling a LineString there is a special twist: by specifying a single number for label-offset we can ask the rendering engine to position our label a set distance away from the LineString. * { stroke: blue; label: [name]; font-fill: black; label-offset: 7px; } 7. When used in this manner the rotation of the label will be adjusted automatically to match the LineString. How Labeling Works The rendering engine collects all the generated labels during the rendering of each layer. Then, during labeling, the engine sorts through the labels performing collision avoidance (to prevent labels overlapping). Finally the rendering engine draws the labels on top of the map. Even with collision avoidance you can spot areas where labels are so closely spaced that the result is hard to read. 6.7. Styling Workshop 837 GeoServer User Manual, Release 2.15.1 To take greater control over the GeoServer rendering engine we can use extra parameters. 1. The ability to take control of the labeling process is exactly the kind of hint a extra parameter is intended for. Update line_example with the following: * { stroke: blue; label: [name]; font-fill: black; label-offset: 7px; label-padding: 10; } 2. The parameter label-padding provides additional space around our label for use in collision avoidance. * { stroke: blue; label: [name]; font-fill: black; label-offset: 7px; label-padding: 10; } 3. Each label is now separated from its neighbor, improving legibility. Scale This section explores the use of attribute selectors and the @scale selector together to simplify the road dataset for display. 1. Replace the line_example CSS definition with: [scalerank < 4] { stroke: black; } 2. And use the Map tab to preview the result. 838 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 3. The scalerank attribute is provided by the Natural Earth dataset to allow control of the level of detail based on scale. Our selector shortlisted all content with scalerank 4 or lower, providing a nice quick preview when we are zoomed out. 4. In addition to testing feature attributes, selectors can also be used to check the state of the rendering engine. Replace your CSS with the following: [@scale > 35000000] { stroke: black; } [@scale < 35000000] { stroke: blue; } 5. As you adjust the scale in the Map preview (using the mouse scroll wheel) the color will change between black and blue. You can read the current scale in the bottom right corner, and the legend will change to reflect the current style. 6. Putting these two ideas together allows control of level detail based on scale: [@scale < 9000000] [scalerank > 7] { stroke: #888888; } [@scale < 17000000] [scalerank = 7] { stroke: #777777; } [@scale < 35000000] [scalerank = 6] { stroke: #444444; } [@scale ,→> 9000000] [@scale < 70000000] [scalerank = 5] { stroke: #000055; } [@scale < 9000000] [scalerank = 5] { stroke: #000055; stroke-width: 2 } [@scale > 35000000] [scalerank < 4] { stroke: black; } [@scale ,→> 9000000] [@scale <= 35000000] [scalerank < 4] { 6.7. Styling Workshop 839 GeoServer User Manual, Release 2.15.1 stroke: black; stroke-width: 2 } [@scale <= 9000000] [scalerank < 4] { stroke: black; stroke-width: 4 } 7. As shown above selectors can be combined in the same rule: • Selectors separated by whitespace are combined CQL Filter AND • Selectors separated by a comma are combined using CQL Filter OR Our first rule [@scale < 9000000] [scalerank > 7] checks that the scale is less than 9M AND scalerank is greater than 7. Bonus Finished early? Here are some opportunities to explore what we have learned, and extra challenges requiring creativity and research. In a classroom setting please divide the challenges between teams (this allows us to work through all the material in the time available). Explore Follow Line Option Options can be used to enable some quite useful effects, while still providing a style that can be used by other applications. 1. Update line_example with the following: * { stroke: #ededff; stroke-width: 10; label: [level] " " [name]; font-fill: black; label-follow-line: true; } 2. The property stroke-width has been used to make our line thicker in order to provide a backdrop for our label. * { stroke: #ededff; stroke-width: 10; label: [level] " " [name]; 840 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 font-fill: black; label-follow-line: true; } 3. The label property combines combine several CQL expressions together for a longer label. * { stroke: #ededff; stroke-width: 10; label: [level] " " [name]; font-fill: black; label-follow-line: true; } The combined label property: [level] " " [name] Is internally represented with the Concatenate function: [Concatenate(level,' #', name)] 4. The property label-follow-line provides the ability of have a label exactly follow a LineString character by character. * { stroke: #ededff; stroke-width: 10; label: [level] " " [name]; font-fill: black; label-follow-line: true; } 5. The result is a new appearance for our roads. Challenge SLD Generation 1. Generate the SLD for the following CSS. 6.7. Styling Workshop 841 GeoServer User Manual, Release 2.15.1 * { stroke: black; } What is unusual about the SLD code for this example? 2. Challenge: What is unusual about the generated SLD? Can you explain why it still works as expected? Note: Answer provided at the end of the workbook. Challenge Classification 1. The roads type attribute provides classification information. You can Layer Preview to inspect features to determine available values for type. 2. Challenge: Create a new style adjust road appearance based on type. Hint: The available values are ‘Major Highway’,’Secondary Highway’,’Road’ and ‘Unknown’. Note: Answer provided at the end of the workbook. Challenge SLD Z-Index Generation 1. Review the SLD generated by the z-index example. * { stroke: black, #8080E6; stroke-width: 5px, 3px; z-index: 0, 1; } 2. Challenge: There is an interesting trick in the generated SLD, can you explain how it works? Note: Answer provided at the end of the workbook. 842 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Challenge Label Shields 1. The traditional presentation of roads in the US is the use of a shield symbol, with the road number marked on top. 2. Challenge: Have a look at the documentation and reproduce this technique. Note: Answer provided at the end of the workbook. Polygons Next we look at how CSS styling can be used to represent polygons. Fig. 6.298: Polygon Geometry Review of polygon symbology: • Polygons offer a direct representation of physical extent or the output of analysis. • The visual appearance of polygons reflects the current scale. • Polygons are recorded as a LinearRing describing the polygon boundary. Further LinearRings can be used to describe any holes in the polygon if present. The Simple Feature for SQL Geometry model (used by GeoJSON) represents these areas as Polygons, the ISO 19107 geometry model (used by GML3) represents these areas as Surfaces. • SLD uses a PolygonSymbolizer to describe how the shape of a polygon is drawn. The primary characteristic documented is the Fill used to shade the polygon interior. The use of a Stroke to describe the polygon boundary is optional. • Labeling of a polygon is anchored to the centroid of the polygon. GeoServer provides a vendor option to allow labels to line wrap to remain within the polygon boundaries. 6.7. Styling Workshop 843 GeoServer User Manual, Release 2.15.1 For our Polygon exercises we will try and limit our CSS documents to a single rule, in order to showcase the properties used for rendering. Reference: • Polygon Symbology (User Manual | CSS Property Listing) • Polygons (User Manual | CSS Cookbook) • Polygons (User Manual | SLD Reference ) This exercise makes use of the ne:states_provinces_shp layer. 1. Navigate to Styles. 2. Create a new style polygon_example. Name: Workspace: Format: polygon_example No workspace CSS 3. Enter the following style and click :menuselection:Apply to save: * { fill: lightgrey; } 4. Click on the tab Layer Preview to preview. 5. Set ne:states_provinces_shp as the preview layer. Stroke and Fill The key property for polygon data is fill. 844 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 The fill property is used to provide the color, or pattern, used to draw the interior of a polygon. 1. Replace the contents of polygon_example with the following fill example: * { fill: gray; } 2. The Map tab can be used preview the change: 3. To draw the boundary of the polygon the stroke property is used: The stroke property is used to provide the color, or pattern, for the polygon boundary. It is effected by the same parameters (and vendor specific parameters) as used for LineStrings. * { fill: gray; stroke: black; stroke-width: 2; } Note: Technically the boundary of a polygon is a specific case of a LineString where the first and last vertex are the same, forming a closed LinearRing. 4. The effect of adding stroke is shown in the map preview: 5. An interesting technique when styling polygons in conjunction with background information is to control the fill opacity. The fill-opacity property is used to adjust transparency (provided as range from 0.0 to 1.0). Use of fill-opacity to render polygons works well in conjunction with a raster base map. This approach allows details of the base map to shown through. The stroke-opacity property is used in a similar fashion, as a range from 0.0 to 1.0. 6.7. Styling Workshop 845 GeoServer User Manual, Release 2.15.1 * { fill: white; fill-opacity: 50%; stroke: lightgrey; stroke-width: 0.25; stroke-opacity: 50%; } 6. As shown in the map preview: 7. This effect can be better appreciated using a layer group. Where the transparent polygons is used lighten the landscape provided by the base map. Pattern In addition to color, the fill property can also be used to provide a pattern. The fill pattern is defined by repeating one of the built-in symbols, or making use of an external image. 846 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 1. We have two options for configuring a fill with a repeating graphic: Using url to reference to an external graphic. Used in conjunction with fill-mime property. Use of symbol to access a predefined shape. SLD provides several well-known shapes (circle, square, triangle, arrow, cross, star, and x). GeoServer provides additional shapes specifically for use as fill patterns. Update polygon_example with the following built-in symbol as a repeating fill pattern: * { fill: symbol(square); } 2. The map preview (and legend) will show the result: 3. Add a black stroke: * { fill: symbol(square); stroke: black; } 4. To outline the individual shapes: 5. Additional fill properties allow control over the orientation and size of the symbol. The fill-size property is used to adjust the size of the symbol prior to use. The fill-rotation property is used to adjust the orientation of the symbol. Adjust the size and rotation as shown: 6.7. Styling Workshop 847 GeoServer User Manual, Release 2.15.1 * { fill: symbol(square); fill-size: 22px; fill-rotation: 45; stroke: black; } 6. The size of each symbol is increased, and each symbol rotated by 45 degrees. Note: Does the above look correct? There is an open request GEOT4642 to rotate the entire pattern, rather than each individual symbol. 7. The size and rotation properties just affect the size and placement of the symbol, but do not alter the symbol’s design. In order to control the color we need to make use of a pseudo-selector. We have two options for referencing to our symbol above: :symbol provides styling for all the symbols in the CSS document. :fill provides styling for all the fill symbols in the CSS document. 8. Replace the contents of polygon_example with the following: * { fill: symbol(square); } :fill { fill: green; stroke: darkgreen; } 9. This change adjusts the appearance of our grid of squares. 848 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 10. If you have more than one symbol: :nth-symbol(1) is used to specify which symbol in the document we wish to modify. :nth-fill(1) provides styling for the indicated fill symbol To rewrite our example to use this approach: * { fill: symbol(square); } :nth-fill(1) { fill: green; stroke: darkgreen; } 11. Since we only have one fill in our CSS document the map preview looks identical. 12. The well-known symbols are more suited for marking individual points. Now that we understand how a pattern can be controlled it is time to look at the patterns GeoServer provides. shape://horizline shape://vertline shape://backslash shape://slash shape://plus shape://times horizontal hatching vertical hatching right hatching pattern left hatching pattern vertical and horizontal hatching pattern cross hatch pattern Update the example to use shape://slash for a pattern of left hatching. * { fill: symbol('shape://slash'); stroke: black; } :fill { stroke: gray; } 13. This approach is well suited to printed output or low color devices. 6.7. Styling Workshop 849 GeoServer User Manual, Release 2.15.1 14. To control the size of the symbol produced use the fill-size property. * { fill: symbol('shape://slash'); fill-size: 8; stroke: black; } :fill { stroke: green; } 15. This results in a tighter pattern shown: 16. Another approach (producing the same result is to use the size property on the appropriate pseudo-selector. * { fill: symbol('shape://slash'); stroke: black; } :fill { stroke: green; size: 8; } 17. This produces the same visual result: 18. Multiple fills can be combined by supplying more than one fill as 850 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 part of the same rule. Note the use of a comma to separate fill-size values (including the first fill-size value which is empty). This was the same approach used when combining strokes. * { fill: #DDDDFF, symbol('shape://slash'); fill-size: '','8'; stroke: black; } :fill { stroke: black; stroke-width: 0.5; } 19. The resulting image has a solid fill, with a pattern drawn overtop. Label Labeling polygons follows the same approach used for LineStrings. The key properties fill and label are used to enable Polygon label generation. 1. By default labels are drawn starting at the centroid of each polygon. 2. Try out label and fill together by replacing our polygon_example with the following: * { stroke: blue; fill: #7EB5D3; label: [name]; font-fill: black; } 3. Each label is drawn from the lower-left corner as shown in the Map preview. 6.7. Styling Workshop 851 GeoServer User Manual, Release 2.15.1 4. We can adjust how the label is drawn at the polygon centroid. The property label-anchor provides two numbers expressing how a label is aligned with respect to the centroid. The first value controls the horizontal alignment, while the second value controls the vertical alignment. Alignment is expressed between 0.0 and 1.0 as shown in the following table. Top Middle Bottom Left 0.0 1.0 0.0 0.5 0.0 0.0 Center 0.5 1.0 0.5 0.5 0.5 0.0 Right 1.0 1.0 1.0 0.5 1.0 0.0 Adjusting the label-anchor is the recommended approach to positioning your labels. 5. Using the label-anchor property we can center our labels with respect to geometry centroid. To align the center of our label we select 50% horizontally and 50% vertically, by filling in 0.5 and 0.5 below: * { stroke: blue; fill: #7EB5D3; label: [name]; font-fill: black; label-anchor: 0.5 0.5; } 6. The labeling position remains at the polygon centroid. We adjust alignment by controlling which part of the label we are “snapping” into position. 7. The property label-offset can be used to provide an initial displacement using and x and y offset. 8. This offset is used to adjust the label position relative to the geometry centroid resulting in the starting label position. 852 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 * { stroke: blue; fill: #7EB5D3; label: [name]; font-fill: black; label-offset: 0 7; } 9. Confirm this result in the map preview. 10. These two settings can be used together. The rendering engine starts by determining the label position generated from the geometry centroid and the label-offset displacement. The bounding box of the label is used with the label-anchor setting align the label to this location. Step 1: starting label position = centroid + displacement Step 2: snap the label anchor to the starting label position 11. To move our labels down (allowing readers to focus on each shape) we can use displacement combined with followed by horizontal alignment. * { stroke: blue; fill: #7EB5D3; label: [name]; font-fill: black; label-anchor: 0.5 1; label-offset: 0 -7; } 12. As shown in the map preview. 6.7. Styling Workshop 853 GeoServer User Manual, Release 2.15.1 Legibility When working with labels a map can become busy very quickly, and difficult to read. 1. GeoServer provides extensive vendor parameters directly controlling the labelling process. Many of these parameters focus on controlling conflict resolution (when labels would otherwise overlap). 2. Two common properties for controlling labeling are: label-max-displacement indicates the maximum distance GeoServer should displace a label during conflict resolution. label-auto-wrap allows any labels extending past the provided width will be wrapped into multiple lines. 3. Using these together we can make a small improvement in our example: * { stroke: blue; fill: #7EB5D3; label: [name]; font-fill: black; label-anchor: 0.5 0.5; label-max-displacement: 40; label-auto-wrap: 70; } 4. As shown in the following preview. 854 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 5. Even with this improved spacing between labels, it is difficult to read the result against the complicated line work. Use of a halo to outline labels allows the text to stand out from an otherwise busy background. In this case we will make use of the fill color, to provide some space around our labels. We will also change the font to Arial. * { stroke: blue; fill: #7EB5D3; label: [name]; label-anchor: 0.5 0.5; font-fill: black; font-family: "Arial"; font-size: 14; halo-radius: 2; halo-color: #7EB5D3; halo-opacity:0.8; label-max-displacement: 40; label-auto-wrap: 70; } 6. By making use of halo-opacity we we still allow stroke information to show through, but prevent the stroke information from making the text hard to read. 7. And advanced technique for manually taking control of conflict resolution is the use of the label-priority. This property takes an expression which is used in the event of a conflict. The label with the highest priority “wins.” 8. The Natural Earth dataset we are using includes a labelrank intended to control what labels are displayed based on zoom level. The values for labelrank go from 0 (for zoomed out) to 20 (for 6.7. Styling Workshop 855 GeoServer User Manual, Release 2.15.1 zoomed in). To use this value for label-priority we need to swap the values around so a scalerank of 1 is given the highest priority. * { stroke: blue; fill: #7EB5D3; label: [name]; label-anchor: 0.5 0.5; font-fill: black; font-family: "Arial"; font-size: 14; halo-radius: 2; halo-color: #7EB5D3; halo-opacity:0.8; label-max-displacement: 40; label-auto-wrap: 70; label-priority: [20-labelrank]; } 9. In the following map East Flanders will take priority over Zeeland when the two labels overlap. Theme A thematic map (rather than focusing on representing the shape of the world) uses elements of style to illustrate differences in the data under study. This section is a little more advanced and we will take the time to look at the generated SLD file. 1. We can use a site like ColorBrewer to explore the use of color theming for polygon symbology. In this approach the the fill color of the polygon is determined by the value of the attribute under study. This presentation of a dataset is known as “theming” by an attribute. 2. For our ne:states_provinces_shp dataset, a mapcolor9 attribute has been provided for this purpose. Theming by mapcolor9 results in a map where neighbouring countries are visually distinct. 856 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Qualitative 9-class Set3 #8dd3c7 #fb8072 #b3de69 #ffffb3 #80b1d3 #fccde5 #bebada #fdb462 #d9d9d9 If you are unfamiliar with theming you may wish to visit http:// colorbrewer2.org to learn more. The i icons provide an adequate background on theming approaches for qualitative, sequential and diverging datasets. 3. The first approach we will take is to directly select content based on colormap, providing a color based on the 9-class Set3 palette above: [mapcolor9=1] { fill: #8dd3c7; } [mapcolor9=2] { fill: #ffffb3; } [mapcolor9=3] { fill: #bebada; } [mapcolor9=4] { fill: #fb8072; } [mapcolor9=5] { fill: #80b1d3; } [mapcolor9=6] { fill: #fdb462; } [mapcolor9=7] { fill: #b3de69; } [mapcolor9=8] { fill: #fccde5; } [mapcolor9=9] { fill: #d9d9d9; } * { stroke: gray; stroke-width: 0.5; } 4. The Map tab can be used to preview this result. 5. This CSS makes use of cascading to avoid repeating the stroke and stroke-width information multiple times. 6.7. Styling Workshop 857 GeoServer User Manual, Release 2.15.1 As an example the mapcolor9=2 rule, combined with the * rule results in the following collection of properties: [mapcolor9=2] { fill: #ffffb3; stroke: gray; stroke-width: 0.5; } 6. Reviewing the generated SLD shows us this representation: mapcolor9 2 #ffffb3 #808080 0.5 7. There are three important functions, defined by the Symbology Encoding specification, that are often easier to use for theming than using rules. • Recode: Used the theme qualitative data. Attribute values are directly mapped to styling property such as fill or stroke-width. • Categorize: Used the theme quantitative data. Categories are defined using min and max ranges, and values are sorted into the appropriate category. • Interpolate: Used to smoothly theme quantitative data by calculating a styling property based on an attribute value. Theming is an activity, producing a visual result allow map readers to learn more about how an attribute is distributed spatially. We are free to produce this visual in the most efficient way possible. 8. Swap out mapcolor9 theme to use the Recode function: * { fill:[ recode(mapcolor9, 1,'#8dd3c7', 2,'#ffffb3', 3,'#bebada', 4,'#fb8072', 5,'#80b1d3', 6,'#fdb462', 7,'#b3de69', 8,'#fccde5', 9,'#d9d9d9') 858 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 ]; stroke: gray; stroke-width: 0.5; } 9. The Map tab provides the same preview. 10. The Generated SLD tab shows where things get interesting. Our generated style now consists of a single Rule: mapcolor9 1 #8dd3c7 2 #ffffb3 3 #bebada 4 #fb8072 5 #80b1d3 6 #fdb462 7 #b3de69 8 #fccde5 9 #d9d9d9 #808080 0.5 ,→ 6.7. Styling Workshop 859 GeoServer User Manual, Release 2.15.1 Bonus The following optional explore and challenge activities offer a chance to review and apply the ideas introduced here. The challenge activities equire a bit of creativity and research to complete. In a classroom setting you are encouraged to team up into groups, with each group taking on a different challenge. Explore Antialiasing 1. When we rendered our initial preview, without a stroke, thin white gaps (or slivers) are visible between our polygons. This effect is made more pronounced by the rendering engine making use of the Java 2D sub-pixel accuracy. This technique is primarily used to prevent an aliased (stair-stepped) appearance on diagonal lines. 2. Clients can turn this feature off using a GetMap format option: format_options=antialiasing=off; The LayerPreview provides access to this setting from the Open Layers Options Toolbar: 3. Explore: Experiment with fill and stroke settings to eliminate slivers between polygons. Note: Answer provided at the end of the workbook. Explore Categorize 860 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 1. The Categorize function can be used to generate property values based on quantitative information. Here is an example using Categorize to color states according to size. * { fill: [ Categorize(Shape_Area, '#08519c', 0.5, '#3182bd', 1, '#6baed6', 5, '#9ecae1', 60, '#c6dbef', 80, '#eff3ff') ]; } 2. An exciting use of the GeoServer shape symbols is the theming by changing the fill-size used for pattern density. 3. Explore: Use the Categorize function to theme by datarank. Note: Answer provided at the end of the workbook. Challenge Goodness of Fit 1. A subject we touched on during labeling was the conflict resolution GeoServer performs to ensure labels do not overlap. 2. In addition to the vendor parameter for max displacement you can experiment with different values for “goodness of fit”. These settings control how far GeoServer is willing to move a label to avoid conflict, and under what terms it simply gives up: label-fit-goodness: 0.3; label-max-displacement: 130; 3. You can also experiment with turning off this facility completely: label-conflict-resolution: false; 6.7. Styling Workshop 861 GeoServer User Manual, Release 2.15.1 4. Challenge: Construct your own example using max displacement and fit-goodness. Challenge Halo 1. The halo example used the fill color and opacity for a muted halo, while this improved readability it did not bring attention to our labels. A common design choice for emphasis is to outline the text in a contrasting color. 2. Challenge: Produce a map that uses a white halo around black text. Note: Answer provided at the end of the workbook. Challenge Theming using Multiple Attributes 1. A powerful tool is theming using multiple attributes. This is an important concept allowing map readers to perform “integration by eyeball” (detecting correlations between attribute values information). 2. Challenge: Combine the mapcolor9 and datarank examples to reproduce the following map. Note: Answer provided at the end of the workbook. Challenge Use of Z-Index 1. Earlier we looked at using z-index to simulate line string casing. The line work was drawn twice, once with thick line, and then a second time with a thinner line. The resulting effect is similar to text halos providing breathing space around complex line work allowing it to stand out. 2. Challenge: Use what you know of LineString z-index to reproduce the following map: 862 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Note: Answer provided at the end of the workbook. Points The next stop of the CSS styling tour is the representation of points. Review of point symbology: • Points are used to represent a location only, and do not form a shape. The visual width of lines do not change depending on scale. • SLD uses a PointSymbolizer record how the shape of a line is drawn. • Labeling of points is anchored to the point location. As points have no inherent shape of of their own, emphasis is placed on marking locations with an appropriate symbol. Reference: • Point Symbology (User Manual | CSS Property Listing) • Points (User Manual | CSS Cookbook) • Styled Marks (User Manual | CSS Styling ) • Point (User Manual | SLD Reference ) This exercise makes use of the ne:populated_places layer. 1. Navigate to the Styles page. 2. Click Add a new style and choose the following: Name: Workspace: Format: point_example No workspace CSS 3. Replace the initial CSS definition with the following and click apply: 6.7. Styling Workshop 863 GeoServer User Manual, Release 2.15.1 * { mark: symbol(circle); } 4. And use the Layer Preview tab to preview the result. Mark Points are represented with the mandatory property mark. The SLD standard provides “well-known” symbols for use with point symbology: circle, square, triangle, arrow, cross, star, and x. 1. As a key property the presence mark triggers the generation of an appropriate PointSymbolizer. * { mark: symbol(square); } 2. Map Preview: 3. Before we continue we will use a selector to cut down the amount of data shown to a reasonable level. 864 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 [ SCALERANK < 1 ] { mark: symbol(square); } 4. Resulting in a considerably cleaner image: 5. Additional properties are available to control a mark’s presentation: The mark-size property is used to control symbol size. The mark-rotation property controls orientation, accepting input in degrees. Trying these two settings together: [ SCALERANK < 1 ] { mark: symbol(square); mark-size: 8; mark-rotation: 45; } 6. Results in each location being marked with a diamond: 7. Now that we have assigned our point location a symbol we can make use of a pseudo-selector to style the resulting shape. :symbol - provides styling for all the symbols in the CSS document. :mark - provides styling for all the mark symbols in the CSS document. 6.7. Styling Workshop 865 GeoServer User Manual, Release 2.15.1 This form of pseudo-selector is used for all marks: [ SCALERANK < 1 ] { mark: symbol(square); mark-size: 8; mark-rotation: 45; } :mark{ fill: white; stroke: black; } 8. Updating the mark to a white square with a black outline. 9. The second approach is used to individual configure symbols in the same document. :nth-symbol(1) - if needed we could specify which symbol in the document we wish to modify. :nth-mark(1) - provides styling for the first mark symbol in the CSS document. Using this approach marks can be composed of multiple symbols, each with its own settings: [ SCALERANK < 1 ] { mark: symbol(square),symbol(cross); mark-size: 16,14; mark-rotation: 0,45; } :nth-mark(1){ fill: red; stroke: black; } :nth-mark(2){ fill: black; stroke: white; } 10. Producing an interesting compound symbol effect: 866 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Graphic Symbols can also be supplied by an external graphic, This technique was shown with the initial file:airport.svg CSS example. 1. To use an external graphic two pieces of information are required. mark property is defined with a url reference to image. mark-mime property is used to tell the rendering engine what file format to expect This technique is used to reference files placed in the styles directory. [ SCALERANK < 1 ] { mark: url(port.svg); mark-mime: "image/svg"; } 2. Drawing the provided shape in each location: 3. The mark property url reference can also be used to reference external images. We can make use of the GeoServer logo. 6.7. Styling Workshop 867 GeoServer User Manual, Release 2.15.1 [ SCALERANK < 1 ] { mark: url( ,→"http://localhost:8080/geoserver/web/wicket/resource/ ,→org.geoserver.web.GeoServerBasePage/img/logo.png"); mark-mime: "image/png"; mark-size: 16; } 4. As shown in the map preview. Label Labeling is now familiar from our experience with LineString and Polygons. The key properties mark and label are required to label Point locations. 1. Replace point_example with the following: [ SCALERANK < 1 ] { mark: symbol(circle); label: [NAME]; } 2. Confirm the result in Map preview. 868 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 3. Each label is drawn starting from the provided point - which is unfortunate as it assures each label will overlap with the symbol used. To fix this limitation we will make use of the SLD controls for label placement: label-anchor provides two values expressing how a label is aligned with respect to the starting label position. label-offset is be used to provide an initial displacement using and x and y offset. For points this offset is recommended to adjust the label position away for the area used by the symbol. Note: The property label-anchor defines an anchor position relative to the bounding box formed by the resulting label. This anchor position is snapped to the label position generated by the point location and displacement offset. 4. Using these two facilities together we can center our labels below the symbol, taking care that the displacement used provides an offset just outside the area required for the symbol size. [ SCALERANK < 1 ] { mark: symbol(circle); mark-size: 10; label: [NAME]; label-offset: 0 -12; label-anchor: 0.5 1.0; font-fill: black; } 5. Each label is now placed under the mark. 6.7. Styling Workshop 869 GeoServer User Manual, Release 2.15.1 6. One remaining issue is the overlap between labels and symbols. GeoServer provides a vendor specific parameter to allow symbols to take part in label conflict resolution, preventing labels from overlapping any symbols. This severely limits the area available for labeling and is best used in conjunction with a large maximum displacement vendor option. mark-label-obstacle vendor parameter asks the rendering engine to avoid drawing labels over top of the indicated symbol. label-max-displacement vendor parameter provides the rendering engine a maximum distance it is allowed to move labels during conflict resolution. label-padding vendor parameter tells the rendering engine to provide a minimum distance between the labels on the map, ensuring they do not overlap. Update our example to use these settings: [ SCALERANK < 1 ] { mark: symbol(circle); mark-size: 10; label: [NAME]; label-offset: 0 -12; label-anchor: 0.5 1.0; font-fill: black; mark-label-obstacle: true; label-max-displacement: 100; label-padding: 2; } 7. Resulting in a considerably cleaner image: 870 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Dynamic Styling 1. We will quickly use scalerank to select content based on @scale selectors. [@scale < 4000000] { mark: symbol(circle); } [@scale > 4000000] [@scale < 8000000] [SCALERANK < 7] { mark: symbol(circle); } [@scale ,→> 8000000] [@scale < 17000000] [SCALERANK < 5] { mark: symbol(circle); } [@scale ,→> 17000000] [@scale < 35000000] [SCALERANK < 4] { mark: symbol(circle); } [@scale ,→> 35000000] [@scale < 70000000][SCALERANK < 3] { mark: symbol(circle); } [@scale ,→> 70000000] [@scale < 140000000][SCALERANK < 2] { mark: symbol(circle); } [@scale > 140000000] [SCALERANK < 1] { mark: symbol(circle); } * { mark-size: 6; } 2. Click Submit to update the Map after each step. 6.7. Styling Workshop 871 GeoServer User Manual, Release 2.15.1 3. To add labeling we must use both the key properties mark and label in each scale selector, using rule cascading to define the mark-size and font information once. [@scale < 4000000] { mark: symbol(circle); label: [NAME]; } [@scale > 4000000] [@scale < 8000000] [SCALERANK < 7] { mark: symbol(circle); label: [NAME]; } [@scale ,→> 8000000] [@scale < 17000000] [SCALERANK < 5] { mark: symbol(circle); label: [NAME]; } [@scale ,→> 17000000] [@scale < 35000000] [SCALERANK < 4] { mark: symbol(circle); label: [NAME]; } [@scale ,→> 35000000] [@scale < 70000000][SCALERANK < 3] { mark: symbol(circle); label: [NAME]; } [@scale ,→> 70000000] [@scale < 140000000][SCALERANK < 2] { mark: symbol(circle); label: [NAME]; } [@scale > 140000000] [SCALERANK < 1] { mark: symbol(circle); label: [NAME]; } * { mark-size: 6; 872 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 font-fill: black; font-family: "Arial"; font-size: 10; } 4. We will use label-offset and label-anchor to position the label above each symbol. Add the following two lines to the * selector: * { mark-size: 6; font-fill: black; font-family: "Arial"; font-size: 10; label-anchor: 0.5 0; label-offset: 0 6; } 5. A little bit of work with vendor specific parameters will prevent our labels from colliding with each symbol, while giving the rendering engine some flexibility in how far it is allowed to relocate a label. Add the following vendor options to the * selector: 6.7. Styling Workshop 873 GeoServer User Manual, Release 2.15.1 * { mark-size: 6; font-fill: black; font-family: "Arial"; font-size: 10; label-anchor: 0.5 0; label-offset: 0 6; mark-label-obstacle: true; label-max-displacement: 90; label-padding: 2; } 6. Now that we have clearly labeled our cities, zoom into an area you are familiar with and we can look at changing symbology on a caseby-case basis. We have used expressions previous to generate an appropriate label. Expressions can also be used for many other property settings. The ne:populated_places layer provides several attributes specifically to make styling easier: • SCALERANK: we have already used this attribute to control the level of detail displayed • LABELRANK: hint used for conflict resolution, allowing important cities such as capitals to be labeled even when they are close to a larger neighbor. • FEATURECLA: used to indicate different types of cities. We will check for Admin-0 capital cities. The first thing we will do is calculate the mark-size using a quick expression: [10-(SCALERANK/2)] This expression should result in sizes between 5 and 9 and will need to be applied to both mark-size and label-offset. Rather than the “first come first served” default to resolve labeling conflicts we can manually provide GeoServer with a label priority. 874 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 The expression provided is calculated for each label, in the event of a conflict the label with the highest priority takes precedence. The LABELRANK attribute goes from 1 through 10 and needs to be flipped around before use as a GeoServer label priority: [10 - LABELRANK] This expression will result in values between 0 and 10 and will be used for the label-priority. * { mark-size: [10-(SCALERANK/2)]; font-fill: black; font-family: "Arial"; font-size: 10; label-anchor: 0.5 0; label-offset: 0 [10-(SCALERANK/2)]; mark-label-obstacle: true; label-max-displacement: 90; label-padding: 2; label-priority: [10 - LABELRANK]; } 7. Next we can use FEATURECLA to check for capital cities. Adding a selector for capital cities at the top of the file: /* capitals */ [@scale < 70000000] [FEATURECLA = 'Admin-0 capital'] { mark: symbol(star); label: [NAME]; } [@scale > 70000000] [SCALERANK < 2] [FEATURECLA = 'Admin-0 capital'] { mark: symbol(star); label: [NAME]; } And updating the populated places selectors to ignore capital cities: 6.7. Styling Workshop 875 GeoServer User Manual, Release 2.15.1 /* populated places */ [@scale < 4000000] [FEATURECLA <> 'Admin-0 capital'] { mark: symbol(circle); label: [NAME]; } [@scale > 4000000] [@scale < 8000000] [SCALERANK < 7] [FEATURECLA <> 'Admin-0 capital'] { mark: symbol(circle); label: [NAME]; } [@scale > 8000000] [@scale < 17000000] [SCALERANK < 5] [FEATURECLA <> 'Admin-0 capital'] { mark: symbol(circle); label: [NAME]; } [@scale > 17000000] [@scale < 35000000] [SCALERANK < 4] [FEATURECLA <> 'Admin-0 capital'] { mark: symbol(circle); label: [NAME]; } [@scale > 35000000] [@scale < 70000000][SCALERANK < 3] [FEATURECLA <> 'Admin-0 capital'] { mark: symbol(circle); label: [NAME]; } [@scale > 70000000] [@scale < 140000000][SCALERANK < 2] [FEATURECLA <> 'Admin-0 capital'] { mark: symbol(circle); label: [NAME]; } [@scale > 140000000] [SCALERANK < 1] [FEATURECLA <> 'Admin-0 capital'] { mark: symbol(circle); label: [NAME]; } 8. Finally we can fill in the capital city symbols using a combination 876 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 of a selector to detect capital cities, and pseudo selector to provide mark styling. [FEATURECLA = 'Admin-0 capital'] :mark { fill: black; } :symbol { fill: gray; stroke: black; } 9. If you would like to check your work the final file is here: point_example.css Bonus Challenge Geometry Location 1. The mark property can be used to render any geometry content. 2. Challenge: Try this yourself by rendering a polygon layer using a mark property. Note: Answer discussed at the end of the workbook. Explore Dynamic Symbolization 1. We went to a lot of work to set up selectors to choose between symbol(star) and symbol(circle) for capital cities. This approach is straightforward when applied in isolation: [FEATURECLA = 'Admin-0 capital'] { mark: symbol(star); } [FEATURECLA <> 'Admin-0 capital'] { mark: symbol(circle); } 6.7. Styling Workshop 877 GeoServer User Manual, Release 2.15.1 When combined with checking another attribute, or checking @scale as in our example, this approach can quickly lead to many rules which can be difficult to keep straight. 2. Taking a closer look both symbol() and url() can actually be expressed using a string: [FEATURECLA = 'Admin-0 capital'] { mark: symbol("star"); } Which is represented in SLD as: star 3. GeoServer recognizes this limitation of SLD Mark and ExternalGraphic and provides an opportunity for dynamic symbolization. This is accomplished by embedding a small CQL expression in the string passed to symbol or url. This sub-expression is isolated with ${ } as shown: * { mark: symbol( "${if_then_else(equalTo(FEATURECLA, ,→'Admin-0 capital'),'star','circle')}" ); } Which is represented in SLD as: ,→${if_then_else(equalTo(FEATURECLA,'Admin,→0 capital'),'star','circle')} 4. Challenge: Use this approach to rewrite the Dynamic Styling example. Note: Answer provided at the end of the workbook. 878 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Challenge Layer Group 1. Use a Layer Group to explore how symbology works together to form a map. • ne:NE1 • ne:states_provincces_shp • ne: populated_places 2. To help start things out ne:states_provinces_shp: here is a style for * { fill: white,[ recode(mapcolor9, 1,'#8dd3c7', 2,'#ffffb3', 3,'#bebada', 4,'#fb8072', 5,'#80b1d3', 6,'#fdb462', 7,'#b3de69', 8,'#fccde5', 9,'#d9d9d9') ]; fill-opacity: 05%,50%; stroke: black; stroke-width: 0.25; stroke-opacity: 50%; } 3. This background is relatively busy and care must be taken to ensure both symbols and labels are clearly visible. 4. Challenge: Do your best to style populated_places over this busy background. Here is an example with labels for inspiration: Note: Answer provided at the end of the workbook. 6.7. Styling Workshop 879 GeoServer User Manual, Release 2.15.1 Explore True Type Fonts 1. In addition to image formats GeoServer can make use other kinds of graphics, such as True Type fonts: * { mark: symbol("ttf://Webdings#0x0064"); } :mark { stroke: blue; } 2. Additional fonts dropped in the styles directory are available for use. Explore Custom Graphics 1. The GeoServer rendering engine allows Java developers to hook in additional symbol support. This facility is used by GeoServer to offer the shapes used for pattern fills. Community extensions allow the use of simple custom shapes and even charts. 2. Support has been added for custom grpahics using the WKT Geometry representation. * { mark: symbol("wkt://MULTILINESTRING((-0.25 ,→-0.25, -0.125 -0.25), (0.125 -0.25, 0.25 -0.25), (,→0.25 0.25, -0.125 0.25), (0.125 0.25, 0.25 0.25))"); } :mark { stroke: blue; } Rasters Finally we will look at using CSS styling for the portrayal of raster data. Fig. 6.299: Raster Symbology Review of raster symbology: • Raster data is Grid Coverage where values have been recorded in a regular array. In OGC terms a Coverage can be used to look up a value or measurement for each location. • When queried with a “sample” location: – A grid coverage can determine the appropriate array location and retrieve a value. Different techniques may be used interpolate an 880 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 appropriate value from several measurements (higher quality) or directly return the “nearest neighbor” (faster). – A vector coverages would use a point-in-polygon check and return an appropriate attribute value. – A scientific model can calculate a value for each sample location • Many raster formats organize information into bands of content. Values recorded in these bands and may be mapped into colors for display (a process similar to theming an attribute for vector data). For imagery the raster data is already formed into red, green and blue bands for display. • As raster data has no inherent shape, the format is responsible for describing the orientation and location of the grid used to record measurements. These raster examples use a digital elevation model consisting of a single band of height measurements. The imagery examples use an RGB image that has been hand coloured for use as a base map. Reference: • Raster Symbology (User Manual | CSS Property Listing ) • Rasters (User Manual | CSS Cookbook ); • Point (User Manual | SLD Reference ) The exercise makes use of the usgs:dem and ne:ne1 layers. Image The raster-channels is the key property for display of images and raster data. The value auto is recommended, allowing the image format to select the appropriate red, green and blue channels for display. 1. Navigate to the Styles page. 2. Click Add a new style and choose the following: Name: Workspace: Format: image_example No workspace CSS 3. Replace the initial CSS definition with: * { raster-channels: auto; } 4. And use the Layer Preview tab to preview the result. 6.7. Styling Workshop 881 GeoServer User Manual, Release 2.15.1 5. If required a list three band numbers can be supplied (for images recording in several wave lengths) or a single band number can be used to view a grayscale image. * { raster-channels: 2; } 6. Isolating just the green band (it wil be drawn as a grayscale image): DEM A digital elevation model is an example of raster data made up of measurements, rather than colors information. The usgs:dem layer used used for this exercise: 1. Return to the the Styles page. 2. Click Add a new style and choose the following: Name: Workspace: Format: raster_example No workspace CSS 3. When we use the raster-channels property set to auto the rendering engine will select our single band of raster content, and do its 882 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 best to map these values into a grayscale image. Replace the content of the style with: * { raster-channels: auto; } 4. Use the Layer Preview tab to preview the result. The range produced in this case from the highest and lowest values. 5. We can use a bit of image processing to emphasis the generated color mapping by making use raster-contrast-enhancement. * { raster-channels: 1; raster-contrast-enhancement: histogram; } 6. Image processing of this sort should be used with caution as it does distort the presentation (in this case making the landscape look more varied then it is in reality. Color Map The approach of mapping a data channel directly to a color channel is only suitable to quickly look at quantitative data. For qualitative data (such as land use) or simply to use color, we need a different approach: 1. Apply the following CSS to our usgs:DEM layer: * { raster-channels: auto; raster-color-map: color-map-entry(#9080DB, color-map-entry(#008000, color-map-entry(#105020, color-map-entry(#FFFFFF, } 0) 1) 255) 4000); 2. Resulting in this artificial color image: 6.7. Styling Workshop 883 GeoServer User Manual, Release 2.15.1 3. An opacity value can also be used with color-map-entry. * { raster-channels: auto; raster-color-map: color-map-entry(#9080DB, 0, 0.0) color-map-entry(#008000, 1, 1.0) color-map-entry(#105020, 200, 1.0) ,→ color-map-entry(#FFFFFF, 4000, 1.0); } 4. Allowing the areas of zero height to be transparent: 5. Raster format for GIS work often supply a “no data” value, or contain a mask, limiting the dataset to only the locations with valid information. Custom We can use what we have learned about color maps to apply a color brewer palette to our data. This exploration focuses on accurately communicating differences in value, rather than strictly making a pretty picture. Care should be taken to consider the target audience and medium used during palette selection. 1. Restore the raster_example CSS style to the following: * { raster-channels: auto; } 2. Producing the following map preview. 884 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 3. To start with we can provide our own grayscale using two color map entries. * { raster-channels: auto; raster-color-map: color-map-entry(#000000, 0) color-map-entry(#FFFFFF, 4000); } 4. Use the Map tab to zoom in and take a look. This is much more direct representation of the source data. We have used our knowledge of elevations to construct a more accurate style. 5. While our straightforward style is easy to understand, it does leave a bit to be desired with respect to clarity. The eye has a hard time telling apart dark shades of black (or bright shades of white) and will struggle to make sense of this image. To address this limitation we are going to switch to the ColorBrewer 9-class PuBuGn palette. This is a sequential palette that has been hand tuned to communicate a steady change of values. 6. Update your style with the following: * { raster-channels: auto; 6.7. Styling Workshop 885 GeoServer User Manual, Release 2.15.1 raster-color-map: color-map-entry(#014636, 0) color-map-entry(#016c59, 500) color-map-entry(#02818a,1000) color-map-entry(#3690c0,1500) color-map-entry(#67a9cf,2000) color-map-entry(#a6bddb,2500) color-map-entry(#d0d1e6,3000) color-map-entry(#ece2f0,3500) color-map-entry(#fff7fb,4000); } 7. A little bit of work with alpha (to mark the ocean as a no-data section): * { raster-channels: auto; raster-color-map: color-map-entry(#014636, 0,0) color-map-entry(#014636, 1) color-map-entry(#016c59, 500) color-map-entry(#02818a,1000) color-map-entry(#3690c0,1500) color-map-entry(#67a9cf,2000) color-map-entry(#a6bddb,2500) color-map-entry(#d0d1e6,3000) color-map-entry(#ece2f0,3500) color-map-entry(#fff7fb,4000); } 8. And we are done: 886 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Bonus Explore Contrast Enhancement 1. A special effect that is effective with grayscale information is automatic contrast adjustment. 2. Make use of a simple contrast enhancement with usgs:dem: * { raster-channels: auto; raster-contrast-enhancement: normalize; } 3. Can you explain what happens when zoom in to only show a land area (as indicated with the bounding box below)? Note: Discussion provided at the end of the workbook. Challenge Intervals 1. The raster-color-map-type property dictates how the values are used to generate a resulting color. 6.7. Styling Workshop 887 GeoServer User Manual, Release 2.15.1 • ramp is used for quantitative data, providing a smooth interpolation between the provided color values. • intervals provides categorization for quantitative data, assigning each range of values a solid color. • values is used for qualitative data, each value is required to have a color-map-entry or it will not be displayed. 2. Chalenge: Update your DEM example to use intervals for presentation. What are the advantages of using this approach for elevation data? Note: Answer provided at the end of the workbook. Explore Image Processing Additional properties are available to provide slight image processing during visualization. Note: In this section are we going to be working around a preview issue where only the top left corner of the raster remains visible during image processing. This issue has been reported as GEOS-6213. Image processing can be used to enhance the output to highlight small details or to balance images from different sensors allowing them to be compared. 1. The raster-contrast-enhancement property is used to turn on a range of post processing effects. Settings are provided for normalize or histogram or none; * { raster-channels: auto; raster-contrast-enhancement: normalize; } 2. Producing the following image: 888 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 3. The raster-gamma property is used adjust the brightness of rastercontrast-enhancement output. Values less than 1 are used to brighten the image while values greater than 1 darken the image. * { raster-channels: auto; raster-contrast-enhancement: none; raster-gamma: 1.5; } 4. Providing the following effect: Challenge Clear Digital Elevation Model Presentation 1. Now that you have seen the data on screen and have a better understanding how would you modify our initial gray-scale example? 2. Challenge: Use what you have learned to present the usgs:dem clearly. Note: Answer provided at the end of the workbook. Challenge Raster Opacity 1. There is a quick way to make raster data transparent, raster-opacity property works in the same fashion as with vector data. The raster as a whole will be drawn partially transparent allow content from other layers to provide context. 2. Challenge: Can you think of an example where this would be useful? Note: Discussion provided at the end of the workbook. 6.7. Styling Workshop 889 GeoServer User Manual, Release 2.15.1 CSS Workbook Conclusion We hope you have enjoyed this styling workshop. Additional resources: • CSS Extension • CSS Cookbook CSS Workbook Answer Key The following questions were listed through out the workshop as an opportunity to explore the material in greater depth. Please do your best to consider the questions in detail prior to checking here for the answer. Questions are provided to teach valuable skills, such as a chance to understand how feature type styles are used to control z-order, or where to locate information in the user manual. SLD Generation Answer for Challenge SLD Generation: 1. Generate the SLD for the following CSS. * { stroke: black; } 2. Challenge: What is unusual about the generated SLD? Can you explain why it still works as expected? The generated SLD does not contain any stroke properties, even though black was specified: SLD considers black the default stroke color for a LineSymbolizer, so no further detail was required. Classification Answer for Challenge Classification: 1. Challenge: Create a new style adjust road appearance based on type. 890 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Hint: The available values are ‘Major Highway’,’Secondary Highway’,’Road’ and ‘Unknown’. 2. Here is an example: [type = 'Major Highway' ] { stroke: #000088; stroke-width: 1.25; } [type = 'Secondary Highway' ]{ stroke: #8888AA; stroke-width: 0.75; } [type = 'Road']{ stroke: #888888; stroke-width: .75; } [type = 'Unknown' ]{ stroke: #888888; stroke-width: 0.5; } * { stroke: #AAAAAA; stroke-opacity: 0.25; stroke-width: 0.5; } SLD Z-Index Generation Answer for Challenge SLD Z-Index Generation: 1. Review the SLD generated by the z-index example. * { stroke: black, #8080E6; stroke-width: 5px, 3px; z-index: 0, 1; } 2. Challenge: There is an interesting trick in the generated SLD, can you explain how it works? 3. The Z-Order example produces multiple FeatureTypeSytle definitions, each acting like an “inner layer”. Each FeatureTypeStyle is rendered into its own raster, and the results merged in order. The legend shown in the map preview also provides a hint, as the rule from each FeatureType style is shown. Label Shields Answer for Challenge Label Shields: 1. The traditional presentation of roads in the US is the use of a shield symbol, with the road number marked on top. 6.7. Styling Workshop 891 GeoServer User Manual, Release 2.15.1 1. Challenge: Have a look at the documentation and reproduce this technique. 2. The use of a label shield is a vendor specific capability of the GeoServer rendering engine. The tricky part of this exercise is finding the documentation online ( i.e. Styled Marks in CSS). * { stroke: black,lightgray; stroke-width: 3,2; label: [name]; font-family: 'Ariel'; font-size: 10; font-fill: black; shield: symbol(square); } :shield { fill: white; stroke: black; size: 18; } Antialiasing Answer for Explore Antialiasing: 1. When we rendered our initial preview, without a stroke, thin white gaps (or slivers) are visible between our polygons. This effect is made more pronounced by the rendering engine making use of the Java 2D sub-pixel accuracy. This technique is primarily used to prevent an aliased (stair-stepped) appearance on diagonal lines. 892 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 2. Explore: Experiment with fill and stroke settings to eliminate slivers between polygons. The obvious approach works - setting both values to the same color: symbolizers: - polygon: stroke-color: 'lightgrey' stroke-width: 1 fill-color: 'lightgrey' Categorize Answer for Explore Categorize: 1. An exciting use of the GeoServer shape symbols is the theming by changing the size used for pattern density. 2. Explore: Use the Categorize function to theme by datarank. Example: .. code-block:: css * { fill: symbol('shape://slash'); fill-size: [ Categorize(datarank, 4, 4, 5, 6, 8, 10, 10) ]; stroke: black; } :fill { stroke: darkgray; } Halo Answer for Challenge Halo: 1. The halo example used the fill color and opacity for a muted halo, while this improved readability it did not bring attention to our labels. A common design choice for emphasis is to outline the text in a contrasting color. 6.7. Styling Workshop 893 GeoServer User Manual, Release 2.15.1 2. Challenge: Produce a map that uses a white halo around black text. Here is an example: * { stroke: gray; fill: #7EB5D3; label: [name]; label-anchor: 0.5 0.5; font-fill: black; font-family: "Arial"; font-size: 14; halo-radius: 1; halo-color: white; } Theming using Multiple Attributes Answer for Challenge Theming using Multiple Attributes: 1. A powerful tool is theming using multiple attributes. This is an important concept allowing map readers to perform “integration by eyeball” (detecting correlations between attribute values information). 2. Challenge: Combine the mapcolor9 and datarank examples to reproduce the following map. This should be a cut and paste using the recode example, and categorize examples already provided. * { fill: [ recode(mapcolor9, 1,'#8dd3c7', 2,'#ffffb3', 3,'#bebada', 4,'#fb8072', 5,'#80b1d3', 6,'#fdb462', 7,'#b3de69', 8,'#fccde5', 9,'#d9d9d9') ], symbol('shape://slash'); fill-size: '',[ Categorize(datarank, 6, 4, 8, 6, 10, 10, 12) ]; stroke: black; } :fill { stroke: black; } 894 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Use of Use of Z-Index Answer for Challenge Use of Z-Index: 1. Earlier we looked at using z-index to simulate line string casing. The line work was drawn twice, once with thick line, and then a second time with a thinner line. The resulting effect is similar to text halos providing breathing space around complex line work allowing it to stand out. 2. Challenge: Use what you know of LineString z-index to reproduce the following map: This is a tricky challenge. While it is easy enough to introduce zindex to control stroke what is not immediately obvious is that zorder also controls fill order. The previous examples illustrate how to introduce z-order, some thought is required to untangle fill and stroke z-order (dummy stroke definitions need to be introduced using empty commas). * { fill: lightgray, symbol('shape://slash'); fill-size: 8px; stroke: '','',lightgray, black; stroke-width: '','',6,1.5; z-index: 1,2,3,4; } :fill { stroke: black; stroke-width: 0.75; } The included legend should be a large clue about what is going on. Geometry Location Answer for Challenge Geometry Location: 1. The mark property can be used to render any geometry content. 2. Challenge: Try this yourself by rendering a polygon layer using a mark property. 6.7. Styling Workshop 895 GeoServer User Manual, Release 2.15.1 This can be done one of two ways: • Changing the association of a polygon layer, such as ne:states_provinces_shp to point_example and using the layer preview page. • Changing the Layer Preview tab to a polygon layer, such as ne:states_provinces_shp. The important thing to notice is that the centroid of each polygon is used as a point location. Dynamic Symbolization Answer for Explore Dynamic Symbolization: 1. SLD Mark and ExternalGraphic provide an opportunity for dynamic symbolization. This is accomplished by embedding a small CQL expression in the string passed to symbol or url. This sub-expression is isolated with ${ } as shown: - point: symbols: - mark: shape: ${if_then_else(equalTo(FEATURECLA, ,→'Admin-0 capital'),'star','circle')} 2. Challenge: Use this approach to rewrite the Dynamic Styling example. Example available here point_example.css Layer Group Answer for Challenge Layer Group: 1. Use a Layer Group to explore how symbology works together to form a map. • ne:NE1 • ne:states_provincces_shp • ne:populated_places 2. This background is relatively busy and care must be taken to ensure both symbols and labels are clearly visible. 3. Challenge: Do your best to style populated_places over this busy background. Here is an example with labels for inspiration: 896 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 This should be an opportunity to revisit label halo settings from Polygons. * { mark-size: [5+((10-SCALERANK)/3)]; font-fill: black; font-family: "Arial"; font-size: 10; label-anchor: 0.5 1; label-offset: 0 [-12+SCALERANK]; halo-radius: 2; halo-color: lightgray; halo-opacity:0.7; mark-label-obstacle: true; label-max-displacement: 90; label-priority: [0 - LABELRANK]; } :symbol { fill: black; stroke: white; stroke-opacity:0.75; } Using a lightgray halo, 0.7 opacity and radius 2 fades out the complexity immediately surrounding the label text improving legibility. Contrast Enhancement Discussion for Explore Contrast Enhancement: 1. A special effect that is effective with grayscale information is automatic contrast adjustment. 2. Make use of a simple contrast enhancement with usgs:dem: * { raster-channels: auto; 6.7. Styling Workshop 897 GeoServer User Manual, Release 2.15.1 raster-contrast-enhancement: normalize; } 3. Can you explain what happens when zoom in to only show a land area (as indicated with the bounding box below)? What happens is insanity, normalize stretches the palette of the output image to use the full dynamic range. As long as we have ocean on the screen (with value 0) the land area was shown with roughly the same presentation. Once we zoom in to show only a land area, the lowest point on the screen (say 100) becomes the new black, radically altering what is displayed on the screen. Intervals Answer for Challenge Intervals: 1. The color-map type property dictates how the values are used to generate a resulting color. • ramp is used for quantitative data, providing a smooth interpolation between the provided color values. • intervals provides categorization for quantitative data, assigning each range of values a solid color. 898 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 • values is used for qualitative data, each value is required to have a color-map entry or it will not be displayed. 2. Chalenge: Update your DEM example to use intervals for presentation. What are the advantages of using this approach for elevation data? By using intervals it becomes very clear how relatively flat most of the continent is. The ramp presentation provided lots of fascinating detail which distracted from this fact. Here is style for you to cut and paste: * { raster-channels: auto; raster-color-map: color-map-entry(#014636, 0,0) color-map-entry(#014636, 1) color-map-entry(#016c59, 500) color-map-entry(#02818a,1000) color-map-entry(#3690c0,1500) color-map-entry(#67a9cf,2000) color-map-entry(#a6bddb,2500) color-map-entry(#d0d1e6,3000) color-map-entry(#ece2f0,3500) color-map-entry(#fff7fb,4000); raster-color-map-type: intervals; } Clear Digital Elevation Model Presentation Answer for Challenge Clear Digital Elevation Model Presentation: 1. Now that you have seen the data on screen and have a better understanding how would you modify our initial gray-scale example? 2. Challenge: Use what you have learned to present the usgs:dem clearly. 6.7. Styling Workshop 899 GeoServer User Manual, Release 2.15.1 The original was a dark mess. Consider making use of mid-tones (or adopting a sequential palette from color brewer) in order to fix this. In the following example the ocean has been left dark, allowing the mountains stand out more. * { raster-channels: auto; raster-color-map: color-map-entry(#000000, 0) color-map-entry(#444444, 1) color-map-entry(#FFFFFF, 3000); } Raster Opacity Discussion for Challenge Clear Digital Elevation Model Presentation: 1. There is a quick way to make raster data transparent, raster opacity property works in the same fashion as with vector data. The raster as a whole will be drawn partially transparent allow content from other layers to provide context. 2. Challenge: Can you think of an example where this would be useful? This is difficult as raster data is usually provided for use as a basemap, with layers being drawn over top. The most obvious example here is the display of weather systems, or model output such as fire danger. By drawing the raster with some transparency, the landmass can be shown for context. 6.7.4 YSLD Styling Workbook GeoServer styling can be used for a range of creative effects. This section introduces the YSLD Extension which can be used as alternative to SLD files. 900 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 YSLD Quickstart In the last section, we saw how the OGC defines style using XML documents (called SLD files). We will now explore GeoServer styling in greater detail using a tool to generate our SLD files. The YSLD GeoServer extension is used to generate SLD files using a clearer, more consice language based on YAML. Unlike CSS, the YSLD styling language has a one-to-one correspondance to SLD, meaning that each line of YSLD translates directly to one or more lines of SLD. Aditionally, A YSLD style can be converted to SLD and back without loss of information. Using the YSLD extension to define styles results in shorter examples that are easier to understand. At any point we will be able to review the generated SLD file. Reference: • YSLD Reference Syntax This section provides a quick introduction to YSLD syntax for mapping professionals who may not be familiar with YAML. Property Syntax Individual statements (or directives) in a YSLD styling document are designed as key-value, or property-value pairs of the following form: : The is a string denoting the property name, while the can be one of a number of different types depending on context. Integer Float Text Color Tuple Expression Numerical value. May be surrounded by quotes. Numerical value. May be surrounded by quotes. Text value. If value is amiguous, use single quotes. Hexadecimal color of the form '#RRGGBB'. A list of values in brackets. e.g. [0, 1] CQL expression surrounded by ${ } Mappings and lists There are three types of objects in a YSLD document: 1. Scalar, a simple value 2. Mapping, a collection of key-value (property-value) pairs 6.7. Styling Workshop 901 GeoServer User Manual, Release 2.15.1 3. List, any collection of objects. A list can contain mappings, scalars, and even other lists. Lists require dashes for every entry, while mappings do not. For example, a symbolizer block is a list, so every entry requires its own dash: The polygon: and text: objects (the individual symbolizers themselves) are mappings, and as such, the contents do not require dashes, only indents: - polygon: stroke-color: '#808080' fill-color: '#FF0000' The dash next to polygon means that the item itself is contained in a list, not that it contains a list. And the placement of the dash is at the same level of indentation as the list title. If you have a list that contains only one item, and there is no other content at higher levels of the list, you may omit the enclosing elements. For example, the following are equivalent: feature-styles: - rules: - symbolizers: - point: symbols: - mark: shape: circle fill-color: 'gray' point: symbols: - mark: shape: circle fill-color: 'gray' This is usefull for making your styles more concise. Indentation Indentation is very important in YSLD. All directives must be indented to its proper place to ensure proper hierarchy. Improper indentation will cause a style to be rendered incorrectly, or not at all. For example, the polygon symbolizer, since it is a mapping, contains certain parameters inside it, such as the color of the fill and stroke. These must be indented such that they are “inside” the polygon block. In this example, the following markup is correct: - polygon: fill-color: '#808080' 902 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 fill-opacity: 0.5 stroke-color: black stroke-opacity: 0.75 The parameters inside the polygon (symbolizer) are indented, meaning that they are referencing the symbolizer and are not “outside it.” Compare to the following incorrect markup: - polygon: fill-color: '#808080' fill-opacity: 0.5 stroke-color: black stroke-opacity: 0.75 Rules We have already seen a CSS style composed of a single rule: point: symbols: - mark: shape: circle fill-color: 'gray' We can make a style consisting of more than one rule, carefully choosing the selector for each rule. In this case we are using a selector to style capital cities with a star, and non-capital with a circle: rules: - filter: ${FEATURECLA = 'Admin-0 capital'} scale: [min, max] symbolizers: - point: size: 6 symbols: - mark: shape: star stroke-color: 'black' stroke-width: 1 fill-color: 'gray' - filter: ${FEATURECLA <> 'Admin-0 capital'} scale: [min, max] symbolizers: - point: size: 6 symbols: - mark: shape: circle stroke-color: 'black' stroke-width: 1 fill-color: 'gray' The feature attribute test performed above uses Constraint Query Language (CQL). This syntax can be used to define filters to select 6.7. Styling Workshop 903 GeoServer User Manual, Release 2.15.1 content, similar to how the SQL WHERE statement is used. It can also be used to define expressions to access attribute values allowing their use when defining style properties. Rule selectors can also be triggered based on the state of the rendering engine. In this example we are only applying labels when zoomed in: rules: - scale: [min, '2.0E7'] symbolizers: - text: label: ${NAME} fill-color: 'gray' In the above example the label is defined using the CQL Expression NAME. This results in a dynamic style that generates each label on a case-by-case basis, filling in the label with the feature attribute NAME. Reference: • Filter Syntax (YSLD Reference) • ECQL Reference (User Guide) Variables Up to this point we have been styling individual features, documenting how each shape is represented. When styling multiple feaures, or using filters to style individual features in different yars, you may need to repeat styling information. Variables in YSLD allow for a certain directive or block of directives to be defined by name and later reused. This can greatly simplify the styling document. The two most-common use cases for using variables are: • To create a more-friendly name for a value (such as using myorange instead of #EE8000) • To define a block of directives to remove redundant content and to decrease file length It is customary, but not required, to place all definitions at the very top of the YSLD file. The syntax for defining a variable as a single value is: define: &variable The defined variable can then be used as a value by variable name with a *: : *variable The syntax for defining a variable as a content block is: 904 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 define: &varblock : : ... : - : : ... The syntax for using a variable block is to prepend the variable name with <<: *. For example: : - : <<: *varblock • Variables (YSLD Reference) Compare YSLD to SLD As noted above, YSLD has a one-to-one correspondance with SLD, it merely uses a different markup language to diplay the same content. We can compare a SLD style with a YSLD style to see this correspondence: SLD Style Here is an example SLD file for reference: airports Airports airports Airports image/svg 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 6.7. Styling Workshop 905 GeoServer User Manual, Release 2.15.1 26 27 28 29 30 YSLD Style Here is the same example as YSLD: name: airports title: Airports scale: [min, max] symbolizers: - point: size: 16 symbols: - external: url: airport.svg format: image/svg 1 2 3 4 5 6 7 8 9 10 We use a point symbolizer to indicate we want this content drawn as a Point (line 16 in the SLD, line 5 in the YSLD). The point symbolizer declares an external graphic, which contains the URL airports. svg indicating the image that should be drawn (line 20 in the SLD, line 9 in the YSLD). Tour To confirm everything works, let’s reproduce the airports style above. 1. Navigate to the Styles page. 2. Each time we edit a style, the contents of the associated SLD file are replaced. Rather then disrupt any of our existing styles we will create a new style. Click Add a new style and choose the following: Name: Workspace: Format: airports0 (leave empty) YSLD 3. Replace the initial YSLD definition with with our airport YSLD example and click Apply: name: airports title: Airports scale: [min, max] symbolizers: - point: size: 16 symbols: - external: 906 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 url: airport.svg format: image/svg 4. Click the Layer Preview tab to preview the style. We want to preview on the aiports layer, so click the name of the current layer and select ne:airports from the list that appears. You can use the mouse buttons to pan and scroll wheel to change scale. Fig. 6.300: Choosing the airports layer Fig. 6.301: Layer preview 5. Click Layer Data for a summary of the selected data. 6.7. Styling Workshop 907 GeoServer User Manual, Release 2.15.1 Fig. 6.302: Layer attributes Bonus Finished early? For now please help your neighbour so we can proceed with the workshop. If you are really stuck please consider the following challenge rather than skipping ahead. Explore Data 1. Return to the Data tab and use the Compute link to determine the minimum and maximum for the scalerank attribute. Challenge Compare SLD Generation # The rest API can be used to review your YAML file directly. Browser: • view-source:http://localhost:8080/geoserver/rest/styles/airport0.yaml Command line: curl -v -u admin:geoserver -XGET http:/ ,→/localhost:8080/geoserver/rest/styles/airports0.yaml 1. The REST API can also be used generate an SLD file: Browser: • view-source:http://localhost:8080/geoserver/rest/styles/airport0.sld?pretty=true Command line: 908 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 curl -v -u admin:geoserver -XGET http://localhost:8080/ ,→geoserver/rest/styles/airports0.sld?pretty=true 1. Compare the generated SLD differ above with the hand written SLD file used as an example? Challenge: What differences can you spot? Lines We will start our tour of YSLD styling by looking at the representation of lines. Fig. 6.303: LineString Geometry Review of line symbology: • Lines can be used to represent either abstract concepts with length but not width such as networks and boundaries, or long thin features with a width that is too small to represent on the map. This means that the visual width of line symbols do not normally change depending on scale. • Lines are recorded as LineStrings or Curves depending on the geometry model used. • SLD uses a LineSymbolizer to record how the shape of a line is drawn. The primary characteristic documented is the Stroke used to draw each segment between vertices. • Labeling of line work is anchored to the mid-point of the line. GeoServer provides a vendor option to allow label rotation aligned with line segments. For our exercises we are going to be using simple YSLD documents, often consisting of a single rule, in order to focus on the properties used for line symbology. Each exercise makes use of the ne:roads layer. Reference: • YSLD Reference • YSLD Reference Line symbolizer (User Manual | YSLD Reference) • LineString (User Manual | SLD Reference ) Line A line symbolizer is represented by a line key. You can make a completely default symbolizer by giving it an empty map line: 1. Navigate to the Styles page. 6.7. Styling Workshop 909 GeoServer User Manual, Release 2.15.1 Fig. 6.304: Basic Stroke Properties 2. Click Add a new style and choose the following: New style name: Workspace for new layer: Format: line_example Leave blank YSLD 3. Choose line from the Generate a default style dropdown and click generate. 4. The style editor should look like below: title: dark yellow line symbolizers: - line: stroke-width: 1.0 stroke-color: '#99cc00' Note: The title and value for stroke-color may be different. 1. Click Apply 2. Click Layer Preview to see your new style applied to a layer. You can use this tab to follow along as the style is edited, it will refresh each time Apply is pressed. 3. You can see the equivalent SLD by requesting http:/ /localhost:8080/geoserver/rest/styles/ line_example.sld?pretty=true which will currently show the default line symbolizer we created. line_example ,→ 910 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 line_example dark yellow line name #99CC00 We only specified the line symbolizer, so all of the boilerplate arround was generated for us. 1. Additional properties can be used fine-tune appearance. stroke-color to specify the colour of the line. Use line: stroke-color: blue 2. stroke-width lets us make the line wider line: stroke-color: blue stroke-width: 2px 3. stroke-dasharray applies a dot dash pattern. line: stroke-color: blue stroke-width: 2px stroke-dasharray: 5 2 4. Check the Layer Preview tab to preview the result. Note: The GeoServer rendering engine is quite sophisticated and allows the use of units of measure (such as m or ft). While we are using pixels in this example, real world units will be converted using the current scale, allowing for lines that change width with the scale. 6.7. Styling Workshop 911 GeoServer User Manual, Release 2.15.1 Multiple Symbolizers Providing two strokes is often used to provide a contrasting edge (called casing) to thick lines. This can be created using two symbolizers. 1. Start by filling in a bit of boilerplate that we’ll be using feature-styles: - rules: - symbolizers: - line: stroke-color: '#8080E6' stroke-width: 3px The line symbolizer is inside a rule, which is inside a feature style. 2. Add a second symbolizer to the rule feature-styles: - rules: - symbolizers: - line: stroke-color: stroke-width: - line: stroke-color: stroke-width: black 5px '#8080E6' 3px The wider black line is first so it is drawn first, then the thinner blue line drawn second and so over top of the black line. This is called the painter’s algorithm. 3. If you look carefully you can see a problem with our initial attempt. The junctions of each line show that the casing outlines each line individually, making the lines appear randomly overlapped. Ideally we would like to control this process, only making use of this effect for overpasses. This is becaue the black and blue symbolizers are being drawn on a feature by feature basis. For nice line casing, we want all of the black symbols, and then all of the blue symbols. 4. Create a new feature style and move the second symbolizer there. feature-styles: - rules: - symbolizers: - line: 912 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 stroke-color: stroke-width: - rules: - symbolizers: - line: stroke-color: stroke-width: black 5px '#8080E6' 3px Again we are using painter’s algorithm order: the first feature style is drawn first then the second so the the second is drawn on top of the first. The difference is that for each feature style, all of the features are drawn before the next feature style is drawn. 5. If you look carefully you can see the difference. 6. By using feature styles we have been able to simulate line casing. Label Our next example is significant as it introduces how text labels are generated. Fig. 6.305: Use of Label Property This is also our first example making use of a dynamic style (where a value comes from an attribute from your data). 1. To enable LineString labeling we add a text symbolizer witrh a label. Update line_example with the following: 6.7. Styling Workshop 913 GeoServer User Manual, Release 2.15.1 symbolizers: - line: stroke-color: blue stroke-width: 1px - text: label: ${name} 2. The SLD standard documents the default label position for each kind of Geometry. For LineStrings the initial label is positioned on the midway point of the line. 3. We have used an expression to calculate a property value for label. The label is generated dynamically from the name attribute. Expressions are supplied within curly braces preceded with a dollar sign, and use Extended Constraint Query Language (ECQL) syntax. symbolizers: - line: stroke-color: blue stroke-width: 1px - text: label: ${name} 4. Additional keys can be supplied to fine-tune label presentation: symbolizers: - line: stroke-color: blue stroke-width: 1px - text: label: ${name} fill-color: black placement: line offset: 7px 5. The fill-color property is set to black to provide the colour of the text. symbolizers: - line: stroke-color: blue stroke-width: 1px - text: 914 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 label: ${name} fill-color: black placement: line offset: 7px 6. The placement property is used to set how the label is placed with respect to the line. By default it is point which casues the label to be placed next to the midpoint as it would be for a point feature. When set to line it is placed along the line instead. offset specifies how far from the line the label should be placed. symbolizers: - line: stroke-color: blue stroke-width: 1px - text: label: ${name} fill-color: black placement: line offset: 7px 7. When using point placement, you can shift the position of the label using displacement instead of offset. This takes an x value and a y value. symbolizers: - line: stroke-color: blue stroke-width: 1px - text: label: ${name} fill-color: black displacement: [5px, -10px] How Labeling Works The rendering engine collects all the generated labels during the rendering of each layer. Then, during labeling, the engine sorts through the labels performing collision avoidance (to prevent labels overlapping). Finally the rendering engine draws the labels on top of the 6.7. Styling Workshop 915 GeoServer User Manual, Release 2.15.1 map. Even with collision avoidance you can spot areas where labels are so closely spaced that the result is hard to read. The parameters provided by SLD are general purpose and should be compatible with any rendering engine. To take greater control over the GeoServer rendering engine we can use “vendor specific” parameters. These hints are used specifically for the GeoServer rendering engine and will be ignored by other systems. In YSLD vendor specific parameters start with the prefix x-. 1. The ability to take control of the labeling process is exactly the kind of hint a vendor specific parameter is intended for. Update line_example with the following: symbolizers: - line: stroke-color: blue stroke-width: 1px - text: label: ${name} fill-color: black placement: line offset: 7px x-label-padding: 10 2. The parameter x-label-padding provides additional space around our label for use in collision avoidance. symbolizers: - line: stroke-color: blue stroke-width: 1px - text: label: ${name} fill-color: black placement: line offset: 7px x-label-padding: 10 3. Each label is now separated from its neighbor, improving legibility. Scale This section explores the use of rules with filters and scale restrictions. 1. Replace the line_example YSLD definition with: 916 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 rules: - filter: ${scalerank < 4} symbolizers: - line: stroke-color: black stroke-width: 1 2. And use the Layer Preview tab to preview the result. 3. The scalerank attribute is provided by the Natural Earth dataset to allow control of the level of detail based on scale. Our filter shortlisted all content with scalerank 4 or lower, providing a nice quick preview when we are zoomed out. 4. In addition to testing feature attributes, selectors can also be used to check the state of the rendering engine. Replace your YSLD with the following: rules: - scale: [35000000, max] symbolizers: - line: stroke-color: black stroke-width: 1 - scale: [min, 35000000] symbolizers: - line: stroke-color: blue stroke-width: 1 5. As you adjust the scale in the Layer Preview (using the mouse scroll wheel) the color will change between black and blue. You can read the current scale in the bottom right corner, and the legend will change to reflect the current style. 6. Putting these two ideas together allows control of level detail based on scale: define: &primaryStyle stroke-color: black define: &primaryFilter ${scalerank <= 4} 6.7. Styling Workshop 917 GeoServer User Manual, Release 2.15.1 define: &secondaryStyle stroke-color: '#000055' define: &secondaryFilter ${scalerank = 5} rules: - else: true scale: [min, 9000000] symbolizers: - line: stroke-color: '#888888' stroke-width: 1 - filter: ${scalerank = 7} scale: [min, 17000000] symbolizers: - line: stroke-color: '#777777' stroke-width: 1 - filter: ${scalerank = 6} scale: [min, 35000000] symbolizers: - line: stroke-color: '#444444' stroke-width: 1 - filter: *secondaryFilter scale: [9000000, 70000000] symbolizers: - line: <<: *secondaryStyle stroke-width: 1 - filter: *secondaryFilter scale: [min, 9000000] symbolizers: - line: <<: *secondaryStyle stroke-width: 2 - filter: *primaryFilter scale: [35000000, max] symbolizers: - line: <<: *primaryStyle stroke-width: 1 - filter: *primaryFilter scale: [9000000, 35000000] symbolizers: - line: <<: *primaryStyle stroke-width: 2 - filter: *primaryFilter scale: [min, 9000000] symbolizers: - line: <<: *primaryStyle stroke-width: 4 918 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 7. When a rule has both a filter and a scale, it will trigger when both are true. The first rule has else: true instead of a filter. This causes it to be applied after all other rules have been checked if none of them worked. Since there are some things we need to specify more than once like the colour and filter for primary and secondary roads, even as they change size at different scales, they are given names with define so they can be reused. The filters are inserted inline using *name while the style is inserted as a block with <<: *name Bonus Finished early? Here are some opportunities to explore what we have learned, and extra challenges requiring creativity and research. In a classroom setting please divide the challenges between teams (this allows us to work through all the material in the time available). Explore Vendor Option Follow Line Vendor options can be used to enable some quite spectacular effects, while still providing a style that can be used by other applications. 1. Update line_example with the following: symbolizers: - line: stroke-color: '#EDEDFF' stroke-width: 10 - text: label: '${level} #${name}' fill-color: '#000000' x-followLine: true The # character is the comment character in YAML, so we have to quote strings that contain it like colours and in this expression. 2. The property stroke-width has been used to make our line thicker in order to provide a backdrop for our label. symbolizers: - line: stroke-color: '#EDEDFF' stroke-width: 10 - text: 6.7. Styling Workshop 919 GeoServer User Manual, Release 2.15.1 label: '${level} #${name}' fill-color: '#000000' placement: point x-followLine: true 3. The label property combine several CQL expressions together for a longer label. symbolizers: - line: stroke-color: '#EDEDFF' stroke-width: 10 - text: label: '${level} #${name}' fill-color: '#000000' x-followLine: true The expressions in the label property: ${level} #${name} are inserted into the text by combining them with the text between them using Concatenate function: [Concatenate(level,' #', name)] This happens silently in the background. 4. The property x-followLine provides the ability of have a label exactly follow a LineString character by character. symbolizers: - line: stroke-color: '#EDEDFF' stroke-width: 10 - text: label: ${level} ${name} fill-color: '#000000' x-followLine: true 5. The result is a new appearance for our roads. 920 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Challenge Classification 1. The roads type attribute provides classification information. You can Layer Preview to inspect features to determine available values for type. 2. Challenge: Create a new style adjust road appearance based on type. note:: The available values are ‘Major Highway’,’Secondary Highway’,’Road’ and ‘Unknown’. note:: Answer provided at the end of the workbook. Challenge One Rule Classification 1. You can save a lot of typing by doing your classification in an expression using arithmetic or the Recode function 2. Challenge: Create a new style and classify the roads based on their scale rank using expressions in a single rule instead of multiple rules with filters. Note: Answer provided at the end of the workbook. Challenge Label Shields 1. The traditional presentation of roads in the US is the use of a shield symbol, with the road number marked on top. 2. Challenge: Have a look at the documentation for putting a graphic on a text symbolizer in SLD and reproduce this technique in YSLD. 6.7. Styling Workshop 921 GeoServer User Manual, Release 2.15.1 Note: Answer provided at the end of the workbook. Polygons Next we look at how YSLD styling can be used to represent polygons. Fig. 6.306: Polygon Geometry Review of polygon symbology: • Polygons offer a direct representation of physical extent or the output of analysis. • The visual appearance of polygons reflects the current scale. • Polygons are recorded as a LinearRing describing the polygon boundary. Further LinearRings can be used to describe any holes in the polygon if present. The Simple Feature for SQL Geometry model (used by GeoJSON) represents these areas as Polygons, the ISO 19107 geometry model (used by GML3) represents these areas as Surfaces. • SLD uses a PolygonSymbolizer to describe how the shape of a polygon is drawn. The primary characteristic documented is the Fill used to shade the polygon interior. The use of a Stroke to describe the polygon boundary is optional. • Labeling of a polygon is anchored to the centroid of the polygon. GeoServer provides a vendor-option to allow labels to line wrap to remain within the polygon boundaries. For our Polygon exercises we will try and limit our YSLD documents to a single rule, in order to showcase the properties used for rendering. Reference: • YSLD Reference 922 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 • YSLD Reference Polygon symbolizer (User Manual | YSLD Reference) • Polygons (User Manual | SLD Reference ) This exercise makes use of the ne:states_provinces_shp layer. 1. Navigate to Styles. 2. Create a new style polygon_example. Name: Workspace: Format: polygon_example No workspace YSLD 3. Choose polygon from the Generate a default style dropdown and click generate. 4. Replace the generated style with the following style and click Apply to save: symbolizers: - polygon: fill-color: 'lightgrey' 5. Click on the tab Layer Preview to preview. 6. Set ne:states_provinces_shp as the preview layer. Stroke and Fill The polygon symbolizer controls the display of polygon data. The fill-color property is used to provide the color used to draw the interior of a polygon. 1. Replace the contents of polygon_example with the following fill example: 6.7. Styling Workshop 923 GeoServer User Manual, Release 2.15.1 symbolizers: - polygon: fill-color: 'gray' 2. The Layer Preview tab can be used preview the change: 3. To draw the boundary of the polygon the stroke property is used: The stroke property is used to provide the color and size of the polygon boundary. It is effected by the same parameters (and vendor specific parameters) as used for LineStrings. symbolizers: - polygon: fill-color: 'gray' stroke-color: 'black' stroke-width: 2 Note: Technically the boundary of a polygon is a specific case of a LineString where the first and last vertex are the same, forming a closed LinearRing. 4. The effect of adding stroke is shown in the map preview: 5. An interesting technique when styling polygons in conjunction with background information is to control the fill opacity. The fill-opacity property is used to adjust transparency (provided as range from 0.0 to 1.0). Use of fill-opacity to render polygons works well in conjunction with a raster base map. This approach allows details of the base map to shown through. The stroke-opacity property is used in a similar fashion, as a range from 0.0 to 1.0. symbolizers: - polygon: fill-color: 'white' fill-opacity: 0.5 stroke-color: 'lightgrey' 924 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 stroke-width: 0.25 stroke-opacity: 0.5 6. As shown in the map preview: 7. This effect can be better appreciated using a layer group. Where the transparent polygons is used lighten the landscape provided by the base map. Pattern The fill-graphic property can be used to provide a pattern. The fill pattern is defined by repeating one of the built-in symbols, or making use of an external image. 1. We have two options for configuring a fill-graphic with a repeating graphic: Using external to reference to an external graphic. Use of mark to access a predefined shape. SLD provides several well-known shapes (circle, square, triangle, arrow, cross, star, and 6.7. Styling Workshop 925 GeoServer User Manual, Release 2.15.1 x). GeoServer provides additional shapes specifically for use as fill patterns. Update polygon_example with the following built-in symbol as a repeating fill pattern: symbolizers: - polygon: fill-graphic: symbols: - mark: shape: square fill-color: 'gray' stroke-color: 'black' stroke-width: 1 2. The map preview (and legend) will show the result: 3. Add a black stroke: symbolizers: - polygon: stroke-color: 'black' stroke-width: 1 fill-graphic: symbols: - mark: shape: square fill-color: 'gray' stroke-color: 'black' stroke-width: 1 4. To outline the individual shapes: 5. Additional fill properties allow control over the orientation and size of the symbol. 926 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 The size property is used to adjust the size of the symbol prior to use. The rotation property is used to adjust the orientation of the symbol. Adjust the size and rotation as shown: symbolizers: - polygon: stroke-color: 'black' stroke-width: 1 fill-graphic: size: 22 rotation: 45.0 symbols: - mark: shape: square fill-color: 'gray' stroke-color: 'black' stroke-width: 1 6. The size of each symbol is increased, and each symbol rotated by 45 degrees. Note: Does the above look correct? There is an open request GEOT4642 to rotate the entire pattern, rather than each individual symbol. 7. The size and rotation properties just affect the size and placement of the symbol, but do not alter the symbol’s design. In order to control the color we set the fill-color and stroke-color properties of the mark. 8. Replace the contents of polygon_example with the following: symbolizers: - polygon: fill-graphic: symbols: - mark: shape: square fill-color: '#008000' stroke-color: '#006400' 6.7. Styling Workshop 927 GeoServer User Manual, Release 2.15.1 stroke-width: 1 9. This change adjusts the appearance of our grid of squares. 10. The well-known symbols are more suited for marking individual points. Now that we understand how a pattern can be controlled it is time to look at the patterns GeoServer provides. shape://horizline shape://vertline shape://backslash shape://slash shape://plus shape://times horizontal hatching vertical hatching right hatching pattern left hatching pattern vertical and horizontal hatching pattern cross hatch pattern Update the example to use shape://slash for a pattern of left hatching. symbolizers: - polygon: stroke-color: 'black' stroke-width: 1 fill-graphic: symbols: - mark: shape: 'shape://slash' stroke-color: 'gray' 11. This approach is well suited to printed output or low color devices. 12. To control the size of the symbol produced use the size property of the fill-graphic. 928 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 symbolizers: - polygon: stroke-color: 'black' stroke-width: 1 fill-graphic: size: 8 symbols: - mark: shape: 'shape://slash' stroke-color: 'gray' 13. This results in a tighter pattern shown: 14. Multiple fills can be applied by using a seperate symbolizer for each fill as part of the same rule. symbolizers: - polygon: stroke-color: 'black' stroke-width: 1 fill-color: '#DDDDFF' - polygon: fill-graphic: size: 8 symbols: - mark: shape: shape://slash stroke-color: 'black' stroke-width: 0.5 15. The resulting image has a solid fill, with a pattern drawn overtop. Label Labeling polygons follows the same approach used for LineStrings. The key properties fill and label are used to enable Polygon label generation. 1. By default labels are drawn starting at the centroid of each polygon. 6.7. Styling Workshop 929 GeoServer User Manual, Release 2.15.1 2. Try out label and fill together by replacing our polygon_example with the following: symbolizers: - polygon: stroke-color: 'blue' stroke-width: 1 fill-color: '#7EB5D3' - text: label: ${name} fill-color: 'black' 3. Each label is drawn from the lower-left corner as shown in the Layer Preview preview. 4. We can adjust how the label is drawn at the polygon centroid. The property anchor provides two numbers expressing how a label is aligned with respect to the centroid. The first value controls the horizontal alignment, while the second value controls the vertical alignment. Alignment is expressed between 0.0 and 1.0 as shown in the following table. Top Middle Bottom Left 0.0 1.0 0.0 0.5 0.0 0.0 Center 0.5 1.0 0.5 0.5 0.5 0.0 Right 1.0 1.0 1.0 0.5 1.0 0.0 Adjusting the anchor is the recommended approach to positioning your labels. 5. Using the anchor property we can center our labels with respect to geometry centroid. To align the center of our label we select 50% horizontally and 50% vertically, by filling in 0.5 and 0.5 below: symbolizers: - polygon: stroke-color: 'blue' stroke-width: 1 fill-color: '#7EB5D3' - text: label: ${name} fill-color: 'black' anchor: [0.5, 0.5] 930 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 6. The labeling position remains at the polygon centroid. We adjust alignment by controlling which part of the label we are “snapping” into position. 7. The property displacement can be used to provide an initial displacement using and x and y offset. 8. This offset is used to adjust the label position relative to the geometry centroid resulting in the starting label position. symbolizers: - polygon: stroke-color: 'blue' stroke-width: 1 fill-color: '#7EB5D3' - text: label: ${name} fill-color: 'black' displacement: [0, 7] 9. Confirm this result in the map preview. 10. These two settings can be used together. The rendering engine starts by determining the label position generated from the geometry centroid and the label-offset displacement. 6.7. Styling Workshop 931 GeoServer User Manual, Release 2.15.1 The bounding box of the label is used with the label-anchor setting align the label to this location. Step 1: starting label position = centroid + displacement Step 2: snap the label anchor to the starting label position 11. To move our labels down (allowing readers to focus on each shape) we can use displacement combined with followed by horizontal alignment. symbolizers: - polygon: stroke-color: 'blue' stroke-width: 1 fill-color: '#7EB5D3' - text: label: ${name} fill-color: 'black' anchor: [0.5, 1] displacement: [0, -7] 12. As shown in the map preview. Legibility When working with labels a map can become busy very quickly, and difficult to read. 1. GeoServer provides extensive vendor parameters directly controlling the labelling process. Many of these parameters focus on controlling conflict resolution (when labels would otherwise overlap). 2. Two common properties for controlling labeling are: x-maxDisplacement indicates the maximum distance GeoServer should displace a label during conflict resolution. x-autoWrap allows any labels extending past the provided width will be wrapped into multiple lines. 3. Using these together we can make a small improvement in our example: 932 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 symbolizers: - polygon: stroke-color: 'blue' stroke-width: 1 fill-color: '#7EB5D3' - text: label: ${name} fill-color: 'black' anchor: [0.5, 0.5] x-maxDisplacement: 40 x-autoWrap: 70 4. As shown in the following preview. 5. Even with this improved spacing between labels, it is difficult to read the result against the complicated line work. Use of a halo to outline labels allows the text to stand out from an otherwise busy background. In this case we will make use of the fill color, to provide some space around our labels. We will also change the font to Arial. symbolizers: - polygon: stroke-color: 'blue' stroke-width: 1 fill-color: '#7EB5D3' - text: label: ${name} fill-color: 'black' anchor: [0.5, 0.5] font-family: Arial font-size: 14 font-style: normal font-weight: normal halo: fill-color: '#7EB5D3' fill-opacity: 0.8 radius: 2 x-maxDisplacement: 40 x-autoWrap: 70 6. By making use of fill-opacity on the halo we we still allow stroke 6.7. Styling Workshop 933 GeoServer User Manual, Release 2.15.1 information to show through, but prevent the stroke information from making the text hard to read. 7. And advanced technique for manually taking control of conflict resolution is the use of the priority. This property takes an expression which is used in the event of a conflict. The label with the highest priority “wins.” 8. The Natural Earth dataset we are using includes a labelrank intended to control what labels are displayed based on zoom level. The values for labelrank go from 0 (for zoomed out) to 20 (for zoomed in). To use this value for priority we need to swap the values around so a scalerank of 1 is given the highest priority. symbolizers: - polygon: stroke-color: 'blue' stroke-width: 1 fill-color: '#7EB5D3' - text: label: ${name} fill-color: 'black' anchor: [0.5, 0.5] font-family: Arial font-size: 14 font-style: normal font-weight: normal halo: fill-color: '#7EB5D3' fill-opacity: 0.8 radius: 2 x-maxDisplacement: 40 x-autoWrap: 70 priority: ${'20' - labelrank} 9. In the following map East Flanders will take priority over Zeeland when the two labels overlap. 934 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Theme A thematic map (rather than focusing on representing the shape of the world) uses elements of style to illustrate differences in the data under study. This section is a little more advanced and we will take the time to look at the generated SLD file. 1. We can use a site like ColorBrewer to explore the use of color theming for polygon symbology. In this approach the the fill color of the polygon is determined by the value of the attribute under study. This presentation of a dataset is known as “theming” by an attribute. 2. For our ne:states_provinces_shp dataset, a mapcolor9 attribute has been provided for this purpose. Theming by mapcolor9 results in a map where neighbouring countries are visually distinct. Qualitative 9-class Set3 #8dd3c7 #fb8072 #b3de69 #ffffb3 #80b1d3 #fccde5 #bebada #fdb462 #d9d9d9 If you are unfamiliar with theming you may wish to visit http:// colorbrewer2.org to learn more. The i icons provide an adequate background on theming approaches for qualitative, sequential and diverging datasets. 3. The first approach we will take is to directly select content based on colormap, providing a color based on the 9-class Set3 palette above: define: &stroke stroke-color: 'gray' stroke-width: 0.5 rules: - filter: ${mapcolor9 = '1'} scale: [min, max] symbolizers: - polygon: <<: *stroke 6.7. Styling Workshop 935 GeoServer User Manual, Release 2.15.1 fill-color: '#8DD3C7' - filter: ${mapcolor9 = '2'} scale: [min, max] symbolizers: - polygon: <<: *stroke fill-color: '#FFFFB3' - filter: ${mapcolor9 = '3'} scale: [min, max] symbolizers: - polygon: <<: *stroke fill-color: '#BEBADA' - filter: ${mapcolor9 = '4'} scale: [min, max] symbolizers: - polygon: <<: *stroke fill-color: '#FB8072' - filter: ${mapcolor9 = '5'} scale: [min, max] symbolizers: - polygon: <<: *stroke fill-color: '#80B1D3' - filter: ${mapcolor9 = '6'} scale: [min, max] symbolizers: - polygon: <<: *stroke fill-color: '#FDB462' - filter: ${mapcolor9 = '7'} scale: [min, max] symbolizers: - polygon: <<: *stroke fill-color: '#B3DE69' - filter: ${mapcolor9 = '8'} scale: [min, max] symbolizers: - polygon: <<: *stroke fill-color: '#FCCDE5' - filter: ${mapcolor9 = '9'} scale: [min, max] symbolizers: - polygon: <<: *stroke fill-color: '#D9D9D9' - filter: ${mapcolor9 <> '1' AND mapcolor9 ,→<> '2' AND mapcolor9 <> '3' AND mapcolor9 <> '4' AND ,→mapcolor9 <> '5' AND mapcolor9 <> '6' AND mapcolor9 ,→<> '7' AND mapcolor9 <> '8' AND mapcolor9 <> '9'} scale: [min, max] symbolizers: - line: <<: *stroke 936 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 4. The Layer Preview tab can be used to preview this result. 5. This YSLD makes use of a define to avoid repeating the stroke-color and stroke-width information multiple times. As an example the ${mapcolor9 = '2'} rule, combined with the define: results in the following collection of properties: - filter: ${mapcolor9 = '2'} scale: [min, max] symbolizers: - polygon: stroke-color: 'gray' stroke-width: 0.5 fill-color: '#FFFFB3' 6. Reviewing the generated SLD shows us this representation: mapcolor9 2 #ffffb3 #808080 0.5 7. There are three important functions, defined by the Symbology Encoding specification, that are often easier to use for theming than using rules. • Recode: Used the theme qualitative data. Attribute values are directly mapped to styling property such as fill or stroke-width. • Categorize: Used the theme quantitative data. Categories are defined using min and max ranges, and values are sorted into the appropriate category. 6.7. Styling Workshop 937 GeoServer User Manual, Release 2.15.1 • Interpolate: Used to smoothly theme quantitative data by calculating a styling property based on an attribute value. Theming is an activity, producing a visual result allow map readers to learn more about how an attribute is distributed spatially. We are free to produce this visual in the most efficient way possible. 8. Swap out mapcolor9 theme to use the Recode function: symbolizers: - polygon: stroke-color: 'gray' stroke-width: 0.5 fill-color: ${Recode(mapcolor9, '1','#8dd3c7', '2','#ffffb3', '3','#bebada', '4','#fb8072', '5','#80b1d3', '6','#fdb462', '7','#b3de69', '8','#fccde5', '9','#d9d9d9')} 9. The Layer Preview tab provides the same preview. 10. The Generated SLD tab shows where things get interesting. Our generated style now consists of a single Rule: ,→ 938 mapcolor9 1 #8dd3c7 2 #ffffb3 3 #bebada 4 #fb8072 5 #80b1d3 6 #fdb462 7 #b3de69 8 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 #fccde5 9 #d9d9d9 #808080 0.5 Bonus The following optional explore and challenge activities offer a chance to review and apply the ideas introduced here. The challenge activities equire a bit of creativity and research to complete. In a classroom setting you are encouraged to team up into groups, with each group taking on a different challenge. Explore Antialiasing 1. When we rendered our initial preview, without a stroke, thin white gaps (or slivers) are visible between our polygons. This effect is made more pronounced by the rendering engine making use of the Java 2D sub-pixel accuracy. This technique is primarily used to prevent an aliased (stair-stepped) appearance on diagonal lines. 2. Clients can turn this feature off using a GetMap format option: format_options=antialiasing=off; The LayerPreview provides access to this setting from the Open Layers Options Toolbar: 6.7. Styling Workshop 939 GeoServer User Manual, Release 2.15.1 3. Explore: Experiment with fill and stroke settings to eliminate slivers between polygons. Note: Answer provided at the end of the workbook. Explore Categorize 1. The Categorize function can be used to generate property values based on quantitative information. Here is an example using Categorize to color states according to size. symbolizers: - polygon: fill-color: ${Categorize(Shape_Area, '#08519c','0.5', '#3182bd','1', '#6baed6','5', '#9ecae1','60', '#c6dbef','80', '#eff3ff')} 2. An exciting use of the GeoServer shape symbols is the theming by changing the size used for pattern density. 3. Explore: Use the Categorize function to theme by datarank. Note: Answer provided at the end of the workbook. 940 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Challenge Goodness of Fit 1. A subject we touched on during labeling was the conflict resolution GeoServer performs to ensure labels do not overlap. 2. In addition to the vendor parameter for max displacement you can experiment with different values for “goodness of fit”. These settings control how far GeoServer is willing to move a label to avoid conflict, and under what terms it simply gives up: x-goodnessOfFit: 0.3 x-maxDisplacement: 130 3. You can also experiment with turning off this facility completely: x-conflictResolution: false 4. Challenge: Construct your own example using maxDisplacement and goodnessOfFit. Challenge Halo 1. The halo example used the fill color and opacity for a muted halo, while this improved readability it did not bring attention to our labels. A common design choice for emphasis is to outline the text in a contrasting color. 2. Challenge: Produce a map that uses a white halo around black text. Note: Answer provided at the end of the workbook. Challenge Theming using Multiple Attributes 1. A powerful tool is theming using multiple attributes. This is an important concept allowing map readers to perform “integration by eyeball” (detecting correlations between attribute values information). 2. Challenge: Combine the mapcolor9 and datarank examples to reproduce the following map. Note: Answer provided at the end of the workbook. 6.7. Styling Workshop 941 GeoServer User Manual, Release 2.15.1 Challenge Use of Z-Index 1. Earlier we looked at using multiple feature-styles to simulate line string casing. The line work was drawn twice, once with thick line, and then a second time with a thinner line. The resulting effect is similar to text halos - providing breathing space around complex line work allowing it to stand out. 2. Challenge: Use what you know of LineString feature-styles to reproduce the following map: Note: Answer provided at the end of the workbook. Points The next stop of the ysld styling tour is the representation of points. Review of point symbology: • Points are used to represent a location only, and do not form a shape. The visual width of lines do not change depending on scale. • SLD uses a PointSymbolizer record how the shape of a line is drawn. • Labeling of points is anchored to the point location. As points have no inherent shape of of their own, emphasis is placed on marking locations with an appropriate symbol. Reference: • YSLD Reference • YSLD Reference Point symbolizer (User Manual | YSLD Reference) • Point (User Manual | SLD Reference ) This exercise makes use of the ne:populated_places layer. 1. Navigate to the Styles page. 942 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 2. Click Add a new style and choose the following: Name: Workspace: Format: point_example No workspace YSLD 3. Choose point from the Generate a default style dropdown and click generate. 4. Replace the initial YSLD definition with the following and click apply: symbolizers: - point: symbols: - mark: shape: circle stroke-width: 1 5. And use the Layer Preview tab to preview the result. Mark The point symbolizer controls the display of point data. Points are represented with the mandatory property mark. The SLD standard provides “well-known” symbols for use with point symbology: circle, square, triangle, arrow, cross, star, and x. 1. Change the symbol used by the style to a square: symbolizers: - point: symbols: - mark: shape: square stroke-width: 1 6.7. Styling Workshop 943 GeoServer User Manual, Release 2.15.1 2. Map Preview: 3. Before we continue we will use a filter to cut down the amount of data shown to a reasonable level. rules: - filter: ${SCALERANK < '1'} scale: [min, max] symbolizers: - point: symbols: - mark: shape: square stroke-width: 1 Note: symbolizers has been indented under rules 1. Resulting in a considerably cleaner image: 2. Additional properties are available to control a mark’s presentation: The size property is used to control symbol size. The rotation property controls orientation, accepting input in degrees. Trying these two settings together: 944 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 rules: - filter: ${SCALERANK < '1'} scale: [min, max] symbolizers: - point: size: 8 rotation: 45.0 symbols: - mark: shape: square stroke-width: 1 3. Results in each location being marked with a diamond: 4. The mark property provides parameters to style the point symbol. Let’s change the fill-color to gray. rules: - filter: ${SCALERANK < '1'} scale: [min, max] symbolizers: - point: size: 8 rotation: 45.0 symbols: - mark: shape: square stroke-color: 'black' stroke-width: 1 fill-color: 'gray' 5. Updating the mark to a gray square with a black outline. 6.7. Styling Workshop 945 GeoServer User Manual, Release 2.15.1 6. You can add more symbolizers to apply additional point styles. Using this approach marks can be composed of multiple symbols, each with its own settings: rules: - filter: ${SCALERANK < '1'} scale: [min, max] symbolizers: - point: size: 16 symbols: - mark: shape: square stroke-color: 'black' stroke-width: 1 fill-color: 'red' - point: size: 14 rotation: 45.0 symbols: - mark: shape: cross stroke-color: 'white' stroke-width: 1 fill-color: 'black' 7. Producing an interesting compound symbol effect: 946 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Graphic Symbols can also be supplied by an external graphic, This technique was shown with the initial airport.svg YSLD example. 1. To use an external graphic two pieces of information are required. url property is defined with a url reference to image. format property is used to tell the rendering engine what file format to expect This technique is used to reference files placed in the styles directory. rules: - filter: ${SCALERANK < '1'} scale: [min, max] symbolizers: - point: symbols: - external: url: file:/path/to/geoserver/data_dir/styles/port.svg format: image/svg ,→ 2. Drawing the provided shape in each location: 3. The property url reference can also be used to reference external images. We can make use of the GeoServer logo. rules: - filter: ${SCALERANK < '1'} scale: [min, max] symbolizers: - point: size: 16 symbols: - external: url: ,→http://localhost:8080/geoserver/web/wicket/resource/ ,→org.geoserver.web.GeoServerBasePage/img/logo.png 6.7. Styling Workshop 947 GeoServer User Manual, Release 2.15.1 format: image/png 4. As shown in the map preview. Label Labeling is now familiar from our experience with LineString and Polygons. The text symbolizer with the label property are required to label Point Locations. 1. Replace point_example with the following: rules: - filter: ${SCALERANK < '1'} scale: [min, max] symbolizers: - point: symbols: - mark: shape: circle stroke-color: 'black' stroke-width: 1 fill-color: 'gray' - text: label: ${NAME} fill-color: 'gray' placement: point 2. Confirm the result in Layer Preview preview. 948 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 3. Each label is drawn starting from the provided point - which is unfortunate as it assures each label will overlap with the symbol used. To fix this limitation we will make use of the YSLD controls for label placement: anchor provides two values expressing how a label is aligned with respect to the starting label position. displacement is be used to provide an initial displacement using and x and y offset. For points this offset is recommended to adjust the label position away for the area used by the symbol. Note: The property anchor defines an anchor position relative to the bounding box formed by the resulting label. This anchor position is snapped to the label position generated by the point location and displacement offset. Using these two facilities together we can center our labels below the symbol, taking care that the displacement used provides an offset just outside the area required for the symbol size. rules: - filter: ${SCALERANK < '1'} scale: [min, max] symbolizers: - point: size: 10 symbols: - mark: shape: circle stroke-color: 'black' stroke-width: 1 fill-color: 'gray' - text: label: ${NAME} fill-color: 'black' placement: point anchor: [0.5, 1.0] displacement: [0, -12] 4. Each label is now placed under the mark. 6.7. Styling Workshop 949 GeoServer User Manual, Release 2.15.1 5. One remaining issue is the overlap between labels and symbols. GeoServer provides a vendor specific parameter to allow symbols to take part in label conflict resolution, preventing labels from overlapping any symbols. This severely limits the area available for labeling and is best used in conjunction with a large maximum displacement vendor option. x-labelObstacle vendor parameter asks the rendering engine to avoid drawing labels over top of the indicated symbol. This applies to the point symbolizer. x-maxDisplacement vendor parameter provides the rendering engine a maximum distance it is allowed to move labels during conflict resolution. This applies to the text symbolizer. x-spaceAround vendor parameter tells the rendering engine to provide a minimum distance between the labels on the map, ensuring they do not overlap. This applies to the text symbolizer. Update our example to use these settings: rules: - filter: ${SCALERANK < '1'} scale: [min, max] symbolizers: - point: size: 10 symbols: - mark: shape: circle stroke-color: 'black' stroke-width: 1 fill-color: 'gray' x-labelObstacle: true - text: label: ${NAME} fill-color: 'black' placement: point anchor: [0.5, 1.0] displacement: [0, -12] x-maxDisplacement: 100 x-spaceAround: 2 6. Resulting in a considerably cleaner image: 950 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Dynamic Styling 1. We will quickly use scalerank to select content based on @scale filters. define: &point size: 6 symbols: - mark: shape: circle stroke-color: 'black' stroke-width: 1 fill-color: 'gray' rules: - filter: ${SCALERANK < '7'} scale: ['4000000.0', '8000000.0'] symbolizers: - point: <<: *point - filter: ${SCALERANK < '5'} scale: ['8000000.0', '1.7E7'] symbolizers: - point: <<: *point - filter: ${SCALERANK < '4'} scale: ['1.7E7', '3.5E7'] symbolizers: - point: <<: *point - filter: ${SCALERANK < '3'} scale: ['3.5E7', '7.0E7'] symbolizers: - point: <<: *point - filter: ${SCALERANK < '2'} scale: ['7.0E7', '1.4E8'] symbolizers: - point: <<: *point - filter: ${SCALERANK < '1'} scale: ['1.4E8', max] symbolizers: 6.7. Styling Workshop 951 GeoServer User Manual, Release 2.15.1 - point: <<: *point - scale: [min, '4000000.0'] symbolizers: - point: <<: *point 2. Click Apply to update the Layer Preview after each step. Note: This YSLD makes use of a define to avoid repeating the point symbolizer content multiple times. As an example the scale: [min, '4000000.0'] rule, combined with the define: results in the following collection of properties: - scale: [min, '4000000.0'] symbolizers: - point: size: 6 symbols: - mark: shape: circle stroke-color: 'black' stroke-width: 1 fill-color: 'gray' 3. To add labeling we must use both a point and text symbolizer in each scale filter. define: &point size: 6 symbols: - mark: shape: circle stroke-color: 'black' stroke-width: 1 fill-color: 'gray' define: &label label: ${NAME} fill-color: 'black' font-family: Arial font-size: 10 952 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 font-style: normal font-weight: normal placement: point rules: - filter: ${SCALERANK < '7'} scale: ['4000000.0', '8000000.0'] symbolizers: - point: <<: *point - text: <<: *label - filter: ${SCALERANK < '5'} scale: ['8000000.0', '1.7E7'] symbolizers: - point: <<: *point - text: <<: *label - filter: ${SCALERANK < '4'} scale: ['1.7E7', '3.5E7'] symbolizers: - point: <<: *point - text: <<: *label - filter: ${SCALERANK < '3'} scale: ['3.5E7', '7.0E7'] symbolizers: - point: <<: *point - text: <<: *label - filter: ${SCALERANK < '2'} scale: ['7.0E7', '1.4E8'] symbolizers: - point: <<: *point - text: <<: *label - filter: ${SCALERANK < '1'} scale: ['1.4E8', max] symbolizers: - point: <<: *point - text: <<: *label - scale: [min, '4000000.0'] symbolizers: - point: <<: *point - text: <<: *label 6.7. Styling Workshop 953 GeoServer User Manual, Release 2.15.1 4. We will use displacement and anchor to position the label above each symbol. Add the following two lines to the label define: define: &label label: ${NAME} fill-color: 'black' font-family: Arial font-size: 10 font-style: normal font-weight: normal placement: point anchor: [0.5, 0] displacement: [0, 6] 5. A little bit of work with vendor specific parameters will prevent our labels from colliding with each symbol, while giving the rendering engine some flexibility in how far it is allowed to relocate a label. Add the following vendor options to the label define: define: &label label: ${NAME} fill-color: 'black' font-family: Arial font-size: 10 font-style: normal font-weight: normal placement: point 954 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 anchor: [0.5, 0] displacement: [0, 6] x-maxDisplacement: 90 x-spaceAround: 2 Add the following vendor option to the point define: define: &point size: 6 symbols: - mark: shape: circle stroke-color: 'black' stroke-width: 1 fill-color: 'gray' x-labelObstacle: true 6. Now that we have clearly labeled our cities, zoom into an area you are familiar with and we can look at changing symbology on a caseby-case basis. We have used expressions previous to generate an appropriate label. Expressions can also be used for many other property settings. The ne:populated_places layer provides several attributes specifically to make styling easier: • SCALERANK: we have already used this attribute to control the level of detail displayed • LABELRANK: hint used for conflict resolution, allowing important cities such as capitals to be labeled even when they are close to a larger neighbor. • FEATURECLA: used to indicate different types of cities. We will check for Admin-0 capital cities. The first thing we will do is calculate the point size using a quick expression: ${10-(SCALERANK/2)} This expression should result in sizes between 5 and 9 and will need to be applied to both point size and label displacement. 6.7. Styling Workshop 955 GeoServer User Manual, Release 2.15.1 Rather than the “first come first served” default to resolve labeling conflicts we can manually provide GeoServer with a label priority. The expression provided is calculated for each label, in the event of a conflict the label with the highest priority takes precedence. The LABELRANK attribute goes from 1 through 10 and needs to be flipped around before use as a GeoServer label priority: ${10 - LABELRANK} This expression will result in values between 0 and 10 and will be used for the priority. define: &point size: ${10-(SCALERANK/2)} symbols: - mark: shape: circle stroke-color: 'black' stroke-width: 1 fill-color: 'gray' x-labelObstacle: true define: &label label: ${NAME} fill-color: 'black' font-family: Arial font-size: 10 font-style: normal font-weight: normal placement: point anchor: [0.5, 0] displacement: [0, '${''10'' - SCALERANK / ''2''}'] priority: ${'10' - LABELRANK} x-maxDisplacement: 90 x-spaceAround: 2 7. Next we can use FEATURECLA to check for capital cities. Adding a filter for capital cities at the top of the rules list: - filter: ,→${SCALERANK < '2' AND FEATURECLA = 'Admin-0 capital'} scale: ['7.0E7', max] name: capitals 956 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 symbolizers: - point: symbols: - mark: shape: star stroke-color: 'black' stroke-width: 1 fill-color: 'gray' - text: label: ${NAME} fill-color: 'gray' placement: point - filter: ${FEATURECLA = 'Admin-0 capital'} scale: [min, '7.0E7'] name: capitals symbolizers: - point: symbols: - mark: shape: star stroke-color: 'black' stroke-width: 1 fill-color: 'gray' - text: label: ${NAME} fill-color: 'gray' placement: point And updating the populated places filters to ignore capital cities: - filter: $ ,→{SCALERANK < '7' AND FEATURECLA <> scale: ['4000000.0', '8000000.0'] symbolizers: - point: <<: *point - text: <<: *label - filter: $ ,→{SCALERANK < '5' AND FEATURECLA <> scale: ['8000000.0', '1.7E7'] symbolizers: - point: <<: *point - text: <<: *label - filter: $ ,→{SCALERANK < '4' AND FEATURECLA <> scale: ['1.7E7', '3.5E7'] symbolizers: - point: <<: *point - text: <<: *label - filter: $ ,→{SCALERANK < '3' AND FEATURECLA <> scale: ['3.5E7', '7.0E7'] symbolizers: 6.7. Styling Workshop 'Admin-0 capital'} 'Admin-0 capital'} 'Admin-0 capital'} 'Admin-0 capital'} 957 GeoServer User Manual, Release 2.15.1 - point: <<: *point - text: <<: *label - filter: $ ,→{SCALERANK < '2' AND FEATURECLA <> 'Admin-0 capital'} scale: ['7.0E7', '1.4E8'] symbolizers: - point: <<: *point - text: <<: *label - filter: $ ,→{SCALERANK < '1' AND FEATURECLA <> 'Admin-0 capital'} scale: ['1.4E8', max] symbolizers: - point: <<: *point - text: <<: *label - scale: [min, '4000000.0'] symbolizers: - point: <<: *point - text: <<: *label 8. If you would like to check your work the final file is here: point_example.ysld Bonus Challenge Geometry Location 1. The mark property can be used to render any geometry content. 2. Challenge: Try this yourself by rendering a polygon layer using a mark property. Note: Answer discussed at the end of the workbook. 958 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Explore Dynamic Symbolization 1. We went to a lot of work to set up filters to choose between star and circle for capital cities. This approach is straightforward when applied in isolation: rules: - filter: ${FEATURECLA = 'Admin-0 capital'} scale: [min, max] symbolizers: - point: symbols: - mark: shape: star stroke-color: 'black' stroke-width: 1 fill-color: 'gray' - filter: ${FEATURECLA <> 'Admin-0 capital'} scale: [min, max] symbolizers: - point: symbols: - mark: shape: circle stroke-color: 'black' stroke-width: 1 fill-color: 'gray' When combined with checking another attribute, or checking @scale as in our example, this approach can quickly lead to many rules which can be difficult to keep straight. 2. Taking a closer look, shape can actually be expressed using a string: rules: - filter: ${FEATURECLA = 'Admin-0 capital'} scale: [min, max] symbolizers: - point: symbols: - mark: shape: 'star' stroke-color: 'black' stroke-width: 1 fill-color: 'gray' Which is represented in SLD as: star 6.7. Styling Workshop 959 GeoServer User Manual, Release 2.15.1 3. GeoServer recognizes this limitation of SLD Mark and ExternalGraphic and provides an opportunity for dynamic symbolization. This is accomplished by embedding a small CQL expression in the string passed to symbol or url. This sub-expression is isolated with ${ } as shown: - point: symbols: - mark: shape: ${if_then_else(equalTo(FEATURECLA, ,→'Admin-0 capital'),'star','circle')} Which is represented in SLD as: ,→${if_then_else(equalTo(FEATURECLA,'Admin,→0 capital'),'star','circle')} 4. Challenge: Use this approach to rewrite the Dynamic Styling example. Note: Answer provided at the end of the workbook. Challenge Layer Group 1. Use a Layer Group to explore how symbology works together to form a map. • ne:NE1 • ne:states_provincces_shp • ne:populated_places 2. To help start things out ne:states_provinces_shp: here is a style for symbolizers: - polygon: stroke-color: 'black' stroke-width: 0.25 stroke-opacity: 0.5 fill-color: 'white' fill-opacity: 0.05 - polygon: stroke-color: 'black' stroke-width: 0.25 stroke-opacity: 0.5 960 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 fillcolor: ${Recode(mapcolor9,'1','#8dd3c7','2','#ffffb3 ,→','3','#bebada','4','#fb8072','5','#80b1d3','6', ,→'#fdb462','7','#b3de69','8','#fccde5','9','#d9d9d9')} fill-opacity: 0.5 ,→ 3. This background is relatively busy and care must be taken to ensure both symbols and labels are clearly visible. 4. Challenge: Do your best to style populated_places over this busy background. Here is an example with labels for inspiration: Note: Answer provided at the end of the workbook. Explore True Type Fonts 1. In addition to image formats GeoServer can make use other kinds of graphics, such as True Type fonts: symbolizers: - point: symbols: - mark: shape: ttf://Webdings#0x0064 stroke-color: 'blue' stroke-width: 1 2. Additional fonts dropped in the styles directory are available for use. Explore Custom Graphics 1. The GeoServer rendering engine allows Java developers to hook in additional symbol support. 6.7. Styling Workshop 961 GeoServer User Manual, Release 2.15.1 This facility is used by GeoServer to offer the shapes used for pattern fills. Community extensions allow the use of simple custom shapes and even charts. 2. Support has been added for custom graphics using the WKT Geometry representation. symbolizers: - point: symbols: - mark: shape: wkt://MULTILINESTRING((,→0.25 -0.25, -0.125 -0.25), (0.125 -0.25, 0.25 -0.25), ,→ (-0.25 0.25, -0.125 0.25), (0.125 0.25, 0.25 0.25)) stroke-color: 'blue' stroke-width: 1 Rasters Finally we will look at using YSLD styling for the portrayal of raster data. Fig. 6.307: Raster Symbology Review of raster symbology: • Raster data is Grid Coverage where values have been recorded in a regular array. In OGC terms a Coverage can be used to look up a value or measurement for each location. • When queried with a “sample” location: – A grid coverage can determine the appropriate array location and retrieve a value. Different techniques may be used interpolate an appropriate value from several measurements (higher quality) or directly return the “nearest neighbor” (faster). – A vector coverages would use a point-in-polygon check and return an appropriate attribute value. – A scientific model can calculate a value for each sample location • Many raster formats organize information into bands of content. Values recorded in these bands and may be mapped into colors for display (a process similar to theming an attribute for vector data). For imagery the raster data is already formed into red, green and blue bands for display. • As raster data has no inherent shape, the format is responsible for describing the orientation and location of the grid used to record measurements. These raster examples use a digital elevation model consisting of a single band of height measurements. The imagery examples use an RGB image that has been hand coloured for use as a base map. Reference: 962 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 • YSLD Reference • Raster (YSLD Reference | Raster symbolizer) • Raster (User Manual | SLD Reference ) The exercise makes use of the usgs:dem and ne:ne1 layers. Image The raster symbolizer controls the display of raster data. By default, the raster symbolizer automatically selects the appropriate red, green and blue channels for display. 1. Navigate to the Styles page. 2. Click Add a new style and choose the following: Name: Workspace: Format: image_example No workspace YSLD 3. Choose raster from the Generate a default style dropdown and click generate. 4. Replace the initial YSLD definition with: symbolizers: - raster: opacity: 1.0 5. And use the Layer Preview tab to preview the result. 6. The channels property can be used to provide a list three band numbers (for images recording in several wave lengths) or a single band number can be used to view a grayscale image. symbolizers: - raster: opacity: 1.0 channels: gray: name: '2' 6.7. Styling Workshop 963 GeoServer User Manual, Release 2.15.1 7. Isolating just the green band (it wil be drawn as a grayscale image): DEM A digital elevation model is an example of raster data made up of measurements, rather than color information. The usgs:dem layer used used for this exercise: 1. Return to the the Styles page. 2. Click Add a new style and choose the following: Name: Workspace: Format: raster_example No workspace YSLD 3. Choose raster from the Generate a default style dropdown and click generate. 4. The rendering engine will select our single band of raster content, and do its best to map these values into a grayscale image. Replace the content of the style with: symbolizers: - raster: opacity: 1.0 5. Use the Layer Preview tab to preview the result. The range produced in this case from the highest and lowest values. 6. We can use a bit of image processing to emphasis the generated color mapping by making use of contrast-enhancement. 964 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 symbolizers: - raster: opacity: 1.0 channels: gray: name: '1' contrast-enhancement: mode: histogram 7. Image processing of this sort should be used with caution as it does distort the presentation (in this case making the landscape look more varied then it is in reality. Color Map The approach of mapping a data channel directly to a color channel is only suitable to quickly look at quantitative data. For qualitative data (such as land use) or simply to use color, we need a different approach: Note: We can use a color map to artificially color a single band raster introducing smooth graduations for elevation or tempurature models or clear differentiation for qualitative data. 1. Apply the following YAML to our usgs:DEM layer: symbolizers: - raster: opacity: 1.0 color-map: type: ramp entries: - ['#9080DB', - ['#008000', - ['#105020', - ['#FFFFFF', 1.0, 1.0, 1.0, 1.0, 0, null] 1, null] 255, null] 4000, null] 2. Resulting in this artificial color image: 6.7. Styling Workshop 965 GeoServer User Manual, Release 2.15.1 3. An opacity value can also be used with each color-map entry. symbolizers: - raster: opacity: 1.0 color-map: type: ramp entries: - ['#9080DB', - ['#008000', - ['#105020', - ['#FFFFFF', 0.0, 1.0, 1.0, 1.0, 0, null] 1, null] 255, null] 4000, null] 4. Allowing the areas of zero height to be transparent: Note: Raster format for GIS work often supply a “no data” value, or contain a mask, limiting the dataset to only the locations with valid information. Custom We can use what we have learned about color maps to apply a color brewer palette to our data. This exploration focuses on accurately communicating differences in value, rather than strictly making a pretty picture. Care should be taken to consider the target audience and medium used during palette selection. 1. Restore the raster_example YSLD style to the following: symbolizers: - raster: opacity: 1.0 2. Producing the following map preview. 966 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 3. To start with we can provide our own grayscale using two color map entries. symbolizers: - raster: opacity: 1.0 color-map: type: ramp entries: - ['#000000', 1.0, 0, null] - ['#FFFFFF', 1.0, 4000, null] 4. Use the Layer Preview tab to zoom in and take a look. This is much more direct representation of the source data. We have used our knowledge of elevations to construct a more accurate style. 5. While our straightforward style is easy to understand, it does leave a bit to be desired with respect to clarity. The eye has a hard time telling apart dark shades of black (or bright shades of white) and will struggle to make sense of this image. To address this limitation we are going to switch to the ColorBrewer 9-class PuBuGn palette. This is a sequential palette that has been hand tuned to communicate a steady change of values. 6. Update your style with the following: 6.7. Styling Workshop 967 GeoServer User Manual, Release 2.15.1 symbolizers: - raster: opacity: 1.0 color-map: type: ramp entries: - ['#014636', - ['#016C59', - ['#02818A', - ['#3690C0', - ['#67A9CF', - ['#A6BDDB', - ['#D0D1E6', - ['#ECE2F0', - ['#FFF7FB', 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0, null] 500, null] 1000, null] 1500, null] 2000, null] 2500, null] 3000, null] 3500, null] 4000, null] 7. A little bit of work with alpha (to mark the ocean as a no-data section): symbolizers: - raster: opacity: 1.0 color-map: type: ramp entries: - ['#014636', - ['#014636', - ['#016C59', - ['#02818A', - ['#3690C0', - ['#67A9CF', - ['#A6BDDB', - ['#D0D1E6', - ['#ECE2F0', - ['#FFF7FB', 0, 0, null] 1.0, 1, null] 1.0, 500, null] 1.0, 1000, null] 1.0, 1500, null] 1.0, 2000, null] 1.0, 2500, null] 1.0, 3000, null] 1.0, 3500, null] 1.0, 4000, null] 8. And we are done: 968 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Bonus Explore Contrast Enhancement 1. A special effect that is effective with grayscale information is automatic contrast adjustment. 2. Make use of a simple contrast enhancement with usgs:dem: symbolizers: - raster: opacity: 1.0 contrast-enhancement: mode: normalize 1. Can you explain what happens when zoom in to only show a land area (as indicated with the bounding box below)? Note: Discussion provided at the end of the workbook. Challenge Intervals 1. The color-map type property dictates how the values are used to generate a resulting color. 6.7. Styling Workshop 969 GeoServer User Manual, Release 2.15.1 • ramp is used for quantitative data, providing a smooth interpolation between the provided color values. • intervals provides categorization for quantitative data, assigning each range of values a solid color. • values is used for qualitative data, each value is required to have a color-map entry or it will not be displayed. 2. Chalenge: Update your DEM example to use intervals for presentation. What are the advantages of using this approach for elevation data? Note: Answer provided at the end of the workbook. Explore Image Processing Additional properties are available to provide slight image processing during visualization. Note: In this section are we going to be working around a preview issue where only the top left corner of the raster remains visible during image processing. This issue has been reported as GEOS-6213. Image processing can be used to enhance the output to highlight small details or to balance images from different sensors allowing them to be compared. 1. The contrast-enhancement property is used to turn on a range of post processing effects. Settings are provided for normalize or histogram or none; symbolizers: - raster: opacity: 1.0 contrast-enhancement: mode: normalize 1. Producing the following image: 970 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 2. The raster-gamma property is used adjust the brightness of contrast-enhancement output. Values less than 1 are used to brighten the image while values greater than 1 darken the image. symbolizers: - raster: opacity: 1.0 contrast-enhancement: gamma: 1.5 1. Providing the following effect: Challenge Clear Digital Elevation Model Presentation 1. Now that you have seen the data on screen and have a better understanding how would you modify our initial gray-scale example? 2. Challenge: Use what you have learned to present the usgs:dem clearly. Note: Answer provided at the end of the workbook. Challenge Raster Opacity 1. There is a quick way to make raster data transparent, raster opacity property works in the same fashion as with vector data. The raster as a whole will be drawn partially transparent allow content from other layers to provide context. 2. Challenge: Can you think of an example where this would be useful? Note: Discussion provided at the end of the workbook. 6.7. Styling Workshop 971 GeoServer User Manual, Release 2.15.1 YSLD Workbook Conclusion We hope you have enjoyed this styling workshop. Additional resources: • YSLD Extension • YSLD Reference YSLD Tips and Tricks Converting to YSLD The REST API can be used to convert any of your existing CSS or SLD styles to YSLD. 1. Navigate to the rest api endpoint for styles: • view-source:http://localhost:8080/geoserver/rest/styles Note: Using view-source: in chrome or firefox allows us to focus on page content. 2. Click on one of the styles (for example states.html) 3. Click on the link to the style contents • view-source:http://localhost:8080/geoserver/rest/styles/states.sld 4. Change the URL with ?pretty=true for human readable XML. • view-source:http://localhost:8080/geoserver/rest/styles/states.sld?pretty=true 5. Change the URL with yaml to convert to YSLD. • view-source:http://localhost:8080/geoserver/rest/styles/states.yaml The original SLD file is convert to YSLD: name: states title: Population in the United States abstract: |A sample ,→filter that filters the United States into three ,→ categories of population, drawn in different colors feature-styles: - name: name rules: - name: Population < 2M title: Population < 2M filter: ${PERSONS < '2000000'} scale: [min, max] symbolizers: - polygon: fill-color: '#A6CEE3' fill-opacity: 0.7 - name: Population 2M-4M 972 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 - - - - title: Population 2M-4M filter: ${PERSONS BETWEEN '2000000' AND '4000000'} scale: [min, max] symbolizers: - polygon: fill-color: F78B4 fill-opacity: 0.7 name: '> 4M' title: Population > 4M filter: ${PERSONS > '4000000'} scale: [min, max] symbolizers: - polygon: fill-color: '#B2DF8A' fill-opacity: 0.7 name: State Outlines title: State Outlines scale: [min, max] symbolizers: - line: stroke-color: '#8CADBF' stroke-width: 0.1 name: State Abbreviations title: State Abbreviations scale: ['1.75E7', '3.5E7'] symbolizers: - text: label: ${STATE_ABBR} font-family: SansSerif font-size: 12 font-style: Normal font-weight: normal placement: point anchor: [0.5, 0.5] name: State Names title: State Names scale: [min, '1.75E7'] symbolizers: - text: label: ${STATE_NAME} font-family: SansSerif font-size: 12 font-style: Normal font-weight: normal placement: point anchor: [0.5, 0.5] x-maxDisplacement: 100 x-goodnessOfFit: 0.9 YSLD Workshop Answer Key The following questions were listed through out the workshop as an opportunity to explore the material in greater depth. Please do your best to consider the questions in detail prior to checking here for the answer. Questions are provided to teach valuable skills, such as a chance to understand how feature type styles are used to control 6.7. Styling Workshop 973 GeoServer User Manual, Release 2.15.1 z-order, or where to locate information in the user manual. Classification Answer for Challenge Classification: 1. Challenge: Create a new style adjust road appearance based on type. Hint: The available values are ‘Major Highway’,’Secondary Highway’,’Road’ and ‘Unknown’. 2. Here is an example: define: &common stroke-opacity: 0.25 rules: - filter: ${type = 'Major Highway'} symbolizers: - line: stroke-color: '#000088' stroke-width: 1.25 <<: *common - filter: ${type = 'Secondary Highway'} symbolizers: - line: stroke-color: '#8888AA' stroke-width: 0.75 <<: *common - filter: ${type = 'Road'} symbolizers: - line: stroke-color: '#888888' stroke-width: 0.75 <<: *common - filter: ${type = 'Unknown'} symbolizers: - line: stroke-color: '#888888' stroke-width: 0.5 <<: *common - else: true symbolizers: - line: stroke-color: '#AAAAAA' stroke-width: 0.5 <<: *common 974 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 One Rule Classification Answer for Challenge One Rule Classification: 1. Challenge: Create a new style and classify the roads based on their scale rank using expressions in a single rule instead of multiple rules with filters. 2. This exercise requires looking up information in the user guide, the search tearm recode provides several examples. • The YSLD Reference theming functions provides a clear example. Label Shields Answer for Challenge Label Shields: 1. Challenge: Have a look at the documentation for putting a graphic on a text symbolizer in SLD and reproduce this technique in YSLD. 2. The use of a label shield is a vendor specific capability of the GeoServer rendering engine. The tricky part of this exercise is finding the documentation online ( i.e. TextSymbolizer - Graphic). symbolizers: - line: stroke-color: '#000000' stroke-width: 3 - line: stroke-color: '#D3D3D3' stroke-width: 2 - text: label: ${name} fill-color: '#000000' font-family: Ariel font-size: 10 font-style: normal font-weight: normal placement: point graphic: size: 18 symbols: - mark: 6.7. Styling Workshop 975 GeoServer User Manual, Release 2.15.1 shape: square stroke-color: '#000000' stroke-width: 1 fill-color: '#FFFFFF' Antialiasing Answer for Explore Antialiasing: 1. When we rendered our initial preview, without a stroke, thin white gaps (or slivers) are visible between our polygons. This effect is made more pronounced by the rendering engine making use of the Java 2D sub-pixel accuracy. This technique is primarily used to prevent an aliased (stair-stepped) appearance on diagonal lines. 2. Explore: Experiment with fill and stroke settings to eliminate slivers between polygons. The obvious approach works - setting both values to the same color: symbolizers: - polygon: stroke-color: 'lightgrey' stroke-width: 1 fill-color: 'lightgrey' Categorize Answer for Explore Categorize: 1. An exciting use of the GeoServer shape symbols is the theming by changing the size used for pattern density. 2. Explore: Use the Categorize function to theme by datarank. Example: 976 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 symbolizers: - polygon: stroke-color: 'black' stroke-width: 1 fill-color: 'gray' fill-graphic: size: ,→${Categorize(datarank,'4','4','5','6','8','10','10')} symbols: - mark: shape: shape://slash stroke-color: 'darkgray' stroke-width: 1 Halo Answer for Challenge Halo: 1. The halo example used the fill color and opacity for a muted halo, while this improved readability it did not bring attention to our labels. A common design choice for emphasis is to outline the text in a contrasting color. 2. Challenge: Produce a map that uses a white halo around black text. Here is an example: symbolizers: - polygon: stroke-color: 'gray' stroke-width: 1 fill-color: '#7EB5D3' - text: label: ${name} fill-color: 'black' halo: fill-color: 'white' radius: 1 font-family: Arial font-size: 14 font-style: normal font-weight: normal anchor: [0.5, 0.5] Theming using Multiple Attributes Answer for Challenge Theming using Multiple Attributes: 1. A powerful tool is theming using multiple attributes. This is an important concept allowing map readers to perform “integration by eyeball” (detecting correlations between attribute values information). 6.7. Styling Workshop 977 GeoServer User Manual, Release 2.15.1 2. Challenge: Combine the mapcolor9 and datarank examples to reproduce the following map. This should be a cut and paste using the recode example, and categorize examples already provided. symbolizers: - polygon: stroke-color: 'black' stroke-width: 1 fill-color: ${Recode(mapcolor9, '1','#8dd3c7', '2','#ffffb3', '3','#bebada', '4','#fb8072', '5','#80b1d3', '6','#fdb462', '7','#b3de69', '8','#fccde5', '9','#d9d9d9')} - polygon: stroke-color: 'black' stroke-width: 1 fill-color: 'gray' fill-graphic: size: $ ,→{Categorize(datarank,'6','4','8','6','10','10','12')} symbols: - mark: shape: shape://slash stroke-color: 'black' stroke-width: 1 fill-color: 'gray' Use of Feature styles Answer for Challenge Use of Feature styles: 1. Using multiple feature-styles to simulate line string casing. The resulting effect is similar to text halos - providing breathing space around complex line work allowing it to stand out. 2. Challenge: Use what you know of LineString feature-styles to reproduce the following map: 978 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 This is much easier when using YSLD, where z-order is controlled by feature-style order. In this instance, multiple symbolizers within a feature-style will not work, as the order within a feature-style is only consistent per-feature (not per-layer). feature-styles: - rules: - symbolizers: - polygon: stroke-width: 1.0 fill-color: 'lightgrey' - rules: - symbolizers: - polygon: stroke-width: 1.0 fill-color: 'gray' fill-graphic: size: 8 symbols: - mark: shape: shape://slash stroke-color: 'black' stroke-width: 0.75 - rules: - symbolizers: - line: stroke-color: 'lightgrey' stroke-width: 6 - rules: - symbolizers: - line: stroke-color: 'black' stroke-width: 1.5 The structure of the legend graphic provides an indication on what is going on. Geometry Location Answer for Challenge Geometry Location: 1. The mark property can be used to render any geometry content. 6.7. Styling Workshop 979 GeoServer User Manual, Release 2.15.1 2. Challenge: Try this yourself by rendering a polygon layer using a mark property. This can be done one of two ways: • Changing the association of a polygon layer, such as ne:states_provinces_shp to point_example and using the layer preview page. • Changing the Layer Preview tab to a polygon layer, such as ne:states_provinces_shp. The important thing to notice is that the centroid of each polygon is used as a point location. Dynamic Symbolization Answer for Explore Dynamic Symbolization: 1. SLD Mark and ExternalGraphic provide an opportunity for dynamic symbolization. This is accomplished by embedding a small CQL expression in the string passed to symbol or url. This sub-expression is isolated with ${ } as shown: - point: symbols: - mark: shape: ${if_then_else(equalTo(FEATURECLA, ,→'Admin-0 capital'),'star','circle')} 2. Challenge: Use this approach to rewrite the Dynamic Styling example. Example available here point_example.css : Layer Group Answer for Challenge Layer Group: 1. Use a Layer Group to explore how symbology works together to form a map. • ne:NE1 • ne:states_provincces_shp • ne:populated_places 2. This background is relatively busy and care must be taken to ensure both symbols and labels are clearly visible. 3. Challenge: Do your best to style populated_places over this busy background. Here is an example with labels for inspiration: 980 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 This is opportunity to revisit label halo settings from Polygons: symbolizers: - point: size: ${'5' + '10' - SCALERANK / '3'} symbols: - mark: shape: circle stroke-color: 'white' stroke-width: 1 stroke-opacity: 0.75 fill-color: 'black' x-labelObstacle: true - text: label: ${name} fill-color: 'black' font-family: Arial font-size: 14 anchor: [0.5, 1] offset: [0 ${'-12' + SCALERANK}] halo: fill-color: `lightgray` radius: 2 opacity: 0.7 priority: ${`0` - LABELRANK} x-maxDisplacement: 90 Using a lightgray halo, 0.7 opacity and radius 2 fades out the complexity immediately surrounding the label text improving legibility. Contrast Enhancement Discussion for Explore Contrast Enhancement: 1. A special effect that is effective with grayscale information is automatic contrast adjustment. 2. Make use of a simple contrast enhancement with usgs:dem: symbolizers: - raster: opacity: 1.0 6.7. Styling Workshop 981 GeoServer User Manual, Release 2.15.1 contrast-enhancement: mode: normalize 3. Can you explain what happens when zoom in to only show a land area (as indicated with the bounding box below)? What happens is insanity, normalize stretches the palette of the output image to use the full dynamic range. As long as we have ocean on the screen (with value 0) the land area was shown with roughly the same presentation. Once we zoom in to show only a land area, the lowest point on the screen (say 100) becomes the new black, radically altering what is displayed on the screen. Intervals Answer for Challenge Intervals: 1. The color-map type property dictates how the values are used to generate a resulting color. • ramp is used for quantitative data, providing a smooth interpolation between the provided color values. • intervals provides categorization for quantitative data, assigning each range of values a solid color. 982 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 • values is used for qualitative data, each value is required to have a color-map entry or it will not be displayed. 2. Chalenge: Update your DEM example to use intervals for presentation. What are the advantages of using this approach for elevation data? By using intervals it becomes very clear how relatively flat most of the continent is. The ramp presentation provided lots of fascinating detail which distracted from this fact. Here is style for you to cut and paste: symbolizers: - raster: opacity: 1.0 color-map: type: intervals entries: - ['#014636', 0, 0, null] - ['#014636', 1.0, 1, null] - ['#016C59', 1.0, 500, null] - ['#02818A', 1.0, 1000, null] - ['#3690C0', 1.0, 1500, null] - ['#67A9CF', 1.0, 2000, null] - ['#A6BDDB', 1.0, 2500, null] - ['#D0D1E6', 1.0, 3000, null] - ['#ECE2F0', 1.0, 3500, null] - ['#FFF7FB', 1.0, 4000, null] Clear Digital Elevation Model Presentation Answer for Challenge Clear Digital Elevation Model Presentation: 1. Now that you have seen the data on screen and have a better understanding how would you modify our initial gray-scale example? 2. Challenge: Use what you have learned to present the usgs:dem clearly. 6.7. Styling Workshop 983 GeoServer User Manual, Release 2.15.1 The original was a dark mess. Consider making use of mid-tones (or adopting a sequential palette from color brewer) in order to fix this. In the following example the ocean has been left dark, allowing the mountains stand out more. symbolizers: - raster: opacity: 1.0 color-map: type: ramp entries: - ['#000000', 1.0, 0, null] - ['#444444', 1.0, 1, null] - ['#FFFFFF', 1.0, 3000, null] Raster Opacity Discussion for Challenge Clear Digital Elevation Model Presentation: 1. There is a quick way to make raster data transparent, raster opacity property works in the same fashion as with vector data. The raster as a whole will be drawn partially transparent allow content from other layers to provide context. 2. Challenge: Can you think of an example where this would be useful? This is difficult as raster data is usually provided for use as a basemap, with layers being drawn over top. The most obvious example here is the display of weather systems, or model output such as fire danger. By drawing the raster with some transparency, the landmass can be shown for context. 6.7.5 MBStyle Styling Workbook GeoServer styling can be used for a range of creative effects. This section introduces the MBStyle Extension which can be used as alternative to SLD files. 984 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 MBStyle Quickstart In the last section, we saw how the OGC defines style using XML documents (called SLD files). We will now explore GeoServer styling in greater detail using a tool to generate our SLD files. The MBStyle GeoServer extension is used to generate SLD files using the MabBox Style styling language. Styles written in this language can also be used to style vector tiles in client-side applications. Using the MBStyle extension to define styles results in shorter examples that are easier to understand. At any point we will be able to review the generated SLD file. Reference: • MBStyle Reference MBStyle Syntax This section provides a quick introduction to MBStyle syntax for mapping professionals who may not be familiar with JSON. JSON Syntax All MBStyles consist of a JSON document. There are three types of structures in a JSON document: 1. Object, a collection of key-value pairs. All JSON documents are JSON objects. 2. Array, a collection of values. 3. Value, the value in a key-value pair, or an entry in an array. Values can be objects, arrays, strings, numbers, true, false, or null. ObA collection of key-value pairs, enclosed by curly braces and delimited by commas. Keys are ject surronded by quotes and seperarted from values by a colon. ArA collection values, enclosed by square brackets and delimited by commas. ray String Text value. Must be surrounded by quotes. Num- Numerical value. Must not be surrounded by quotes. ber Booleantrue or false. Null null. Represents an undefined or unset value. MBStyle Specification The Mapbox Style specification defines a number of additional rules that MBStyles must follow. 6.7. Styling Workshop 985 GeoServer User Manual, Release 2.15.1 Root-level Properties Root level properties of a Mapbox style specify the map’s layers, tile sources and other resources, and default values for the initial camera position when not specified elsewhere. The following root-level properties are required for all MBStyles. Additional root-level properties which are supported but not required can be found in the spec. version name sources layers The version of the Mapbox Style specification to use. Must be set to 8. The name of the style. An object defining the source data. Not used by GeoServer. An array of layer style objects For example: { "version": 8, "name": "Streets", "sources": {...}, "layers": [...] } Sources The sources parameter consists of a collection of named sources which define vector tile data the style is to be applied to. This is only used for MBStyles used in client-side applications, and is ignored by GeoServer. If you are only using MBStyles to style your layers within GeoServer, you don’t need a sources parameter. However, if you also want to use your MBStyles for client-side styling, you will need the sources parameter. A GeoServer vector tile source would be defined like this: { "cookbook": { "type": "vector", "tiles": [ "http://localhost:8080/geoserver/gwc/ ,→service/wmts?REQUEST=GetTile&SERVICE=WMTS&VERSION=1. ,→0.0&LAYER=cookbook&STYLE=&TILEMATRIX=EPSG:900913: ,→{z}&TILEMATRIXSET=EPSG:900913&FORMAT=application/x,→protobuf;type=mapbox-vector&TILECOL={x}&TILEROW={y}" ], "minZoom": 0, "maxZoom": 14 } } 986 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Layers The layers parameter contains the primary layout and styling information in the MBStyle. Each layer in the layers list is a self-contained block of styling information. Layers are applied in order, so the last layer in the layers list will be rendered at the top of the image. Note: A layer in an MBStyle is not the same as a layer in GeoServer. A GeoServer layer is a raster or vector dataset that represents a collection of geographic features. A MBStyle layer is a block of styling information, similar to a SLD Symbolizer. Reference: • MBStyle Styling (User Guide) • Mapbox Style specification Compare MBStyle to SLD The MBStyle extension is built with the same GeoServer rendering engine in mind, providing access to most of the functionality of SLD. The two approaches use slightly different terminology: SLD uses terms familiar to mapping professionals, while MBStyle uses ideas more familiar to web developers. SLD Style Here is an example SLD file for reference: airports Airports airports Airports image/svg 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 6.7. Styling Workshop 987 GeoServer User Manual, Release 2.15.1 16 23 24 25 26 27 28 29 30 MBStyle Style Here is the same example as MBStyle: 1 { 2 "version": 8, "name": "airports", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites", "layers": [ { "id": "airports", "type": "symbol", "layout": { "icon-image": "airport" } } ] } 3 4 5 6 7 8 9 10 11 12 13 14 We use a point symbolizer to indicate we want this content drawn as a Point (line 16 in the SLD, line 8 in the MBStyle). The point symbolizer declares an external graphic, which contains the URL airports.svg indicating the image that should be drawn (line 20 in the SLD, line 10 in the MBStyle). Note: Rather than refer to many diffferent icons seperatly, MBStyles use a single spritesheet containing all the necessary icons for the style. This is defined by the sprite property at the top-level of the style. Tour To confirm everything works, let’s reproduce the airports style above. 1. Navigate to the Styles page. 2. Each time we edit a style, the contents of the associated SLD file are replaced. Rather then disrupt any of our existing styles we will create a new style. Click Add a new style and choose the following: Name: Workspace: Format: 988 airports0 (leave empty) MBStyle Chapter 6. Styling GeoServer User Manual, Release 2.15.1 3. Replace the initial MBStyle definition with with our airport MBStyle example and click Apply: { "version": 8, "name": "airports", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites", "layers": [ { "id": "airports", "type": "symbol", "layout": { "icon-image": "airport" } } ] } 4. Click the Layer Preview tab to preview the style. We want to preview on the aiports layer, so click the name of the current layer and select ne:airports from the list that appears. You can use the mouse buttons to pan and scroll wheel to change scale. Fig. 6.308: Choosing the airports layer 5. Click Layer Data for a summary of the selected data. Bonus Finished early? For now please help your neighbour so we can proceed with the workshop. If you are really stuck please consider the following challenge rather than skipping ahead. 6.7. Styling Workshop 989 GeoServer User Manual, Release 2.15.1 Fig. 6.309: Layer preview Fig. 6.310: Layer attributes 990 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 Explore Data 1. Return to the Data tab and use the Compute link to determine the minimum and maximum for the scalerank attribute. Challenge Compare SLD Generation 1. The rest API can be used to review your YAML file directly. Browser: • view-source:http://localhost:8080/geoserver/rest/styles/airport0.json Command line: curl -v -u admin:geoserver -XGET http:/ ,→/localhost:8080/geoserver/rest/styles/airports0.json 1. The REST API can also be used generate an SLD file: Browser: • view-source:http://localhost:8080/geoserver/rest/styles/airport0.sld?pretty=true Command line: curl -v -u admin:geoserver -XGET http://localhost:8080/ ,→geoserver/rest/styles/airports0.sld?pretty=true 1. Compare the generated SLD differ above with the hand written SLD file used as an example? Challenge: What differences can you spot? Lines We will start our tour of MBStyle styling by looking at the representation of lines. Fig. 6.311: LineString Geometry Review of line symbology: • Lines can be used to represent either abstract concepts with length but not width such as networks and boundaries, or long thin features with a didth that is too smallt o represent on the map. This means that the visual width of line symbols do not normally change depending on scale. • Lines are recorded as LineStrings or Curves depending on the geometry model used. • SLD uses a LineSymbolizer to record how the shape of a line is drawn. The primary characteristic documented is the Stroke used to draw each segment between vertices. 6.7. Styling Workshop 991 GeoServer User Manual, Release 2.15.1 • Labeling of line work is anchored to the mid-point of the line. GeoServer provides a vendor option to allow label rotation aligned with line segments. For our exercises we are going to be using simple MBStyle documents, often consisting of a single layer, in order to focus on the properties used for line symbology. Each exercise makes use of the ne:roads layer. Reference: • MBStyle Reference • MapBox Style Spec Line Layer • LineString (User Manual | SLD Reference ) Line A line layer is represented by the line type. Fig. 6.312: Basic Stroke Properties 1. Navigate to the Styles page. 2. Click Add a new style and choose the following: New style name: Workspace for new layer: Format: line_example Leave blank MBStyle 3. Fill in the style editor { "version": 8, "name": "line_example", "layers": [ { "id": "line_example", "source-layer": "ne:roads", "type": "line", } ] } 4. Click Apply 5. Click Layer Preview to see your new style applied to a layer. You can use this tab to follow along as the style is edited, it will refresh each time Apply is pressed. 992 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 6. You can see the equivalent SLD by requesting http:/ /localhost:8080/geoserver/rest/styles/ line_example.sld?pretty=true which will currently show the default line symbolizer we created. ,→ line_example line_example name We only specified the line layer, so all of the boilerplate arround was generated for us. 1. Additional properties cane be used fine-tune appearance. Use linecolor to specify the colour and width of the line. { "paint": { "line-color": "blue" } } 2. line-width lets us make the line wider { "paint": { "line-color": "blue", "line-width": 2 } } 6.7. Styling Workshop 993 GeoServer User Manual, Release 2.15.1 3. line-dasharray applies a dot dash pattern. { "paint": { "line-color": "blue", "line-width": 2, "line-dasharray": [5, 2] } } 4. Check the Map tab to preview the result. Multiple Layers Providing two strokes is often used to provide a contrasting edge (called casing) to thick lines. This can be created using two layers. 1. Start by filling in a bit of boilerplate that we’ll be using { "version": 8, "name": "line_example", "layers": [ { "id": "line_example", "source-layer": "ne:roads", "type": "line", "paint": { "line-color": "#8080E6", "line-width": 3, } } ] } 2. Add a second layer to the rule { "version": 8, "name": "line_example", "layers": [ { "id": "line_casing", "source-layer": "ne:roads", "type": "line", "paint": { 994 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 "line-color": "black", "line-width": 5, } }, { "id": "line_center", "source-layer": "ne:roads", "type": "line", "paint": { "line-color": "#8080E6", "line-width": 3, } } ] } The wider black line is first so it is drawn first, then the thinner blue line drawn second and so over top of the black line. This is called the painter’s algorithm. Label Our next example is significant as it introduces how text labels are generated. Fig. 6.313: Use of Label Property This is also our first example making use of a dynamic style (where a value comes from an attribute from your data). 1. To enable LineString labeling we add a symbol layer with a text-field. Update line_example with the following: { "version": 8, "name": "line_example", "layers": [ { "id": "line", "source-layer": "ne:roads", "type": "line", "paint": { "line-color": "blue", "line-width": 1, } }, 6.7. Styling Workshop 995 GeoServer User Manual, Release 2.15.1 { "id": "label", "source-layer": "ne:roads", "type": "symbol", "layout": { "text-field": "{name}" } } ] } 2. The SLD standard documents the default label position for each kind of Geometry. For LineStrings the initial label is positioned on the midway point of the line. 3. We have used a feature property calculate a value for the label. The label is generated dynamically from the name attribute. Feature properties are supplied within curly braces, and must match the name of a property of the feature type. { "version": 8, "name": "line_example", "layers": [ { "id": "line", "source-layer": "ne:roads", "type": "line", "paint": { "line-color": "blue", "line-width": 1, } }, { "id": "label", "source-layer": "ne:roads", "type": "symbol", "layout": { "text-field": "{name}" } } ] } 996 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 4. Additional keys can be supplied to fine-tune label presentation: { "version": 8, "name": "line_example", "layers": [ { "id": "line", "source-layer": "ne:roads", "type": "line", "paint": { "line-color": "blue", "line-width": 1, } }, { "id": "label", "source-layer": "ne:roads", "type": "symbol", "layout": { "text-field": "{name}", "symbol-placement": "line", "text-offset": [0, -8] } "paint": { "text-color": "black" } } ] } 5. The text-color property is set to black to provide the colour of the text. Notice how this is a paint property, unlike all the others which are layout properties. { "version": 8, "name": "line_example", "layers": [ { "id": "line", "source-layer": "ne:roads", "type": "line", "paint": { "line-color": "blue", "line-width": 1, } }, { "id": "label", "source-layer": "ne:roads", "type": "symbol", "layout": { "text-field": "{name}", "symbol-placement": "line", "text-offset": [0, -8] } "paint": { 6.7. Styling Workshop 997 GeoServer User Manual, Release 2.15.1 "text-color": "black" } } ] } 6. The symbol-placement property is used to set how the label is placed with respect to the line. By default it is point which casues the label to be placed next to the midpoint as it would be for a point feature. When set to line it is placed along the line instead. textoffset specifies how far from the anchor the label should be placed, in both the x and y directions. { "version": 8, "name": "line_example", "layers": [ { "id": "line", "source-layer": "ne:roads", "type": "line", "paint": { "line-color": "blue", "line-width": 1, } }, { "id": "label", "source-layer": "ne:roads", "type": "symbol", "layout": { "text-field": "{name}", "symbol-placement": "line", "text-offset": [0, -8] } "paint": { "text-color": "black" } } ] } 998 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 How Labeling Works The rendering engine collects all the generated labels during the rendering of each layer. Then, during labeling, the engine sorts through the labels performing collision avoidance (to prevent labels overlapping). Finally the rendering engine draws the labels on top of the map. Even with collision avoidance you can spot areas where labels are so closely spaced that the result is hard to read. 1. The parameter text-padding provides additional space around our label for use in collision avoidance. { "version": 8, "name": "line_example", "layers": [ { "id": "line", "source-layer": "ne:roads", "type": "line", "paint": { "line-color": "blue", "line-width": 1, } }, { "id": "label", "source-layer": "ne:roads", "type": "symbol", "layout": { "text-field": "{name}", "symbol-placement": "line", "text-offset": [0, -8], "text-padding": "10" } "paint": { "text-color": "black" } } ] } 2. Each label is now separated from its neighbor, improving legibility. Zoom This section explores the use of rules with filters and zoom restrictions. 6.7. Styling Workshop 999 GeoServer User Manual, Release 2.15.1 1. Replace the line_example MBStyle definition with: { "version": 8, "name": "line_example", "layers": [ { "id": "line_example", "source-layer": "ne:roads", "type": "line", "filter": ["<", "scalerank", 4], "paint": { "line-color": "black", "line-width": 1 } } ] } 2. And use the Map tab to preview the result. 3. The scalerank attribute is provided by the Natural Earth dataset to allow control of the level of detail based on scale. Our filter shortlisted all content with scalerank 4 or lower, providing a nice quick preview when we are zoomed out. 4. In addition to testing feature attributes, selectors can also be used to check the state of the rendering engine. Replace your MBStyle with the following: { "version": 8, "name": "line_example", "layers": [ { "id": "line_black", "source-layer": "ne:roads", "type": "line", "maxzoom": 3, "paint": { "line-color": "black", "line-width": 1 } }, { "id": "line_blue", "source-layer": "ne:roads", "type": "line", "minzoom": 3, "paint": { 1000 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 "line-color": "blue", "line-width": 1 } } ] } 5. As you adjust the scale in the Map preview (using the mouse scroll wheel) the color will change between black and blue. You can read the current scale in the bottom right corner, and the legend will change to reflect the current style. 6. Putting these two ideas together allows control of level detail based on scale: { "version": 8, "name": "line_example", "layers": [ { "id": "line_else", "source-layer": "ne:roads", "type": "line", "filter": [">", "scalerank", 7], "minzoom": 7, "paint": { "line-color": "#888888", "line-width": 1 } }, { "id": "line_7", "source-layer": "ne:roads", "type": "line", "filter": ["==", "scalerank", 7], "minzoom": 6, "paint": { "line-color": "#777777", "line-width": 1 } }, { "id": "line_6", "source-layer": "ne:roads", "type": "line", "filter": ["==", "scalerank", 6], "minzoom": 5, "paint": { "line-color": "#444444", "line-width": 1 6.7. Styling Workshop 1001 GeoServer User Manual, Release 2.15.1 } }, { "id": "line_5_1", "source-layer": "ne:roads", "type": "line", "filter": ["==", "scalerank", 5], "minzoom": 4, "maxzoom": 7 "paint": { "line-color": "#000055", "line-width": 1 } }, { "id": "line_5_2", "source-layer": "ne:roads", "type": "line", "filter": ["==", "scalerank", 5], "minzoom": 7, "paint": { "line-color": "#000055", "line-width": 2 } }, { "id": "line_5_1", "source-layer": "ne:roads", "type": "line", "filter": ["<=", "scalerank", 4], "maxzoom": 5, "paint": { "line-color": "black", "line-width": 1 } }, { "id": "line_5_2", "source-layer": "ne:roads", "type": "line", "filter": ["<=", "scalerank", 4], "minzoom": 5, "maxzoom": 7 "paint": { "line-color": "black", "line-width": 2 } }, { "id": "line_5_4", "source-layer": "ne:roads", "type": "line", "filter": ["<=", "scalerank", 4], "minzoom": 7, "paint": { "line-color": "black", "line-width": 4 } 1002 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 } ] } 7. When a rule has both a filter and a scale, it will trigger when both are true. Bonus Finished early? Here are some opportunities to explore what we have learned, and extra challenges requiring creativity and research. In a classroom setting please divide the challenges between teams (this allows us to work through all the material in the time available). Challenge Classification 1. The roads type attribute provides classification information. You can Layer Preview to inspect features to determine available values for type. 2. Challenge: Create a new style adjust road appearance based on type. Note: The available values are ‘Major Highway’,’Secondary Highway’,’Road’ and ‘Unknown’. Note: Answer provided at the end of the workbook. Challenge One Rule Classification 1. You can save a lot of typing by doing your classification in an expression using arithmetic or the Recode function 6.7. Styling Workshop 1003 GeoServer User Manual, Release 2.15.1 2. Challenge: Create a new style and classify the roads based on their scale rank using expressions in a single rule instead of multiple rules with filters. Note: Answer provided at the end of the workbook. Challenge Label Shields 1. The traditional presentation of roads in the US is the use of a shield symbol, with the road number marked on top. 2. Challenge: Have a look at the documentation for putting a graphic on a text symbolizer in SLD and reproduce this technique in MBStyle. Note: Answer provided at the end of the workbook. Polygons Next we look at how MBStyle styling can be used to represent polygons. Fig. 6.314: Polygon Geometry Review of polygon symbology: • Polygons offer a direct representation of physical extent or the output of analysis. • The visual appearance of polygons reflects the current scale. • Polygons are recorded as a LinearRing describing the polygon boundary. Further LinearRings can be used to describe any holes in the polygon if present. The Simple Feature for SQL Geometry model (used by GeoJSON) represents these areas as Polygons, the ISO 19107 geometry model (used by GML3) represents these areas as Surfaces. 1004 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 • SLD uses a PolygonSymbolizer to describe how the shape of a polygon is drawn. The primary characteristic documented is the Fill used to shade the polygon interior. The use of a Stroke to describe the polygon boundary is optional. • Labeling of a polygon is anchored to the centroid of the polygon. GeoServer provides a vendor-option to allow labels to line wrap to remain within the polygon boundaries. For our Polygon exercises we will try and limit our MBStyle documents to a single rule, in order to showcase the properties used for rendering. Reference: • MBStyle Reference • MapBox Style Spec Fill Layer • Polygons (User Manual | SLD Reference ) This exercise makes use of the ne:states_provinces_shp layer. 1. Navigate to Styles. 2. Create a new style polygon_example. Name: Workspace: Format: polygon_example No workspace MBStyle 3. Enter the following style and click :menuselection:Apply to save: { "version": 8, "name": "polygon_example", "layers": [ { "id": "polygon_example", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "lightgrey" } } ] } 4. Click on the tab Layer Preview to preview. 6.7. Styling Workshop 1005 GeoServer User Manual, Release 2.15.1 5. Set ne:states_provinces_shp as the preview layer. Fill and Outline The fill layer controls the display of polygon data. The fill-color property is used to provide the color used to draw the interior of a polygon. 1. Replace the contents of polygon_example with the following fill example: { "version": 8, "name": "polygon_example", "layers": [ { "id": "polygon_example", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "gray" } } ] } 2. The Map tab can be used preview the change: 1006 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 3. To draw the boundary of the polygon the fill-outline property is used: The fill-outline property is used to provide the color of the polygon boundary. For more advanced boundary styling, use a seperate line layer. { "version": 8, "name": "polygon_example", "layers": [ { "id": "polygon_example", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "gray", "fill-outline-color": "black" } } ] } Note: Technically the boundary of a polygon is a specific case of a LineString where the first and last vertex are the same, forming a closed LinearRing. 4. The effect of adding fill-outline is shown in the map preview: 5. An interesting technique when styling polygons in conjunction with background information is to control the fill opacity. The fill-opacity property is used to adjust transparency (provided as range from 0.0 to 1.0). Use of fill-opacity to render polygons works well in conjunction with a raster base map. This approach allows details of the base map to shown through. fill-opacity affects both the fill and the fill outline. The stroke-opacity property is used in a similar fashion, as a range from 0.0 to 1.0. { "version": 8, "name": "polygon_example", "layers": [ { "id": "polygon_example", "source-layer": "ne:states_provinces_shp", "type": "fill", 6.7. Styling Workshop 1007 GeoServer User Manual, Release 2.15.1 "paint": { "fill-opacity": 0.5, "fill-color": "white", "fill-outline-color": "lightgrey" } } ] } 6. As shown in the map preview: 7. This effect can be better appreciated using a layer group. Where the transparent polygons is used lighten the landscape provided by the base map. Pattern The fill-pattern property can be used to provide a pattern. The fill pattern is defined by repeating an image defined in a spritesheet. 1008 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 1. Update polygon_example with the following sprite as a repeating fill pattern: { "version": 8, "name": "polygon_example", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites" "layers": [ { "id": "polygon_example", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-pattern": "grey_square16" } } ] } 2. The map preview (and legend) will show the result: 3. You can view the names of all the icons in the spritesheet by looking at its json definition, at http://localhost:8080/geoserver/styles/ sprites.json. { "white_square16": { "height": 16, "pixelRatio": 1, "width": 16, "x": 1, "y": 1 }, "grey_square8": { "height": 8, "pixelRatio": 1, "width": 8, "x": 24, "y": 18 }, "grey_square16": { "height": 16, 6.7. Styling Workshop 1009 GeoServer User Manual, Release 2.15.1 "pixelRatio": 1, "width": 16, "x": 18, "y": 1 }, "grey_square22": { "height": 22, "pixelRatio": 1, "width": 22, "x": 1, "y": 18 }, "green_square16": { "height": 16, "pixelRatio": 1, "width": 16, "x": 35, "y": 1 }, "grey_x": { "height": 30, "pixelRatio": 1, "width": 30, "x": 1, "y": 41 }, "grey_diag8": { "height": 8, "pixelRatio": 1, "width": 8, "x": 24, "y": 27 }, "grey_diag16": { "height": 16, "pixelRatio": 1, "width": 16, "x": 35, "y": 18 }, "grey_circle": { "height": 17, "pixelRatio": 1, "width": 17, "x": 36, "y": 36 }, "airport": { "height": 16, "pixelRatio": 1, "width": 16, "x": 52, "y": 18 }, "port": { "height": 16, "pixelRatio": 1, "width": 16, 1010 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 "x": 52, "y": 1 }, "star": { "height": 16, "pixelRatio": 1, "width": 16, "x": 69, "y": 1 } } Update the example to use grey_diag16 for a pattern of left hatching. { "version": 8, "name": "polygon_example", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites" "layers": [ { "id": "polygon_example", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-pattern": "grey_diag16" } } ] } 4. This approach is well suited to printed output or low color devices. 5. Multiple fills can be applied by using a seperate layer for each fill. { "version": 8, "name": "polygon_example", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites" "layers": [ { 6.7. Styling Workshop 1011 GeoServer User Manual, Release 2.15.1 "id": "polygon_background", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "#DDDDFF", "fill-outline-color": "black" } }, { "id": "polygon_pattern", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-pattern": "grey_diag8" } } ] } 6. The resulting image has a solid fill, with a pattern drawn overtop. Label Labeling polygons follows the same approach used for LineStrings. 1. By default labels are drawn starting at the centroid of each polygon. 2. Try out text-field and text-color polygon_example with the following: by replacing our { "version": 8, "name": "polygon_example", "layers": [ { "id": "polygon_fill", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "#7EB5D3", "fill-outline-color": "blue" } }, { "id": "polygon_label", "source-layer": "ne:states_provinces_shp", 1012 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 "type": "symbol", "layout": { "text-field": "{name}" }, "paint": { "text-color": "black" } } ] } 3. Each label is drawn from the lower-left corner as shown in the Map preview. 4. We can adjust how the label is drawn at the polygon centroid. The property text-anchor provides two numbers expressing how a label is aligned with respect to the centroid. Adjusting the textanchor is the recommended approach to positioning your labels. 5. Using the text-anchor property we can center our labels with respect to geometry centroid. To align the center of our label we select “center” below: { "version": 8, "name": "polygon_example", "layers": [ { "id": "polygon_fill", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "#7EB5D3", "fill-outline-color": "blue" } }, { "id": "polygon_label", "source-layer": "ne:states_provinces_shp", "type": "symbol", "layout": { "text-field": "{name}", "text-anchor": "center" }, "paint": { "text-color": "black" } 6.7. Styling Workshop 1013 GeoServer User Manual, Release 2.15.1 } ] } 6. The labeling position remains at the polygon centroid. We adjust alignment by controlling which part of the label we are “snapping” into position. 7. The property text-translate can be used to provide an initial displacement using and x and y offset. 8. This offset is used to adjust the label position relative to the geometry centroid resulting in the starting label position. { "version": 8, "name": "polygon_example", "layers": [ { "id": "polygon_fill", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "#7EB5D3", "fill-outline-color": "blue" } }, { "id": "polygon_label", "source-layer": "ne:states_provinces_shp", "type": "symbol", "layout": { "text-field": "{name}", }, "paint": { "text-color": "black", "text-translate": [0, -7] } } ] } 1014 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 9. Confirm this result in the map preview. 10. These two settings can be used together. The rendering engine starts by determining the label position generated from the geometry centroid and the text-translate displacement. The bounding box of the label is used with the text-anchor setting align the label to this location. Step 1: starting label position = centroid + displacement Step 2: snap the label anchor to the starting label position 11. To move our labels down (allowing readers to focus on each shape) we can use displacement combined with followed by horizontal alignment. { "version": 8, "name": "polygon_example", "layers": [ { "id": "polygon_fill", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "#7EB5D3", "fill-outline-color": "blue" } }, { "id": "polygon_label", "source-layer": "ne:states_provinces_shp", "type": "symbol", "layout": { "text-field": "{name}", "text-anchor": "left" }, "paint": { "text-color": "black", "text-translate": [0, -7] } } 6.7. Styling Workshop 1015 GeoServer User Manual, Release 2.15.1 ] } 12. As shown in the map preview. Legibility When working with labels a map can become busy very quickly, and difficult to read. 1. MBStyle extensive proterties for controlling the labelling process. One common property for controlling labeling is text-max-width, which allows any labels extending past the provided width will be wrapped into multiple lines. 2. Using this we can make a small improvement in our example: { "version": 8, "name": "polygon_example", "layers": [ { "id": "polygon_fill", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "#7EB5D3", "fill-outline-color": "blue" } }, { "id": "polygon_label", "source-layer": "ne:states_provinces_shp", "type": "symbol", "layout": { "text-field": "{name}", "text-anchor": "center" "text-max-width": 14 }, "paint": { "text-color": "black", 1016 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 } } ] } 3. As shown in the following preview. 4. Even with this improved spacing between labels, it is difficult to read the result against the complicated line work. Use of a halo to outline labels allows the text to stand out from an otherwise busy background. In this case we will make use of the fill color, to provide some space around our labels. We will also change the font to Arial. { "version": 8, "name": "polygon_example", "layers": [ { "id": "polygon_fill", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "#7EB5D3", "fill-outline-color": "blue" } }, { "id": "polygon_label", "source-layer": "ne:states_provinces_shp", "type": "symbol", "layout": { "text-field": "{name}", "text-anchor": "center" "text-max-width": 14, "text-font": ["Arial"] }, "paint": { "text-color": "black", "text-halo-color": "#7EB5D3", "text-halo-width": 2 6.7. Styling Workshop 1017 GeoServer User Manual, Release 2.15.1 } } ] } Theme A thematic map (rather than focusing on representing the shape of the world) uses elements of style to illustrate differences in the data under study. This section is a little more advanced and we will take the time to look at the generated SLD file. 1. We can use a site like ColorBrewer to explore the use of color theming for polygon symbology. In this approach the the fill color of the polygon is determined by the value of the attribute under study. This presentation of a dataset is known as “theming” by an attribute. 2. For our ne:states_provinces_shp dataset, a mapcolor9 attribute has been provided for this purpose. Theming by mapcolor9 results in a map where neighbouring countries are visually distinct. Qualitative 9-class Set3 #8dd3c7 #fb8072 #b3de69 #ffffb3 #80b1d3 #fccde5 #bebada #fdb462 #d9d9d9 If you are unfamiliar with theming you may wish to visit http:// colorbrewer2.org to learn more. The i icons provide an adequate background on theming approaches for qualitative, sequential and diverging datasets. 3. The first approach we will take is to directly select content based on colormap, providing a color based on the 9-class Set3 palette above: { "version": 8, "name": "polygon_example", "layers": [ { "id": "polygon_1", "filter": ["==", "mapcolor9", 1], "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "#8DD3C7", 1018 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 "fill-outline-color": "gray" } }, { "id": "polygon_2", "filter": ["==", "mapcolor9", 2], "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "#FFFFB3", "fill-outline-color": "gray" } }, { "id": "polygon_3", "filter": ["==", "mapcolor9", 3], "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "#BEBADA", "fill-outline-color": "gray" } }, { "id": "polygon_4", "filter": ["==", "mapcolor9", 4], "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "#FB8072", "fill-outline-color": "gray" } }, { "id": "polygon_5", "filter": ["==", "mapcolor9", 5], "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "#80B1D3", "fill-outline-color": "gray" } }, { "id": "polygon_6", "filter": ["==", "mapcolor9", 6], "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "#FDB462", "fill-outline-color": "gray" } }, { "id": "polygon_7", "filter": ["==", "mapcolor9", 7], "source-layer": "ne:states_provinces_shp", "type": "fill", 6.7. Styling Workshop 1019 GeoServer User Manual, Release 2.15.1 "paint": { "fill-color": "#B3DE69", "fill-outline-color": "gray" } }, { "id": "polygon_8", "filter": ["==", "mapcolor9", 8], "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "#FCCDE5", "fill-outline-color": "gray" } }, { "id": "polygon_9", "filter": ["==", "mapcolor9", 9], "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "#D9D9D9", "fill-outline-color": "gray" } } ] } 4. The Map tab can be used to preview this result. 5. Property functions can be used to make theming substantially easier, by directly mapping property values to style values using an array of stops. MBStyle supports three types of function interpolation, which is used to define the behavior between these stops: • categorical: Used the theme qualitative data. Attribute values are directly mapped to styling property such as fill or stroke-width. Equvalent to the SLD Recode function. • interval: Used the theme quantitative data. Categories are defined using min and max ranges, and values are sorted into the appropriate category. Equvalent to the SLD Categorize function. • exponential: Used to smoothly theme quantitative data by calculating a styling property based on an attribute value. Supports a base attribute for controlling the steepness of interpolation. When base is 1, this is equivalent to the SLD Interpolate function. Theming is an activity, producing a visual result allow map readers to learn more about how an attribute is distributed spatially. We are free to produce this visual in the most efficient way possible. 1020 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 6. Swap out mapcolor9 theme to use the categorical function: { "version": 8, "name": "polygon_example", "layers": [ { "id": "polygon", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": { "property": "mapcolor9", "type": "categorical", "stops": [ [1, "#8dd3c7"], [2, "#ffffb3"], [3, "#bebada"], [4, "#fb8072"], [5, "#80b1d3"], [6, "#fdb462"], [7, "#b3de69"], [8, "#fccde5"], [9, "#d9d9d9"] ] }, "fill-outline-color": "gray" } } ] } 7. The Map tab provides the same preview. 8. The Generated SLD tab shows where things get interesting. Our generated style now consists of a single Rule: ,→ 6.7. Styling Workshop mapcolor9 1 #8dd3c7 2 #ffffb3 3 #bebada 4 1021 GeoServer User Manual, Release 2.15.1 #fb8072 5 #80b1d3 6 #fdb462 7 #b3de69 8 #fccde5 9 #d9d9d9 #808080 0.5 Bonus The following optional explore and challenge activities offer a chance to review and apply the ideas introduced here. The challenge activities equire a bit of creativity and research to complete. In a classroom setting you are encouraged to team up into groups, with each group taking on a different challenge. Explore Interval 1. The interval function can be used to generate property values based on quantitative information. Here is an example using interval to color states according to size. { "version": 8, "name": "polygon_example", "layers": [ { "id": "polygon", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": { "property": "Shape_Area", "type": "interval", "stops": [ [0, "#08519c"], [0.5, "#3182bd"], 1022 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 [1, "#6baed6"], [5, "#9ecae1"], [60, "#c6dbef"], [80, "#eff3ff"] ] } } } ] } 2. An exciting use of the GeoServer shape symbols is the theming by changing the size used for pattern density. 3. Explore: Use the interval function to theme by datarank. Note: Answer provided at the end of the workbook. Challenge Halo 1. The halo example used the fill color and opacity for a muted halo, while this improved readability it did not bring attention to our labels. A common design choice for emphasis is to outline the text in a contrasting color. 2. Challenge: Produce a map that uses a white halo around black text. Note: Answer provided at the end of the workbook. Challenge Theming using Multiple Attributes 1. A powerful tool is theming using multiple attributes. This is an important concept allowing map readers to perform “integration by 6.7. Styling Workshop 1023 GeoServer User Manual, Release 2.15.1 eyeball” (detecting correlations between attribute values information). 2. Challenge: Combine the mapcolor9 and datarank examples to reproduce the following map. Note: Answer provided at the end of the workbook. Challenge Use of Z-Index 1. Earlier we looked at using multiple layers to simulate line string casing. The line work was drawn twice, once with thick line, and then a second time with a thinner line. The resulting effect is similar to text halos - providing breathing space around complex line work allowing it to stand out. 2. Challenge: Use what you know of rendering order to reproduce the following map: Note: Answer provided at the end of the workbook. Points The next stop of the mbstyle styling tour is the representation of points. Review of point symbology: 1024 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 • Points are used to represent a location only, and do not form a shape. The visual width of lines do not change depending on scale. • SLD uses a PointSymbolizer record how the shape of a line is drawn. • Labeling of points is anchored to the point location. As points have no inherent shape of of their own, emphasis is placed on marking locations with an appropriate symbol. Reference: • MBStyle Reference • MapBox Style Spec Symbol Layer • MapBox Style Spec Circle Layer • Point (User Manual | SLD Reference ) This exercise makes use of the ne:populated_places layer. 1. Navigate to the Styles page. 2. Click Add a new style and choose the following: Name: Workspace: Format: point_example No workspace MBStyle 3. Replace the initial MBStyle definition with the following and click apply: { "version": 8, "name": "point_example", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites" "layers": [ { "id": "point_example", "type": "symbol", "source-layer": "ne:populated_places", "layout": { "icon-image": "grey_circle", } } ] } 4. And use the Layer Preview tab to preview the result. 6.7. Styling Workshop 1025 GeoServer User Manual, Release 2.15.1 Sprite The symbol layer controls the display of point data. Points are typically represented with an icon-image. MBStyle uses a spritesheet defined at the top-level of the style to define a set of icons. You can view the names of all the icons in the spritesheet by looking at its json definition, at http://localhost: 8080/geoserver/styles/sprites.json. 1. Change the symbol used by the style to a square: { "version": 8, "name": "point_example", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites" "layers": [ { "id": "point_example", "type": "symbol", "source-layer": "ne:populated_places", "layout": { "icon-image": "grey_square16", } } ] } 2. Map Preview: 1026 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 3. Before we continue we will use a selector to cut down the amount of data shown to a reasonable level. { "version": 8, "name": "point_example", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites" "layers": [ { "id": "point_example", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 1], "layout": { "icon-image": "grey_square16", } } ] } 4. Resulting in a considerably cleaner image: 5. Additional properties are available to control an icon’s presentation: The icon-size property is used to control symbol size. The icon-rotate property controls orientation, accepting input in degrees. 6.7. Styling Workshop 1027 GeoServer User Manual, Release 2.15.1 Trying these two settings together: { "version": 8, "name": "point_example", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites" "layers": [ { "id": "point_example", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 1], "layout": { "icon-image": "grey_square16", "icon-size": 0.75, "icon-rotate": 45 } } ] } 6. Results in each location being marked with a diamond: Circle Another way of displaying point data is using the circle layer. Rather than rendering an icon from a preset sprite sheet, the circle layer lets us chose size and color for a simple circle. 1. Modify the style to render a grey circle using the circle layer: { "version": 8, "name": "point_example", "layers": [ { "id": "point_example", "type": "circle", "source-layer": "ne:populated_places", "paint": { "circle-color": "gray", 1028 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } } ] } 2. And use the Layer Preview tab to preview the result. Label Labeling is now familiar from our experience with LineString and Polygons. The symbol layer with the label property are used to to label Point Locations. 1. Replace point_example with the following: { "version": 8, "name": "point_example", "layers": [ { "id": "point_circle", "type": "circle", "source-layer": "ne:populated_places", "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } }, { "id": "point_label", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 1], "type": "symbol", 6.7. Styling Workshop 1029 GeoServer User Manual, Release 2.15.1 "layout": { "text-field": "{NAME}" }, "paint": { "text-color": "gray" } } ] } 2. Confirm the result in Map preview. 3. Each label is drawn starting from the provided point - which is unfortunate as it assures each label will overlap with the symbol used. To fix this limitation we will make use of the MBStyle controls for label placement: text-anchor provides a value expressing how a label is aligned with respect to the starting label position. text-translate is used to provide an initial displacement using and x and y offset. For points this offset is recommended to adjust the label position away for the area used by the symbol. Note: The property text-anchor defines an anchor position relative to the bounding box formed by the resulting label. This anchor position is snapped to the label position generated by the point location and displacement offset. 4. Using these two facilities together we can center our labels below the symbol, taking care that the displacement used provides an offset just outside the area required for the symbol size. { "version": 8, "name": "point_example", "layers": [ { "id": "point_circle", "type": "circle", "source-layer": "ne:populated_places", 1030 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } }, { "id": "point_label", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 1], "type": "symbol", "layout": { "text-field": "{NAME}", "text-anchor": "top" }, "paint": { "text-color": "black", "text-translate": [0, 12] } } ] } 5. Each label is now placed under the mark. 6. One remaining issue is the overlap between labels and symbols. MBStyle provides various parameters to control label rendering and conflict resolution, preventing labels from overlapping any symbols. icon-allow-overlap and text-allow-overlap allows the rendering engine to draw the indicated symbol atop previous labels and icons. icon-ignore-placement and text-ignore-placement allows the rendering engine to draw labels and icons over top of the indicated symbol. icon-padding and text-padding tells the rendering engine to provide a minimum distance between the icons and text on the map, ensuring they do not overlap with other labels or icons. The -allow-overlap and -ignore-placement parameters are false by default, which is the behavior we want. Update our example to use 6.7. Styling Workshop 1031 GeoServer User Manual, Release 2.15.1 text-padding: { "version": 8, "name": "point_example", "layers": [ { "id": "point_circle", "type": "circle", "source-layer": "ne:populated_places", "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } }, { "id": "point_label", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 1], "type": "symbol", "layout": { "text-field": "{NAME}", "text-anchor": "top", "text-padding": 2 }, "paint": { "text-color": "black", "text-translate": [0, 12] } } ] } 7. Resulting in a considerably cleaner image: Dynamic Styling 1. We will quickly use minzoom and maxzoom to select content based on SCALERANK selectors. 1032 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 { "version": 8, "name": "point_example", "layers": [ { "id": "point_7", "type": "circle", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 7], "minzoom": 6, "maxzoom": 7, "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } }, { "id": "point_5", "type": "circle", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 5], "minzoom": 5, "maxzoom": 6, "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } }, { "id": "point_4", "type": "circle", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 4], "minzoom": 4, "maxzoom": 5, "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } }, { "id": "point_3", "type": "circle", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 3], "minzoom": 3, "maxzoom": 4, "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 6.7. Styling Workshop 1033 GeoServer User Manual, Release 2.15.1 } }, { "id": "point_2", "type": "circle", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 2], "minzoom": 2, "maxzoom": 3, "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } }, { "id": "point_1", "type": "circle", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 1], "maxzoom": 2, "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } }, { "id": "point_0", "type": "circle", "source-layer": "ne:populated_places", "minzoom": 7, "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } } ] } 2. Click Submit to update the Map after each step. 1034 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 3. To add labeling we can add a symbol layer for each of the existing circle layers. { "version": 8, "name": "point_example", "layers": [ { "id": "point_7", "type": "circle", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 7], "minzoom": 6, "maxzoom": 7, "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } }, { "id": "point_7_text", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 7], "minzoom": 6, "maxzoom": 7, "layout": { "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10 }, "paint": { "text-color": "black" } }, { "id": "point_5", "type": "circle", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 5], "minzoom": 5, "maxzoom": 6, 6.7. Styling Workshop 1035 GeoServer User Manual, Release 2.15.1 "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } }, { "id": "point_5_text", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 5], "minzoom": 5, "maxzoom": 6, "layout": { "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10 }, "paint": { "text-color": "black" } }, { "id": "point_4", "type": "circle", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 4], "minzoom": 4, "maxzoom": 5, "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } }, { "id": "point_4_text", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 4], "minzoom": 4, "maxzoom": 5, "layout": { "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10 }, "paint": { "text-color": "black" } }, { "id": "point_3", "type": "circle", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 3], 1036 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 "minzoom": 3, "maxzoom": 4, "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } }, { "id": "point_3_text", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 3], "minzoom": 3, "maxzoom": 4, "layout": { "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10 }, "paint": { "text-color": "black" } }, { "id": "point_2", "type": "circle", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 2], "minzoom": 2, "maxzoom": 3, "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } }, { "id": "point_2_text", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 2], "minzoom": 2, "maxzoom": 3, "layout": { "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10 }, "paint": { "text-color": "black" } }, { "id": "point_1", "type": "circle", 6.7. Styling Workshop 1037 GeoServer User Manual, Release 2.15.1 "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 1], "maxzoom": 2, "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } }, { "id": "point_1_text", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 1], "maxzoom": 2, "layout": { "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10 }, "paint": { "text-color": "black" } }, { "id": "point_0", "type": "circle", "source-layer": "ne:populated_places", "minzoom": 7, "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } }, { "id": "point_0_text", "type": "symbol", "source-layer": "ne:populated_places", "minzoom": 7, "layout": { "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10 }, "paint": { "text-color": "black" } } ] } 1038 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 4. We will use text-offset to position the label above each symbol, and text-padding to give some extra space around our labels. Add the following line to each layer: { "id": "point_example", "type": "symbol", "source-layer": "ne:populated_places", "minzoom": 7, "layout": { "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10, "text-padding": 2 }, "paint": { "text-color": "black", "text-translate": [0, -12] } } 5. Now that we have clearly labeled our cities, zoom into an area you are familiar with and we can look at changing symbology on a caseby-case basis. We have used expressions previous to generate an appropriate label. Expressions can also be used for many other property settings. The ne:populated_places layer provides several attributes 6.7. Styling Workshop 1039 GeoServer User Manual, Release 2.15.1 specifically to make styling easier: • SCALERANK: we have already used this attribute to control the level of detail displayed • FEATURECLA: used to indicate different types of cities. We will check for Admin-0 capital cities. The first thing we will do is calculate the point size using a quick expression: { "property": "SCALERANK", "type": "exponential", "stops": [ [0, 4.5], [10, 2.5] ] }, This expression should result in sizes between 5 and 9 and will need to be applied to both point size and label displacement. { "id": "point_0", "type": "circle", "source-layer": "ne:populated_places", "minzoom": 7, "paint": { "circle-color": "gray", "circle-radius": { "property": "SCALERANK", "type": "exponential", "stops": [ [0, 4.5], [10, 2.5] ] }, "circle-stroke-color": "black", "circle-stroke-width": 1 } } { "id": "point_0_text", "type": "symbol", "source-layer": "ne:populated_places", "minzoom": 7, "layout": { "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10, "text-padding": 2 }, "paint": { "text-color": "black", "text-translate": { "property": "SCALERANK", "type": "exponential", 1040 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 "stops": [ [0, [0, -8]], [10, [0, -6]] ] }, } } 6. Next we can use FEATURECLA to check for capital cities. Adding a selector for capital cities at the top of the rules list: { "id": "point_capital", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["all",["<", "SCALERANK ,→", 2], ["==", "FEATURECLA", "Admin-0 capital"]] "minzoom": 2, "layout": { "icon-image": "star", "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10, "text-padding": 2 }, "paint": { "text-color": "black", "text-translate": [0, -12] } } Also add the spritesheet url to the top of the style if it is not present: { "version": 8, "name": "point_example", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites", } And updating the populated places selectors to ignore capital cities: 6.7. Styling Workshop 1041 GeoServer User Manual, Release 2.15.1 { "id": "point_7", "type": "circle", "source-layer": "ne:populated_places", "filter": ["all", ["<", "SCALERANK ,→", 7], ["!=", "FEATURECLA", "Admin-0 capital"]], "minzoom": 6, "maxzoom": 7, "paint": { "circle-color": "gray", "circle-radius": { "property": "SCALERANK", "type": "exponential", "stops": [ [0, 4.5], [10, 2.5] ] }, "circle-stroke-color": "black", "circle-stroke-width": 1 } } { "id": "point_7_text", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["all", ["<", "SCALERANK ,→", 7], ["!=", "FEATURECLA", "Admin-0 capital"]], "minzoom": 6, "maxzoom": 7, "layout": { "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10, "text-padding": 2 }, "paint": { "text-color": "black", "text-translate": { "property": "SCALERANK", "type": "exponential", "stops": [ [0, [0, -8]], [10, [0, -6]] ] } } } { "id": "point_5", "type": "circle", "source-layer": "ne:populated_places", "filter": ["all", ["<", "SCALERANK ,→", 5], ["!=", "FEATURECLA", "Admin-0 capital"]], "minzoom": 5, 1042 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 "maxzoom": 6, "paint": { "circle-color": "gray", "circle-radius": { "property": "SCALERANK", "type": "exponential", "stops": [ [0, 4.5], [10, 2.5] ] }, "circle-stroke-color": "black", "circle-stroke-width": 1 } } { "id": "point_5_text", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["all", ["<", "SCALERANK ,→", 5], ["!=", "FEATURECLA", "Admin-0 capital"]], "minzoom": 5, "maxzoom": 6, "layout": { "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10, "text-padding": 2 }, "paint": { "text-color": "black", "text-translate": { "property": "SCALERANK", "type": "exponential", "stops": [ [0, [0, -8]], [10, [0, -6]] ] } } } { "id": "point_4", "type": "circle", "source-layer": "ne:populated_places", "filter": ["all", ["<", "SCALERANK ,→", 4], ["!=", "FEATURECLA", "Admin-0 capital"]], "minzoom": 4, "maxzoom": 5, "paint": { "circle-color": "gray", "circle-radius": { "property": "SCALERANK", "type": "exponential", "stops": [ 6.7. Styling Workshop 1043 GeoServer User Manual, Release 2.15.1 [0, 4.5], [10, 2.5] ] }, "circle-stroke-color": "black", "circle-stroke-width": 1 } } { "id": "point_4_text", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["all", ["<", "SCALERANK ,→", 4], ["!=", "FEATURECLA", "Admin-0 capital"]], "minzoom": 4, "maxzoom": 5, "layout": { "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10, "text-padding": 2 }, "paint": { "text-color": "black", "text-translate": { "property": "SCALERANK", "type": "exponential", "stops": [ [0, [0, -8]], [10, [0, -6]] ] } } } { "id": "point_3", "type": "circle", "source-layer": "ne:populated_places", "filter": ["all", ["<", "SCALERANK ,→", 3], ["!=", "FEATURECLA", "Admin-0 capital"]], "minzoom": 3, "maxzoom": 4, "paint": { "circle-color": "gray", "circle-radius": 8 "circle-stroke-color": "black", "circle-stroke-width": 1 } } { "id": "point_3_text", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["all", ["<", "SCALERANK ,→", 3], ["!=", "FEATURECLA", "Admin-0 capital"]], 1044 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 "minzoom": 3, "maxzoom": 4, "layout": { "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10, "text-padding": 2 }, "paint": { "text-color": "black", "text-translate": { "property": "SCALERANK", "type": "exponential", "stops": [ [0, [0, -8]], [10, [0, -6]] ] } } } { "id": "point_2", "type": "circle", "source-layer": "ne:populated_places", "filter": ["all", ["<", "SCALERANK ,→", 2], ["!=", "FEATURECLA", "Admin-0 capital"]], "minzoom": 2, "maxzoom": 3, "paint": { "circle-color": "gray", "circle-radius": { "property": "SCALERANK", "type": "exponential", "stops": [ [0, 4.5], [10, 2.5] ] }, "circle-stroke-color": "black", "circle-stroke-width": 1 } } { "id": "point_2_text", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["all", ["<", "SCALERANK ,→", 2], ["!=", "FEATURECLA", "Admin-0 capital"]], "minzoom": 2, "maxzoom": 3, "layout": { "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10, "text-padding": 2 6.7. Styling Workshop 1045 GeoServer User Manual, Release 2.15.1 }, "paint": { "text-color": "black", "text-translate": { "property": "SCALERANK", "type": "exponential", "stops": [ [0, [0, -8]], [10, [0, -6]] ] } } } { "id": "point_1", "type": "circle", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 1], "maxzoom": 2, "paint": { "circle-color": "gray", "circle-radius": { "property": "SCALERANK", "type": "exponential", "stops": [ [0, 4.5], [10, 2.5] ] }, "circle-stroke-color": "black", "circle-stroke-width": 1 } } { "id": "point_1_text", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["<", "SCALERANK", 1], "maxzoom": 2, "layout": { "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10, "text-padding": 2 }, "paint": { "text-color": "black", "text-translate": { "property": "SCALERANK", "type": "exponential", "stops": [ [0, [0, -8]], [10, [0, -6]] ] } 1046 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 } } { "id": "point_0", "type": "circle", "source-layer": "ne:populated_places", "filter": ["!=", "FEATURECLA", "Admin-0 capital"], "minzoom": 7, "paint": { "circle-color": "gray", "circle-radius": { "property": "SCALERANK", "type": "exponential", "stops": [ [0, 4.5], [10, 2.5] ] }, "circle-stroke-color": "black", "circle-stroke-width": 1 } } { "id": "point_0_text", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["!=", "FEATURECLA", "Admin-0 capital"], "minzoom": 7, "layout": { "text-field": "{NAME}", "text-font": ["Arial"], "text-size": 10, "text-padding": 2 }, "paint": { "text-color": "black", "text-translate": { "property": "SCALERANK", "type": "exponential", "stops": [ [0, [0, -8]], [10, [0, -6]] ] } } } 6.7. Styling Workshop 1047 GeoServer User Manual, Release 2.15.1 7. If you would like to check your work the final file is here: point_example.mbstyle Bonus Challenge Geometry Location 1. The mark property can be used to render any geometry content. 2. Challenge: Try this yourself by rendering a polygon layer using a mark property. Note: Answer discussed at the end of the workbook. Explore Dynamic Symbolization 1. We went to a lot of work to set up selectors to choose between star and circle for capital cities. This approach is straightforward when applied in isolation: { "version": 8, "name": "point_example", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites", "layers": [ { "id": "point_capital", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["==", "FEATURECLA", "Admin-0 capital"] "minzoom": 2, "layout": { "icon-image": "star", } }, { "id": "point_0", 1048 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 "type": "circle", "source-layer": "ne:populated_places", "filter": ["!=", "FEATURECLA", "Admin-0 capital"], "minzoom": 7, "paint": { "circle-color": "gray", "circle-radius": 4, "circle-stroke-color": "black", "circle-stroke-width": 1 } ,→ } ] } When combined with checking another attribute, or checking @scale as in our example, this approach can quickly lead to many rules which can be difficult to keep straight. 2. Taking a closer look, icon-image is expressed using a string: { "id": "point_capital", "type": "symbol", "source-layer": "ne:populated_places", "filter": ["==", "FEATURECLA", "Admin-0 capital"] "minzoom": 2, "layout": { "icon-image": "star", } } Which is represented in SLD as: mbsprite 3. MBStyle provides an opportunity for dynamic symbolization. This is accomplished by using a function for the value of the iconimage: { "version": 8, "name": "point_example", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites", "layers": [ 6.7. Styling Workshop 1049 GeoServer User Manual, Release 2.15.1 { "id": "point_capital", "type": "symbol", "source-layer": "ne:populated_places", "layout": { "icon-image": { "type": "categorical", "property": "FEATURECLA", "default": "grey_circle", "stops": [ ["Admin-0 capital", "star"] ] } } } ] } Which is represented in SLD as: mbsprite 4. Challenge: Use this approach to rewrite the Dynamic Styling example. Note: Answer provided at the end of the workbook. Rasters Finally we will look at using MBStyle styling for the portrayal of raster data. Fig. 6.315: Raster Symbology Review of raster symbology: • Raster data is Grid Coverage where values have been recorded in a regular array. In OGC terms a Coverage can be used to look up a value or measurement for each location. • When queried with a “sample” location: 1050 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 – A grid coverage can determine the appropriate array location and retrieve a value. Different techniques may be used interpolate an appropriate value from several measurements (higher quality) or directly return the “nearest neighbor” (faster). – A vector coverages would use a point-in-polygon check and return an appropriate attribute value. – A scientific model can calculate a value for each sample location • Many raster formats organize information into bands of content. Values recorded in these bands and may be mapped into colors for display (a process similar to theming an attribute for vector data). For imagery the raster data is already formed into red, green and blue bands for display. • As raster data has no inherent shape, the format is responsible for describing the orientation and location of the grid used to record measurements. These raster examples use a digital elevation model consisting of a single band of height measurements. The imagery examples use an RGB image that has been hand coloured for use as a base map. Since MBStyle is primarily intended for client-side styling, it doesn’t have much ability to style raster data when compared with SLD, so this section will be much shorter than the equivalent raster sections for CSS and YSLD. Reference: • MBStyle Reference • MapBox Style Spec Raster Layer • Point (User Manual | SLD Reference ) The exercise makes use of the usgs:dem and ne:ne1 layers. Image The raster layer controls the display of raster data. 1. Navigate to the Styles page. 2. Click Add a new style and choose the following: Name: Workspace: Format: image_example No workspace MBStyle 3. Replace the initial MBStyle definition with: { "name": "image_example", "version": 8, "layers": [ { "id": "image_example", 6.7. Styling Workshop 1051 GeoServer User Manual, Release 2.15.1 "type": "raster", "source-layer": "ne:ne1", "paint": { "raster-opacity": 1 } } ] } 4. And use the Layer Preview tab to preview the result. DEM A digital elevation model is an example of raster data made up of measurements, rather than color information. The usgs:dem layer used used for this exercise: 1. Return to the the Styles page. 2. Click Add a new style and choose the following: Name: Workspace: Format: raster_example No workspace MBStyle 3. The rendering engine will select our single band of raster content, and do its best to map these values into a grayscale image. Replace the content of the style with: { "name": "raster_example", "version": 8, "layers": [ { "id": "raster_example", "type": "raster", "source-layer": "usgs:dem", "paint": { "raster-opacity": 1 } 1052 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 } ] } 4. Use the Layer Preview tab to preview the result. The range produced in this case from the highest and lowest values. Bonus Challenge Raster Opacity 1. There is a quick way to make raster data transparent, raster opacity property works in the same fashion as with vector data. The raster as a whole will be drawn partially transparent allow content from other layers to provide context. 2. Challenge: Can you think of an example where this would be useful? Note: Discussion provided at the end of the workbook. MBStyle Workbook Conclusion We hope you have enjoyed this styling workshop. Additional resources: • MBStyle Extension • MBStyle Reference MBStyle Tips and Tricks MBStyle Workshop Answer Key The following questions were listed through out the workshop as an opportunity to explore the material in greater depth. Please do your best to consider the questions in detail prior to checking here for the answer. Questions are provided to teach valuable skills, such as a chance to understand how feature type styles are used to control z-order, or where to locate information in the user manual. 6.7. Styling Workshop 1053 GeoServer User Manual, Release 2.15.1 Note: Coming Soon Classification Answer for Challenge Classification: 1. Challenge: Create a new style adjust road appearance based on type. Hint: The available values are ‘Major Highway’,’Secondary Highway’,’Road’ and ‘Unknown’. 2. Here is an example: { "version": 8, "name": "line_example", "layers": [ { "id": "line_hwy1", "source-layer": "ne:roads", "type": "line", "filter": ["==", "type", "Major Highway"], "paint": { "line-color": "#000088", "line-width": 1.25, "line-opacity": 0.25 } }, { "id": "line_hwy2", "source-layer": "ne:roads", "type": "line", "filter": ["==", "type", "Secondary Highway"], "paint": { "line-color": "#8888AA", "line-width": 0.75, "line-opacity": 0.25 } }, { "id": "line_road", "source-layer": "ne:roads", "type": "line", "filter": ["==", "type", "Road"], "paint": { "line-color": "#888888", "line-width": 0.75, 1054 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 "line-opacity": 0.25 } }, { "id": "line_unk", "source-layer": "ne:roads", "type": "line", "filter": ["==", "type", "Unknown"], "paint": { "line-color": "#888888", "line-width": 0.5, "line-opacity": 0.25 } } ] } One Rule Classification Answer for Challenge One Rule Classification: 1. Challenge: Create a new style and classify the roads based on their scale rank using expressions in a single rule instead of multiple rules with filters. 2. This exercise requires looking up information in the MBstyle user guide. • The Mapbox Style specification functions provides details. Label Shields Answer for Challenge Label Shields: 1. Challenge: Have a look at the documentation for putting a graphic on a text symbolizer in SLD and reproduce this technique in MBStyle. 2. The use of a label shield is a vendor specific capability of the GeoServer rendering engine. The tricky part of this exercise is finding which symbol layout parameters give the desired behavior, 6.7. Styling Workshop 1055 GeoServer User Manual, Release 2.15.1 mainly icon-text-fit but also the various placement and overlap parameters to allow the text to be drawn atop the labels ( see symbol layer). { "version": 8, "name": "line_example", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites", "layers": [ { "id": "line_casing", "source-layer": "ne:roads", "type": "line", "paint": { "line-color": "#000000", "line-width": 3, } }, { "id": "line_inner", "source-layer": "ne:roads", "type": "line", "paint": { "line-color": "#D3D3D3", "line-width": 2, } }, { "id": "label", "source-layer": "ne:roads", "type": "symbol", "layout": { "icon-image": "white_square16", "icon-text-fit": "width", "icon-text-fit-padding": [2, 2, 2, 2], "text-field": "{name}", "text-font": ["Ariel"], "text-font-size": 10, "text-ignore-placement": true, "text-allow-overlap": true, "icon-ignore-placement": true, "icon-allow-overlap": true, "symbol-placement": "line", "symbol-spacing": 0 } "paint": { "text-color": "black" } } ] } Interval Answer for Explore Interval: 1056 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 1. An exciting use of the GeoServer fill-pattern symbols is theming by changing the pattern used. 2. Explore: Use the interval function to theme by datarank. Example: { "version": 8, "name": "polygon_example", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites", "layers": [ { "id": "polygon", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-pattern": { "property": "datarank", "type": "interval", "stops": [ [4, "grey_diag8"], [6, "grey_diag16"] ] } } } ] } Halo Answer for Challenge Halo: 1. The halo example used the fill color and opacity for a muted halo, while this improved readability it did not bring attention to our labels. A common design choice for emphasis is to outline the text in a contrasting color. 2. Challenge: Produce a map that uses a white halo around black text. Here is an example: { "version": 8, "name": "polygon_example", "layers": [ { 6.7. Styling Workshop 1057 GeoServer User Manual, Release 2.15.1 "id": "polygon_fill", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "#7EB5D3", "fill-outline-color": "gray" } }, { "id": "polygon_label", "source-layer": "ne:states_provinces_shp", "type": "symbol", "layout": { "text-field": "{name}", "text-anchor": "center" "text-max-width": 14, "text-font": ["Arial"] }, "paint": { "text-color": "white", "text-halo-color": "black", "text-halo-width": 1 } } ] } Theming using Multiple Attributes Answer for Challenge Theming using Multiple Attributes: 1. A powerful tool is theming using multiple attributes. This is an important concept allowing map readers to perform “integration by eyeball” (detecting correlations between attribute values information). 2. Challenge: Combine the mapcolor9 and datarank examples to reproduce the following map. This should be a cut and paste using the categorical example, and interval examples already provided. { "version": 8, "name": "polygon_example", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites", "layers": [ 1058 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 { "id": "polygon", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": { "property": "mapcolor9", "type": "categorical", "stops": [ [1, "#8dd3c7"], [2, "#ffffb3"], [3, "#bebada"], [4, "#fb8072"], [5, "#80b1d3"], [6, "#fdb462"], [7, "#b3de69"], [8, "#fccde5"], [9, "#d9d9d9"] ] }, "fill-outline-color": "gray" } }, { "id": "polygon", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-pattern": { "property": "datarank", "type": "interval", "stops": [ [4, "grey_diag8"], [6, "grey_diag16"] ] } } } ] } Use of Z-Index Answer for Challenge Use of Z-Index: 1. Using multiple layers to simulate line string casing. The resulting effect is similar to text halos - providing breathing space around complex line work allowing it to stand out. 2. Challenge: Use what you know of LineString rendering order to reproduce the following map: 6.7. Styling Workshop 1059 GeoServer User Manual, Release 2.15.1 This is much easier when using MBStyle, where z-order is controlled by layer. { "version": 8, "name": "polygon_example", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites", "layers": [ { "id": "polygon_fill", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-color": "lightgrey", } }, { "id": "polygon_pattern", "source-layer": "ne:states_provinces_shp", "type": "fill", "paint": { "fill-pattern": "grey_diag16" } } { "id": "polygon_casing", "source-layer": "ne:states_provinces_shp", "type": "line", "paint": { "line-color": "lightgrey", "line-width": 6 } }, { "id": "polygon_outline", "source-layer": "ne:states_provinces_shp", "type": "line", "paint": { "line-color": "black", "line-width": 1.5 } } ] 1060 Chapter 6. Styling GeoServer User Manual, Release 2.15.1 } The structure of the legend graphic provides an indication on what is going on. Geometry Location Answer for Challenge Geometry Location: 1. The symbol layer can be used to render any geometry content. 2. Challenge: Try this yourself by rendering polygon data using a symbol layer. This can be done one of two ways: • Changing the association of a polygon layer, such as ne:states_provinces_shp to point_example and using the layer preview page. • Changing the Layer Preview tab to a polygon layer, such as ne:states_provinces_shp. The important thing to notice is that the centroid of each polygon is used as a point location. Note: A layer in an MBStyle is not the same as a layer in GeoServer. A GeoServer layer is a raster or vector dataset that represents a collection of geographic features. A MBStyle layer is a block of styling information, similar to a SLD Symbolizer. Dynamic Symbolization Answer for Explore Dynamic Symbolization: 1. icon-image provides an opportunity for dynamic symbolization. This is accomplished by using a function for the value of icon-image: { "version": 8, "name": "point_example", "sprite ,→": "http://localhost:8080/geoserver/styles/sprites", "layers": [ { "id": "point_capital", "type": "symbol", "source-layer": "ne:populated_places", "layout": { "icon-image": { "type": "categorical", "property": "FEATURECLA", "default": "grey_circle", "stops": [ 6.7. Styling Workshop 1061 GeoServer User Manual, Release 2.15.1 ["Admin-0 capital", "star"] ] } } } ] } 2. Challenge: Use this approach to rewrite the Dynamic Styling example. Example available here point_example.json : Raster Opacity Discussion for Challenge Raster Opacity: 1. There is a quick way to make raster data transparent, raster opacity property works in the same fashion as with vector data. The raster as a whole will be drawn partially transparent allow content from other layers to provide context. 2. Challenge: Can you think of an example where this would be useful? This is difficult as raster data is usually provided for use as a basemap, with layers being drawn over top. The most obvious example here is the display of weather systems, or model output such as fire danger. By drawing the raster with some transparency, the landmass can be shown for context. 1062 Chapter 6. Styling CHAPTER 7 Services GeoServer serves data using standard protocols established by the Open Geospatial Consortium: • The Web Map Service (WMS) supports requests for map images (and other formats) generated from geographical data. • The Web Feature Service (WFS) supports requests for geographical feature data (with vector geometry and attributes). • The Web Coverage Service (WCS) supports requests for coverage data (rasters). These services are the primary way that GeoServer supplies geospatial information. 7.1 Web Map Service (WMS) This section describes the Web Map Service (WMS). 7.1.1 WMS settings This page details the configuration options for WMS in the web administration interface. Service Metadata See the section on Service Metadata. Root Layer Information In this section is possible to define a title and an abstract for the root layer in the WMS capabilities. When these are left empty the WMS service title and abstract are used. 1063 GeoServer User Manual, Release 2.15.1 Fig. 7.1: WMS configuration options 1064 Chapter 7. Services GeoServer User Manual, Release 2.15.1 Raster Rendering Options The Web Map Service Interface Standard (WMS) provides a simple way to request and serve geo-registered map images. During pan and zoom operations, WMS requests generate map images through a variety of raster rendering processes. Such image manipulation is generally called resampling, interpolation, or down-sampling. GeoServer supports three resampling methods that determine how cell values of a raster are outputted. These sampling methods—Nearest Neighbor, Bilinear Interpolation and Bicubic—are available on the Default Interpolation menu. Nearest Neighbor—Uses the center of nearest input cell to determine the value of the output cell. Original values are retained and no new averages are created. Because image values stay exactly the same, rendering is fast but possibly pixelated from sharp edge detail. Nearest neighbor interpolation is recommended for categorical data such as land use classification. Bilinear—Determines the value of the output cell based by sampling the value of the four nearest cells by linear weighting. The closer an input cell, the higher its influence of on the output cell value. Since output values may differ from nearest input, bilinear interpolation is recommended for continuous data like elevation and raw slope values. Bilinear interpolation takes about five times as long as nearest neighbor interpolation. Bicubic—Looks at the sixteen nearest cells and fits a smooth curve through the points to find the output value. Bicubic interpolation may both change the input value as well as place the output value outside of the range of input values. Bicubic interpolation is recommended for smoothing continuous data, but this incurs a processing performance overhead. Watermark Settings Watermarking is the process of embedding an image into a map. Watermarks are usually used for branding, copyright, and security measures. Watermarks are configured in the WMS watermarks setting section. Enable Watermark—Turns on watermarking. When selected, all maps will render with the same watermark. It is not currently possible to specify watermarking on a per-layer or per-feature basis. Watermark URL—Location of the graphic for the watermark. The graphic can be referenced as an absolute path (e.g., C:\GeoServer\watermark.png), a relative one inside GeoServer’s data directory (e.g., watermark.png), or a URL (e.g., http://www.example.com/images/watermark.png). Each of these methods have their own advantages and disadvantages. When using an absolute or relative link, GeoServer keeps a cached copy of the graphic in memory, and won’t continually link to the original file. This means that if the original file is subsequently deleted, GeoServer won’t register it missing until the watermark settings are edited. Using a URL might seem more convenient, but it is more I/O intensive. GeoServer will load the watermark image for every WMS request. Also, should the URL cease to be valid, the layer will not properly display. Watermark Transparency–Determines the opacity level of the watermark. Numbers range between 0 (opaque) and 100 (fully invisible). Watermark Position—Specifies the position of the watermark relative to the WMS request. The nine options indicate which side and corner to place the graphic (top-left, top-center, top-right, etc). The default watermark position is bottom-right. Note that the watermark will always be displayed flush with the boundary. If extra space is required, the graphic itself needs to change. Because each WMS request renders the watermark, a single tiled map positions one watermark relative to the view window while a tiled map positions the watermark for each tile. The only layer specific aspect of watermarking occurs because a single tile map is one WMS request, whereas a tiled map contains many WMS requests. (The latter watermark display resembles Google Maps faint copyright notice in their Satellite imagery.) The following three examples demonstrate watermark position, transparency and tiling display, respectively. 7.1. Web Map Service (WMS) 1065 GeoServer User Manual, Release 2.15.1 Fig. 7.2: Single tile watermark (aligned top-right, transparency=0) Fig. 7.3: Single tile watermark (aligned top-right, transparency=90) 1066 Chapter 7. Services GeoServer User Manual, Release 2.15.1 Fig. 7.4: Tiled watermark (aligned top-right, transparency=90) SVG Options The GeoServer WMS supports SVG (Scalable Vector Graphics) as an output format. GeoServer currently supports two SVG renderers, available from the SVG producer menu. 1. Simple—Simple SVG renderer. It has limited support for SLD styling, but is very fast. 2. Batik—Batik renderer (as it uses the Batik SVG Framework). It has full support for SLD styling, but is slower. Enable Anti-aliasing Anti-aliasing is a technique for making edges appear smoother by filling in the edges of an object with pixels that are between the object’s color and the background color. Anti-aliasing creates the illusion of smoother lines and smoother selections. Turning on anti-aliasing will generally make maps look nicer, but will increase the size of the images, and will take longer to return. If you are overlaying the anti-aliased map on top of others, beware of using transparencies as the anti-aliasing process mixes with the colors behind and can create a “halo” effect. Advanced projection handling and map wrapping Advanced projection handling is a set of extra “smarts” applied while rendering that help getting a good looking map despite the data touching or crossing “difficult areas” in selected map projection. This includes, among others: • Cutting the geometries so that they fit within the area of mathematical stability of the projection math, e.g., it will cut any bit at more than 45 degrees west and east from the central meridian of a transverse Mercator projection, or beyond 85 degrees north or south in a Mercator projection • Make sure both “ends” of the world get queried for data when a map in polar stereographic is hitting an area that includes the dateline Along with advanced projection handling there is the possibility of creating a continuous map across the dateline, wrapping the data on the other side of the longitude range, to get a continuous map. This is called continuous map wrapping, and it’s enabled in Mercator and Equirectangular (plate carrée) projections. Both functionalities are rather useful, and enabled by default, but the tendency to generate multiple ored bounding boxes (to query both sides of the dateline) can cause extreme slowness in certain databases 7.1. Web Map Service (WMS) 1067 GeoServer User Manual, Release 2.15.1 (e.g. Oracle), and some users might simply not like the wrapping output, thus, it’s possible to disable both functions in the WMS UI: Continuous map wrapping is disabled if advanced projection handling is disabled. Advanced projection handling can also be disabled using the advancedProjectionHandling Format Option. Similarly, continuous map wrapping can also be disabled using the mapWrapping Format Option. Restricting MIME types for GetMap and GetFeatureInfo requests GeoServer supports restricting formats for WMS GetMap and WMS GetFeatureInfo requests. The default is to allow all MIME types for both kinds of request. The following figure shows an example for MIME type restriction. The MIME types image/png and text/html;subtype=openlayers are allowed for GetMap requests, the MIME types text/html and text/plain are allowed for GetFeatureInfo requests. A GetMap/GetFeatureInfo request with a MIME type not allowed will result in a service exception reporting the error. Note: Activating MIME type restriction and not allowing at least one MIME type disables the particular request. Disabling usage of dynamic styling in GetMap and GetFeatureInfo requests Dynamic styles can be applied to layers in GetMap and GetFeatureInfo requests using the SLD or SLD_BODY parameters for GET requests. In addition, GetMap POST requests can contain inline style definition for layers. The usage of dynamic styling can be restricted on a global or per virtual service basis using the Dynamic styling section. When the flag is checked, a GetMap/GetFeatureInfo request with a dynamic style will result in a service exception reporting the error. Disabling GetFeatureInfo requests results reprojection By default GetFeatureInfo results are reproject to the map coordinate reference system. This behavior can be deactivated on a global or per virtual service basis in the GetFeatureInfo results reprojection section. 1068 Chapter 7. Services GeoServer User Manual, Release 2.15.1 7.1. Web Map Service (WMS) 1069 GeoServer User Manual, Release 2.15.1 When the flag is checked, GetFeatureInfo requests results will not be reprojected and will instead used the layer coordinate reference system. 7.1.2 WMS basics GeoServer provides support for Open Geospatial Consortium (OGC) Web Map Service (WMS) versions 1.1.1 and 1.3.0. This is the most widely used standard for generating maps on the web, and it is the primary interface to request map products from GeoServer. Using WMS makes it possible for clients to overlay maps from several different sources in a seamless way. GeoServer’s WMS implementation fully supports the standard, and is certified compliant against the OGC’s test suite. It includes a wide variety of rendering and labeling options, and is one of the fastest WMS Servers for both raster and vector data. GeoServer WMS supports reprojection to any coordinate reference system in the EPSG database. It is possible to add additional coordinate systems if the Well Known Text definition is known. See Coordinate Reference System Handling for details. GeoServer fully supports the Styled Layer Descriptor (SLD) standard, and uses SLD files as its native styling language. For more information on how to style data in GeoServer see the section Styling Differences between WMS versions The major differences between versions 1.1.1 and 1.3.0 are: • In 1.1.1 geographic coordinate systems specified with the EPSG namespace are defined to have an axis ordering of longitude/latitude. In 1.3.0 the ordering is latitude/longitude. See Axis Ordering below for more details. • In the GetMap operation the srs parameter is called crs in 1.3.0. GeoServer supports both keys regardless of version. • In the GetFeatureInfo operation the x and y parameters are called i and j in 1.3.0. GeoServer supports both keys regardless of version, except when in CITE-compliance mode. Axis Ordering The WMS 1.3.0 specification mandates that the axis ordering for geographic coordinate systems defined in the EPSG database be latitude/longitude, or y/x. This is contrary to the fact that most spatial data is usually in longitude/latitude, or x/y. This requires that the coordinate order in the BBOX parameter be reversed for SRS values which are geographic coordinate systems. For example, consider the WMS 1.1 request using the WGS84 SRS (EPSG:4326): geoserver/wms?VERSION=1.1.1&REQUEST=GetMap&SRS=epsg:4326&BBOX=-180,-90,180,90&... The equivalent WMS 1.3.0 request is: geoserver/wms?VERSION=1.3.0&REQUEST=GetMap&CRS=epsg:4326&BBOX=-90,-180,90,180&... Note that the coordinates specified in the BBOX parameter are reversed. 1070 Chapter 7. Services GeoServer User Manual, Release 2.15.1 7.1.3 WMS reference Introduction The OGC Web Map Service (WMS) specification defines an HTTP interface for requesting georeferenced map images from a server. GeoServer supports WMS 1.1.1, the most widely used version of WMS, as well as WMS 1.3.0. The relevant OGC WMS specifications are: • OGC Web Map Service Implementation Specification, Version 1.1.1 • OGC Web Map Service Implementation Specification, Version 1.3.0 GeoServer also supports some extensions to the WMS specification made by the Styled Layer Descriptor (SLD) standard to control the styling of the map output. These are defined in: • OpenGIS Styled Layer Descriptor Profile of the Web Map Service Implementation Specification, Version 1.1.0 Benefits of WMS WMS provides a standard interface for requesting a geospatial map image. The benefit of this is that WMS clients can request images from multiple WMS servers, and then combine them into a single view for the user. The standard guarantees that these images can all be overlaid on one another as they actually would be in reality. Numerous servers and clients support WMS. Operations WMS requests can perform the following operations: Operation Description Exceptions If an exception occur GetCapabilities Retrieves metadata about the service, including supported operations and parameters, and a list of the available layers GetMap Retrieves a map image for a specified area and content GetFeatureInfo Retrieves the underlying data, including geometry and attribute values, for a pixel (optional) location on a map DescribeLayer Indicates the WFS or WCS to retrieve additional information about the layer. (optional) GetLegendGraphicRetrieves a generated legend for a map (optional) Exceptions Formats in which WMS can report exceptions. The supported values for exceptions are: 7.1. Web Map Service (WMS) 1071 GeoServer User Manual, Release 2.15.1 Format XML Syntax EXCEPTIONS=application/ vnd.ogc.se_xml INIMAGE EXCEPTIONS=application/ vnd.ogc.se_inimage BLANK EXCEPTIONS=application/ vnd.ogc.se_blank PARTIALMAP EXCEPTIONS=application/ vnd.gs.wms_partial JSON JSONP EXCEPTIONS=application/ json EXCEPTIONS=text/ javascript Notes Xml output. (The default format) Generates an image Generates a blank image This is a GeoServer vendor parameter and only applicable for getMap requests. Returns everything that was rendered at the time the rendering process threw an exception. Can be used with the WMS Configuration Limits to return a partial image even if the request is terminated for exceeding one of these limits. It also works with the timeout vendor parameter. Simple Json representation. Return a JsonP in the form: paddingOutput(. . . jsonp. . . ). See WMS vendor parameters to change the callback name. Note that this format is disabled by default (See Global variables affecting WMS). GetCapabilities The GetCapabilities operation requests metadata about the operations, services, and data (“capabilities”) that are offered by a WMS server. The parameters for the GetCapabilities operation are: Parameter service version request Required?Description Yes Service name. Value is WMS. Yes Service version. Value is one of 1.0.0, 1.1.0, 1.1.1, 1.3.0. Yes Operation name. Value is GetCapabilities. GeoServer provides the following vendor-specific parameters for the GetCapabilities operation. They are fully documented in the WMS vendor parameters section. Parameter namespace format Required?Description No limits response to layers in a given namespace No request the capabilities document in a certain format A example GetCapabilities request is: http://localhost:8080/geoserver/wms? service=wms& version=1.1.1& request=GetCapabilities There are three parameters being passed to the WMS server, service=wms, version=1.1.1, and request=GetCapabilities. The service parameter tells the WMS server that a WMS request is forthcoming. The version parameter refers to which version of WMS is being requested. The request pa1072 Chapter 7. Services GeoServer User Manual, Release 2.15.1 rameter specifies the GetCapabilities operation. The WMS standard requires that requests always includes these three parameters. GeoServer relaxes these requirements (by setting the default version if omitted), but for standard-compliance they should always be specified. The response is a Capabilities XML document that is a detailed description of the WMS service. It contains three main sections: Service Request Layer Contains service metadata such as the service name, keywords, and contact information for the organization operating the server. Describes the operations the WMS service provides and the parameters and output formats for each operation. If desired GeoServer can be configured to disable support for certain WMS operations. Lists the available coordinate systems and layers. In GeoServer layers are named in the form “namespace:layer”. Each layer provides service metadata such as title, abstract and keywords. GetMap The GetMap operation requests that the server generate a map. The core parameters specify one or more layers and styles to appear on the map, a bounding box for the map extent, a target spatial reference system, and a width, height, and format for the output. The information needed to specify values for parameters such as layers, styles and srs can be obtained from the Capabilities document. The response is a map image, or other map output artifact, depending on the format requested. GeoServer provides a wide variety of output formats, described in WMS output formats. The standard parameters for the GetMap operation are: 7.1. Web Map Service (WMS) 1073 GeoServer User Manual, Release 2.15.1 Parameter service version request layers styles srs or crs bbox width height format transparent bgcolor exceptions time sld sld_body Required?Description Yes Service name. Value is WMS. Yes Service version. Value is one of 1.0.0, 1.1.0, 1.1.1, 1.3.0. Yes Operation name. Value is GetMap. Yes Layers to display on map. Value is a comma-separated list of layer names. Yes Styles in which layers are to be rendered. Value is a comma-separated list of style names, or empty if default styling is required. Style names may be empty in the list, to use default layer styling. Yes Spatial Reference System for map output. Value is in form EPSG:nnn. crs is the parameter key used in WMS 1.3.0. Yes Bounding box for map extent. Value is minx,miny,maxx,maxy in units of the SRS. Yes Width of map output, in pixels. Yes Height of map output, in pixels. Yes Format for the map output. See WMS output formats for supported values. No Whether the map background should be transparent. Values are true or false. Default is false No Background color for the map image. Value is in the form RRGGBB. Default is FFFFFF (white). No Format in which to report exceptions. Default value is application/ vnd.ogc.se_xml. No Time value or range for map data. See Time Support in GeoServer WMS for more information. No A URL referencing a StyledLayerDescriptor XML file which controls or enhances map layers and styling No A URL-encoded StyledLayerDescriptor XML document which controls or enhances map layers and styling GeoServer provides a number of useful vendor-specific parameters for the GetMap operation. These are documented in the WMS vendor parameters section. Example WMS request for topp:states layer to be output as a PNG map image in SRS EPGS:4326 and using default styling is: http://localhost:8080/geoserver/wms? request=GetMap &service=WMS &version=1.1.1 &layers=topp%3Astates &styles=population &srs=EPSG%3A4326 &bbox=-145.15104058007,21.731919794922,-57.154894212888,58.961058642578& &width=780 &height=330 &format=image%2Fpng The standard specifies many of the parameters as being mandatory, GeoServer provides the WMS Reflector to allow many of them to be optionally specified. Experimenting with this feature is a good way to get to know the GetMap parameters. Example WMS request using a GetMap XML document is: 1074 Chapter 7. Services GeoServer User Manual, Release 2.15.1 topp:states population -13024 -5550 image/png 550250 Time As of GeoServer 2.2.0, GeoServer supports a TIME attribute for WMS GetMap requests as described in version 1.3.0 of the WMS specification. This parameter allows filtering a dataset by temporal slices as well as spatial tiles for rendering. See Time Support in GeoServer WMS for information on its use. GetFeatureInfo The GetFeatureInfo operation requests the spatial and attribute data for the features at a given location on a map. It is similar to the WFS GetFeature operation, but less flexible in both input and output. Since GeoServer provides a WFS service we recommend using it instead of GetFeatureInfo whenever possible. The one advantage of GetFeatureInfo is that the request uses an (x,y) pixel value from a returned WMS image. This is easier to use for a naive client that is not able to perform true geographic referencing. The standard parameters for the GetFeatureInfo operation are: 7.1. Web Map Service (WMS) 1075 GeoServer User Manual, Release 2.15.1 Parameter service version request layers styles srs or crs bbox width height query_layers info_format feature_count x or i y or j exceptions Required?Description Yes Service name. Value is WMS. Yes Service version. Value is one of 1.0.0, 1.1.0, 1.1.1, 1.3.0. Yes Operation name. Value is GetFeatureInfo. Yes See GetMap Yes See GetMap Yes See GetMap Yes See GetMap Yes See GetMap Yes See GetMap Yes Comma-separated list of one or more layers to query. No Format for the feature information response. See below for values. No Maximum number of features to return. Default is 1. Yes X ordinate of query point on map, in pixels. 0 is left side. i is the parameter key used in WMS 1.3.0. Yes Y ordinate of query point on map, in pixels. 0 is the top. j is the parameter key used in WMS 1.3.0. No Format in which to report exceptions. The default value is application/vnd.ogc.se_xml. Note: If you are sending a GetFeatureInfo request against a layergroup, all the layers in that layergroup must be set as “Queryable” to get a result (See WMS Settings on Layers page) GeoServer supports a number of output formats for the GetFeatureInfo response. Server-styled HTML is the most commonly-used format. For maximum control and customisation the client should use GML3 and style the raw data itself. The supported formats are: Format TEXT GML 2 GML 3 HTML JSON JSONP Syntax info_format=text/plain info_format=application/ vnd.ogc.gml info_format=application/ vnd.ogc.gml/3.1.1 info_format=text/html info_format=application/ json info_format=text/ javascript Notes Simple text output. (The default format) Works only for Simple Features (see Complex Features) Works for both Simple and Complex Features (see Complex Features) Uses HTML templates that are defined on the server. See GetFeatureInfo Templates for information on how to template HTML output. Simple Json representation. Returns a JsonP in the form: parseResponse(. ..json...). See WMS vendor parameters to change the callback name. Note that this format is disabled by default (See Global variables affecting WMS). GeoServer provides the following vendor-specific parameters for the GetFeatureInfo operation. They are fully documented in the WMS vendor parameters section. Parameter buffer cql_filter filter propertyName 1076 Required?Description No width of search radius around query point. No Filter for returned data, in ECQL format No Filter for returned data, in OGC Filter format No Feature properties to be returned Chapter 7. Services GeoServer User Manual, Release 2.15.1 An example request for feature information from the topp:states layer in HTML format is: http://localhost:8080/geoserver/wms? request=GetFeatureInfo &service=WMS &version=1.1.1 &layers=topp%3Astates &styles= &srs=EPSG%3A4326 &format=image%2Fpng &bbox=-145.151041%2C21.73192%2C-57.154894%2C58.961059 &width=780 &height=330 &query_layers=topp%3Astates &info_format=text%2Fhtml &feature_count=50 &x=353 &y=145 &exceptions=application%2Fvnd.ogc.se_xml An example request for feature information in GeoJSON format is: http://localhost:8080/geoserver/wms? &INFO_FORMAT=application/json &REQUEST=GetFeatureInfo &EXCEPTIONS=application/vnd.ogc.se_xml &SERVICE=WMS &VERSION=1.1.1 &WIDTH=970&HEIGHT=485&X=486&Y=165&BBOX=-180,-90,180,90 &LAYERS=COUNTRYPROFILES:grp_administrative_map &QUERY_LAYERS=COUNTRYPROFILES:grp_administrative_map &TYPENAME=COUNTRYPROFILES:grp_administrative_map The result will be: { "type":"FeatureCollection", "features":[ { "type":"Feature", "id":"dt_gaul_geom.fid-138e3070879", "geometry":{ "type":"MultiPolygon", "coordinates":[ [ [ [ XXXXXXXXXX, XXXXXXXXXX ], ... [ XXXXXXXXXX, XXXXXXXXXX ] ] ] ] }, 7.1. Web Map Service (WMS) 1077 GeoServer User Manual, Release 2.15.1 "geometry_name":"at_geom", "properties":{ "bk_gaul":X, "at_admlevel":0, "at_iso3":"XXX", "ia_name":"XXXX", "at_gaul_l0":X, "bbox":[ XXXX, XXXX, XXXX, XXXX ] } } ], "crs":{ "type":"EPSG", "properties":{ "code":"4326" } }, "bbox":[ XXXX, XXXX, XXXX, XXXX ] } DescribeLayer The DescribeLayer operation is used primarily by clients that understand SLD-based WMS. In order to make an SLD one needs to know the structure of the data. WMS and WFS both have operations to do this, so the DescribeLayer operation just routes the client to the appropriate service. The standard parameters for the DescribeLayer operation are: Parameter service version request layers exceptions Required?Description Yes Service name. Value is WMS. Yes Service version. Value is 1.1.1. Yes Operation name. Value is DescribeLayer. Yes See GetMap No Format in which to report exceptions. application/vnd.ogc.se_xml. The default value is GeoServer supports a number of output formats for the DescribeLayer response. Server-styled HTML is the most commonly-used format. The supported formats are: 1078 Chapter 7. Services GeoServer User Manual, Release 2.15.1 Format TEXT GML 2 JSON JSONP Syntax output_format=text/xml output_format=application/ vnd.ogc.wms_xml output_format=application/ json output_format=text/ javascript Notes Same as default. The default format. Simple Json representation. Return a JsonP in the form: paddingOutput(. . . jsonp. . . ). See WMS vendor parameters to change the callback name. Note that this format is disabled by default (See Global variables affecting WMS). An example request in XML (default) format on a layer is: : http://localhost:8080/geoserver/topp/wms?service=WMS quest=DescribeLayer &layers=topp:coverage &version=1.1.1 &re- An example request for feature description in JSON format on a layer group is: http://localhost:8080/geoserver/wms?service=WMS &version=1.1.1 &request=DescribeLayer &layers=sf:roads,topp:tasmania_roads,nurc:mosaic &outputFormat=application/json The result will be: { version: "1.1.1", layerDescriptions: [ { layerName: "sf:roads", owsURL: "http://localhost:8080/geoserver/wfs/WfsDispatcher?", owsType: "WFS", typeName: "sf:roads" }, { layerName: "topp:tasmania_roads", owsURL: "http://localhost:8080/geoserver/wfs/WfsDispatcher?", owsType: "WFS", typeName: "topp:tasmania_roads" }, { layerName: "nurc:mosaic", owsURL: "http://localhost:8080/geoserver/wcs?", owsType: "WCS", typeName: "nurc:mosaic" 7.1. Web Map Service (WMS) 1079 GeoServer User Manual, Release 2.15.1 } ] GetLegendGraphic The GetLegendGraphic operation provides a mechanism for generating legend graphics as images, beyond the LegendURL reference of WMS Capabilities. It generates a legend based on the style defined on the server, or alternatively based on a user-supplied SLD. For more information on this operation and the various options that GeoServer supports see GetLegendGraphic. 7.1.4 Time Support in GeoServer WMS GeoServer supports a TIME attribute in GetMap requests for layers that are properly configured with a time dimension. This is used to specify a temporal subset for rendering. For example, you might have a single dataset with weather observations collected over time and choose to plot a single day’s worth of observations. The attribute to be used in TIME requests can be set up through the GeoServer web interface by navigating to Layers -> [specific layer] -> Dimensions tab. Note: Read more about how to use the web interface to configure an attribute for TIME requests. Specifying a time The format used for specifying a time in the WMS TIME parameter is based on ISO-8601. Times may be specified up to a precision of 1 millisecond; GeoServer does not represent time queries with more precision than this. The parameter is: TIME= Times follow the general format: yyyy-MM-ddThh:mm:ss.SSSZ where: • yyyy: 4-digit year • MM: 2-digit month • dd: 2-digit day • hh: 2-digit hour • mm: 2-digit minute • ss: 2-digit second • SSS: 3-digit millisecond 1080 Chapter 7. Services GeoServer User Manual, Release 2.15.1 The day and intraday values are separated with a capital T, and the entire thing is suffixed with a Z, indicating UTC for the time zone. (The WMS specification does not provide for other time zones.) GeoServer will apply the TIME value to all temporally enabled layers in the LAYERS parameter of the GetMap request. Layers without a temporal component will be served normally, allowing clients to include reference information like political boundaries along with temporal data. Description December 12, 2001 at 6:00 PM May 5, 1993 at 11:34 PM Time specification 2001-12-12T18:00:00.0Z 1993-05-05T11:34:00.0Z Specifying an absolute interval A client may request information over a continuous interval instead of a single instant by specifying a start and end time, separated by a / character. In this scenario the start and end are inclusive; that is, samples from exactly the endpoints of the specified range will be included in the rendered tile. Description The month of September 2002 The entire day of December 25, 2010 Time specification 2002-09-01T00:00:00.0Z/2002-09-30T23:59:59.999Z 2010-12-25T00:00:00.0Z/2010-12-25T23:59:59.999Z Specifying a relative interval A client may request information over a relative time interval instead of a set time range by specifying a start or end time with an associated duration, separated by a / character. One end of the interval must be a time value, but the other may be a duration value as defined by the ISO 8601 standard. The special keyword PRESENT may be used to specify a time relative to the present server time. Description The month of September 2002 The entire day of December 25, 2010 The entire day preceding December 25, 2010 36 hours preceding the current time Time specification 2002-09-01T00:00:00.0Z/P1M 2010-12-25T00:00:00.0Z/P1D P1D/2010-12-25T00:00:00.0Z PT36H/PRESENT Note: The final example could be paired with the KML service to provide a Google Earth network link which is always updated with the last 36 hours of data. Reduced accuracy times The WMS specification also allows time specifications to be truncated by omitting some of the time string. In this case, GeoServer treats the time as a range whose length is equal to the most precise unit specified in the time string. For example, if the time specification omits all fields except year, it identifies a range one year long starting at the beginning of that year. 7.1. Web Map Service (WMS) 1081 GeoServer User Manual, Release 2.15.1 Note: GeoServer implements this by adding the appropriate unit, then subtracting 1 millisecond. This avoids surprising results when using an interval that aligns with the actual sampling frequency of the data - for example, if yearly data is natively stored with dates like 2001-01-01T00:00:00.0Z, 2002-01-01T00:00:00Z, etc. then a request for 2001 would include the samples for both 2001 and 2002, which wouldn’t be desired. Description The month of September 2002 The day of December 25, 2010 Reduced Accuracy Time 2002-09 2010-12-25 Equivalent Range 2002-09-01T00:00:00.0Z/ 2002-09-30T23:59:59.999Z 2010-12-25T00:00:00.0Z/ 2010-12-25T23:59:59.999Z Reduced accuracy times with ranges Reduced accuracy times are also allowed when specifying ranges. In this case, GeoServer effectively expands the start and end times as described above, and then includes any samples from after the beginning of the start interval and before the end of the end interval. Note: Again, the ranges are inclusive. Description The months of September through December 2002 12PM through 6PM, December 25, 2010 Reduced Accuracy Time 2002-09/2002-12 2010-12-25T12/ 2010-12-25T18 Equivalent Range 2002-09-01T00:00:00.0Z/ 2002-12-31T23:59:59.999Z 2010-12-25T12:00:00.0Z/ 2010-12-25T18:59:59.999Z Note: In the last example, note that the result may not be intuitive, as it includes all times from 6PM to 6:59PM. Specifying a list of times GooServer can also accept a list of discrete time values. This is useful for some applications such as animations, where one time is equal to one frame. The elements of a list are separated by commas. Note: GeoServer currently does not support lists of ranges, so all list queries effectively have a resolution of 1 millisecond. If you use reduced accuracy notation when specifying a range, each range will be automatically converted to the instant at the beginning of the range. If the list is evenly spaced (for example, daily or hourly samples) then the list may be specified as a range, using a start time, end time, and period separated by slashes. 1082 Chapter 7. Services GeoServer User Manual, Release 2.15.1 Description Noon every day for August 12-14, 2012 List notation TIME=2012-08-12T12:00:00. 0Z,2012-08-13T12:00:00.0Z, 2012-08-14T12:00:00.0Z Midnight on the first of September, October, and November 1999 TIME=1999-09-01T00:00:00. 0Z,1999-10-01T00:00:00.0Z, 1999-11-01T00:00:00.0Z Equivalent range notation TIME=2012-08-12T12:00:00. 0Z/ 2012-08-18:T12:00:00. 0Z/P1D TIME=1999-09-01T00:00:00. 0Z/ 1999-11-01T00:00:00. 0Z/P1M Specifying a periodicity The periodicity is also specified in ISO-8601 format: a capital P followed by one or more interval lengths, each consisting of a number and a letter identifying a time unit: Unit Years Months Days Hours Minutes Seconds Abbreviation Y M D H M S The Year/Month/Day group of values must be separated from the Hours/Minutes/Seconds group by a T character. The T itself may be omitted if hours, minutes, and seconds are all omitted. Additionally, fields which contain a 0 may be omitted entirely. Fractional values are permitted, but only for the most specific value that is included. Note: The period must divide evenly into the interval defined by the start/end times. So if the start/end times denote 12 hours, a period of 1 hour would be allowed, but a period of 5 hours would not. For example, the multiple representations listed below are all equivalent. • One hour: P0Y0M0DT1H0M0S PT1H0M0S PT1H • 90 minutes: P0Y0M0DT1H30M0S PT1H30M P90M • 18 months: 7.1. Web Map Service (WMS) 1083 GeoServer User Manual, Release 2.15.1 P1Y6M0DT0H0M0S P1Y6M0D P0Y18M0DT0H0M0S P18M Note: P1.25Y3M would not be acceptable, because fractional values are only permitted in the most specific value given, which in this case would be months. 7.1.5 WMS output formats WMS returns images in a number of possible formats. This page shows a list of the output formats. The syntax for setting an output format is: format= where is any of the options below. Note: The list of output formats supported by a GeoServer instance can be found by a WMS GetCapabilities request. 1084 Chapter 7. Services GeoServer User Manual, Release 2.15.1 Format PNG PNG8 Syntax format=image/png format=image/png8 JPEG JPEG-PNG format=image/jpeg format=image/vnd. jpeg-png JPEG-PNG8 format=image/vnd. jpeg-png8 GIF TIFF TIFF8 format=image/gif format=image/tiff format=image/tiff8 GeoTIFF format=image/geotiff GeoTIFF8 format=image/geotiff8 SVG PDF format=image/svg format=application/ pdf format=rss format=kml format=kmz format=application/ openlayers format=application/ json;type=utfgrid GeoRSS KML KMZ OpenLayers UTFGrid 7.1. Web Map Service (WMS) Notes Default Same as PNG, but computes an optimal 256 color (8 bit) palette, so the image size is usually smaller A custom format that will decide dynamically, based on the image contents, if it’s best to use a JPEG or PNG compression. The images are returned in JPEG format if fully opaque and not paletted. In order to use this format in a meaningful way the GetMap must include a “&transparent=TRUE” parameter, as without it GeoServer generates opaque images with the default/requested background color, making this format always return JPEG images (or always PNG, if they are paletted). When using the layer preview to test this format, remember to add “&transparent=TRUE” to the preview URL, as normally the preview generates non transparent images. Same as JPEG-PNG, but generating a paletted output if the PNG format is chosen Same as TIFF, but computes an optimal 256 color (8 bit) palette, so the image size is usually smaller Same as TIFF, but includes extra GeoTIFF metadata Same as TIFF, but includes extra GeoTIFF metadata and computes an optimal 256 color (8 bit) palette, so the image size is usually smaller Generates an OpenLayers HTML application. Generates an UTFGrid 1.3 JSON response. Requires vector output, either from a vector layer, or from a raster layer turned into vectors by a rendering transformation. 1085 GeoServer User Manual, Release 2.15.1 7.1.6 WMS vendor parameters WMS vendor parameters are non-standard request parameters that are defined by an implementation to provide enhanced capabilities. GeoServer supports a variety of vendor-specific WMS parameters. angle The angle parameter rotates the output map clockwise around its center. The syntax is: angle= where is the number of degrees to rotate by. Map rotation is supported in all raster formats, PDF, and SVG when using the Batik producer (which is the default). buffer The buffer parameter specifies the number of additional border pixels that are used in the GetMap and GetFeatureInfo operations. The syntax is: buffer= where is the width of the buffer in pixels. In the GetMap operation, buffering includes features that lie outside the request bounding box, but whose styling is thick enough to be visible inside the map area. In the GetFeatureInfo operation, buffering creates a “search radius” around the location of the request. Feature info is returned for features intersecting the search area. This is useful when working with an OpenLayers map (such as those generated by the Layer Preview page) since it relaxes the need to click precisely on a point for the appropriate feature info to be returned. In both operations GeoServer attempts to compute the buffer value automatically by inspecting the styles for each layer. All active symbolizers are evaluated, and the size of the largest is used (i.e. largest point symbolizer, thickest line symbolizer). Automatic buffer sizing cannot be computed if: • the SLD contains sizes that are specified as feature attribute values • the SLD contains external graphics and does not specify their size explicitly In this event, the following defaults are used: • 0 pixels for GetMap requests • 5 pixels for GetFeatureInfo requests (a different min value can be set via the org.geoserver.wms. featureinfo.minBuffer system variable, e.g., add -Dorg.geoserver.wms.featureinfo. minBuffer=10 to make the min buffer be 10 pixels) If these are not sufficiently large, the explicit parameter can be used. cql_filter The cql_filter parameter is similar to the standard filter parameter, but the filter is expressed using ECQL (Extended Common Query Language). ECQL provides a more compact and readable syntax compared to OGC XML filters. For full details see the ECQL Reference and CQL and ECQL tutorial. 1086 Chapter 7. Services GeoServer User Manual, Release 2.15.1 If more than one layer is specified in the layers parameter, then a separate filter can be specified for each layer, separated by semicolons. The syntax is: cql_filter=filter1;filter2... An example of a simple CQL filter is: cql_filter=INTERSECTS(the_geom,%20POINT%20(-74.817265%2040.5296504)) sortBy The sortBy parameter allows to control the order of features/rasters displayed in the map, using the same syntax as WFS 1.0, that is: • &sortBy=att1 A|D,att2 A|D, ... for a single layer request • &sortBy=(att1Layer1 A|D,att2Layer1 A|D, ...)(att1Layer2 A|D,att2Layer2 A|D, ...)... when requesting multiple layers Care should be taken when using it as it has different behavior for raster layers, vector layers, and layer groups. In particular: • For raster layers, sortBy maps to a “SORTING” read parameter that the reader might expose (image mosaic exposes such parameter). In image mosaic, this causes the first granule found in the sorting will display on top, and then the others will follow. Thus, to sort a scattered mosaic of satellite images so that the most recent image shows on top, and assuming the time attribute is called ingestion in the mosaic index, the specification will be &sortBy=ingestion D. • For vector layers, sortBy maps to a sort by clause in the vector data source, and then painting happens using the normal “painter model” rules, so the first item returned is painted first, and then all others on top of it. Thus, to sort a set of event points so that the most recent event is painted on top, and assuming the attribute is called “date” in the vector layer, the specification will be &sortBy=date or &sortBy=date A (ascending direction being the default one). • For layer groups, the sort specification is going to be copied over all internal layers, so the spec has to be valid for all of them, or an error will be reported. An empty spec can be used for layer groups in this case, for example, layers=theGroup,theLayer&sortBy=(),(date A) env The env parameter defines the set of substitution values that can be used in SLD variable substitution. The syntax is: env=param1:value1;param2:value2;... See Variable substitution in SLD for more information. featureid The featureid parameter filters by feature ID, a unique value given to all features. Multiple features can be selected by separating the featureids by comma, as in this example: 7.1. Web Map Service (WMS) 1087 GeoServer User Manual, Release 2.15.1 featureid=states.1,states.45 filter The WMS specification allows only limited filtering of data. GeoServer enhances the WMS filter capability to match that provided by WFS. The filter parameter can specify a list of OGC XML filters. The list is enclosed in parentheses: ( ). When used in a GET request, the XML tag brackets must be URL-encoded. If more than one layer is specified in the layers parameter then a separate filter can be specified for each layer. An example of an OGC filter encoded in a GET request is: filter=%3CFilter%20xmlns:gml=%22http://www.opengis.net/gml%22%3E%3CIntersects%3E ,→%3CPropertyName%3Ethe_geom%3C/PropertyName%3E%3Cgml:Point%20srsName=%224326%22%3E ,→%3Cgml:coordinates%3E-74.817265,40.5296504%3C/gml:coordinates%3E%3C/gml:Point%3E%3C/ ,→Intersects%3E%3C/Filter%3E format_options The format_options is a container for parameters that are format-specific. The syntax is: format_options=param1:value1;param2:value2;... The supported format options are: • antialiasing (values = on, off, text): controls the use of antialiased rendering in raster output. • callback: specifies the callback function name for the jsonp response format (default is parseResponse). • dpi: sets the rendering DPI (dots-per-inch) for raster outputs. The OGC standard output resolution is 90 DPI. If you need to create high resolution images (e.g for printing) it is advisable to request a larger image size and specify a higher DPI. In general, the image size should be increased by a factor equal to targetDPI/90, with the target dpi set in the format options. For example, to print a 100x100 image at 300 DPI request a 333x333 image with the DPI value set to 300: &width=333&height=333&format_options=dpi:300 • layout: specifies a layout name to use. Layouts are used to add decorators such as compasses and legends. This capability is discussed further in the WMS Decorations section. • quantizer (values = octree, mediancut): controls the color quantizer used to produce PNG8 images. GeoServer 2.2.0 provides two quantizers, a fast RGB quantizer called octree that does not handle translucency and a slower but more accurate RGBA quantizer called mediancut. By default the first is used on opaque images, whilst the second is enabled if the client asks for a transparent image (transparent=true). This vendor parameter can be used to manually force the usage of a particular quantizer. • timeout: Apply a timeout value for a getMap request. If the timeout is reached, the getMap request is cancelled and an error is returned. The value used for the timeout will be the minimum of this format option and the global WMS timeout defined in the WMS configuration. A value of zero means no timeout. • kmattr (values = true, false): determines whether the KML returned by GeoServer should include clickable attributes or not. This parameter primarily affects Google Earth rendering. • legend (values = true, false): KML may add the legend. 1088 Chapter 7. Services GeoServer User Manual, Release 2.15.1 • kmscore (values = between 0 to force raster output and 100 to force vector output): parameter sets whether GeoServer should render KML data as vector or raster. This parameter primarily affects Google Earth rendering. • kmltitle: parameter sets the KML title. • kmlrefresh (values = greater than 0 or expires): Force Network Link reload in refresh mode on interval of seconds. When expires is specified client will refresh whenever the time has elapsed specified in cache expiration headers. The caching time may be set in the Layer configuration under Publishing tab setting HTTP Cache Time. This parameter primarily affects Google Earth rendering and is dependent on being respected by the client. Using a second interval is a more reliable choice. • kmlvisible (values = true, false): Indicates whether layers selected will default to enabled or not. Default behavior is enabled. This parameter primarily affects Google Earth rendering. • advancedProjectionHandling (values = true, false): Enable Disable advanced projection handling, if it is enabled in the GUI. If it is disabled in the GUI, this option has no effect. • mapWrapping (values = true, false): Enable Disable continuous map wrapping, if it is enabled in the GUI. If it is disabled in the GUI, this option has no effect. Continuous map wrapping will also be disabled if advancedProjectionHandling is disabled. maxFeatures and startIndex The parameters maxFeatures and startIndex can be used together to provide “paging” support. Paging is helpful in situations such as KML crawling, where it is desirable to be able to retrieve the map in sections when there are a large number of features. The startindex=n parameter specifies the index from which to start rendering in an ordered list of features. n must be a positive integer. The maxfeatures=n parameter sets a limit on the amount of features rendered. n must be a positive integer. When used with startindex, the features rendered will be the ones starting at the startindex value. Note that not all layers support paging. For a layer to be queried in this way, the underlying feature source must support paging. This is usually the case for databases (such as PostGIS). namespace The namespace parameter causes WMS GetCapabilities responses to be filtered to only contain layers in to a particular namespace. The syntax is: namespace= where is the namespace prefix. Warning: Using an invalid namespace prefix will not cause an error, but the capabilities document returned will contain no layers, only layer groups. Note: This affects the capabilities document only, not other requests. Other WMS operations will still process all layers, even when a namespace is specified. 7.1. Web Map Service (WMS) 1089 GeoServer User Manual, Release 2.15.1 palette It is sometimes advisable (for speed and bandwidth reasons) to downsample the bit depth of returned maps. The way to do this is to create an image with a limited color palette, and save it in the palettes directory inside your GeoServer Data Directory. It is then possible to specify the palette parameter of the form: palette= where is the filename of the palette image (without the extension). To force a web-safe palette, use the syntax palette=safe. For more information see the tutorial on Paletted Images propertyName The propertyName parameter specifies which properties are included in the response of the GetFeatureInfo operation. The syntax is the same as in the WFS GetFeature operation. For a request for a single layer the syntax is: propertyName=name1,...,nameN For multiple layers the syntax is: propertyName=(nameLayer11,...,nameLayer1N)...(name1LayerN,...,nameNLayerN) The nature of the properties depends on the layer type: • For vector layers the names specify the feature attributes. • For raster layers the names specify the bands. • For cascaded WMS layers the names specify the GML properties to be returned by the remote server. tiled Meta-tiling prevents issues with duplicated labels when using a tiled client such as OpenLayers. When meta-tiling is used, images are rendered and then split into smaller tiles (by default in a 3x3 pattern) before being served. In order for meta-tiling to work, the tile size must be set to 256x256 pixels, and the tiled and tilesorigin parameters must be specified. The tiled parameter controls whether meta-tiling is used. The syntax is: tiled=[true|false] To invoke meta-tiling use tiled=true. tilesorigin The tilesorigin parameter is also required for meta-tiling. The syntax is: tilesorigin=x,y where x and y are the coordinates of the lower left corner (the “origin”) of the tile grid system. 1090 Chapter 7. Services GeoServer User Manual, Release 2.15.1 OpenLayers example In OpenLayers, a good way to specify the tilesorigin is to reference the map extents directly. Warning: If the map extents are modified dynamically, the tilesorigin of each meta-tiled layer must be updated accordingly. The following code shows how to specify the meta-tiling parameters: 1 2 3 4 5 6 var options = { ... maxExtent: new OpenLayers.Bounds(-180, -90, 180, 90), ... }; map = new OpenLayers.Map('map', options); 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 tiled = new OpenLayers.Layer.WMS( "Layer name", "http://localhost:8080/geoserver/wms", { srs: 'EPSG:4326', width: 391, styles: '', height: 550, layers: 'layerName', format: 'image/png', tiled: true, tilesorigin: map.maxExtent.left + ',' + map.maxExtent.bottom }, {buffer: 0} ); scaleMethod The scaleMethod parameter controls how the scale denominator is computed by GeoServer The two possible values are: • OGC (default): the scale denominator is computed according to the OGC SLD specification, which imposes simplified formulas for the sake of interoperability • Accurate: use the full expressions for computing the scale denominator against geographic data, taking into account the ellipsoidal shape of Earth The two methods tend to return values rather close to each other near the equator, but they do diverge to larger differences as the latitude approaches the poles. interpolations The interpolations parameter allows choosing a specific resampling (interpolation) method. It can be used in the GetMap operation. If more than one layer is specified in the layers parameter, then a separate interpolation method can be specified for each layer, separated by commas. The syntax is: 7.1. Web Map Service (WMS) 1091 GeoServer User Manual, Release 2.15.1 interpolations=method1,method2,... method values can be one of the following: • nearest neighbor • bilinear • bicubic or empty if the default method has to be used for the related layer. The parameter allows to override the global WMS Raster Rendering Options setting (see WMS Settings for more info), as well as the layer specific Default Interpolation Method publishing parameter (see Layers for more info), on a layer by layer basis. format The format parameter can be used to request capabilities documents in a certain format. If the requested format is not supported the default format will be used. An example request: http://localhost:8080/geoserver/ows?service=wms&version=1.1.1&request= GetCapabilities&format=text/xml Note: Currently this parameter can only be used to request WMS 1.1.1 capabilities documents encoded in text/xml, if used with other WMS versions or other formats it will have no effect. 7.1.7 Non Standard AUTO Namespace The WMS standard supports a small number of “automatic” coordinate reference systems that include a user-selected centre of projection. These are specified using: AUTO:auto_crs_id,factor,lon0,lat0 for example: CRS=AUTO:42003,1,-100,45 Note: in GeoServer 2.8.x AUTO and AUTO2 namespaces are treated identically. Note: in GeoServer 2.8.x the factor parameter in the AUTO namespace is ignored. The BBOX parameter to GetMap must therefore be specified in metres. The WMS standard provide projections with IDs in the range 42001 to 42005. 1092 Chapter 7. Services GeoServer User Manual, Release 2.15.1 ID 42001 42002 42003 42004 42005 Projection Universal Transverse Mercator Transverse Mercator Orthographic Equirectangular Mollweide (not supported in GeoServer 2.8.x) GeoServer also supports some non-standard coordinate reference systems. These are ID 97001 97002 Projection Gnomonic Stereographic Note: the auto stereographic projection uses a sphere. It does this by setting the semi minor axis to the same value as the semi major axis. 7.1.8 WMS configuration Layer Groups A Layer Group is a group of layers that can be referred to by one layer name. For example, if you put three layers (call them layer_A, layer_B, and layer_C) under the one “Layer Group” layer, then when a user makes a WMS getMap request for that group name, they will get a map of those three layers. For information on configuring Layer Groups in the Web Administration Interface see Layer Groups Request limits The request limit options allow the administrator to limit the resources consumed by each WMS GetMap request. The following table shows the option names, a description, and the minimum GeoServer version at which the option is available (older versions will ignore it if set). 7.1. Web Map Service (WMS) 1093 GeoServer User Manual, Release 2.15.1 Option Max rendering memory (KB) Max rendering time (s) Max rendering errors (count) Max number of dimension values Description Sets the maximum amount of memory a single GetMap request is allowed to use (in kilobytes). The limit is checked before request execution by estimating how much memory would be required to produce the output in the format requested. For example, for an image format the estimate is based on the size of the required rendering memory (which is determined by the image size, the pixel bit depth, and the number of active FeatureTypeStyles at the requested scale). If the estimated memory size is below the limit, the request is executed; otherwise it is cancelled. Sets the maximum amount of time GeoServer will spend processing a request (in seconds). This time limits the “blind processing” portion of the request, that is, the time taken to read data and compute the output result (which may occur concurrently). If the execution time reaches the limit, the request is cancelled. The time required to write results back to the client is not limited by this parameter, since this is determined by the (unknown) network latency between the server and the client. For example, in the case of PNG/JPEG image generation, this option limits the data reading and rendering time, but not the time taken to write the image out. Sets the maximum amount of rendering errors tolerated by a GetMap request. By default GetMap makes a best-effort attempt to serve the result, ignoring invalid features, reprojection errors and the like. Setting a limit on the number of errors ignored can make it easier to notice issues, and conserves CPU cycles by reducing the errors which must be handled and logged Sets the maximum number of dimension (time, elevation, custom) values that a client can request in a GetMap/GetFeatureInfo request (the work to be done is usually proportional to said number of times, and the list of values is kept in memory during the processing) Version 1.7.5 1.7.5 1.7.5 2.14.0 The default value of each limit is 0, which specifies that the limit is not applied. If any of the request limits is exceeded, the GetMap operation is cancelled and a ServiceException is returned to the client. When setting the above limits it is suggested that peak conditions be taken into consideration. For example, under normal circumstances a GetMap request may take less than a second. Under high load it is acceptable for it to take longer, but it’s usually not desirable to allow a request to go on for 30 minutes. The following table shows examples of reasonable values for the request limits: 1094 Chapter 7. Services GeoServer User Manual, Release 2.15.1 Option Value maxRequestMemory 16384 maxRenderingTime 120 maxRenderingErrors100 Rationale 16MB are sufficient to render a 2048x2048 image at 4 bytes per pixel (full color and transparency), or a 8x8 meta-tile when using GeoWebCache or TileCache. Note that the rendering process uses a separate memory buffer for each FeatureTypeStyle in an SLD, so this also affects the maximum image size. For example, if an SLD contains two FeatureTypeStyle elements in order to draw cased lines for a highway, the maximum image size will be limited to 1448x1448 (the memory requirement increases with the product of the image dimensions, so halving the memory decreases image dimensions by only about 30%) A request that processes for a full two minutes is probably rendering too many features, regardless of the current server load. This may be caused by a request against a big layer using a style that does not have suitable scale dependencies Encountering 100 errors is probably the result of a request trying to reproject a big data set into a projection that is not appropriate for the output extent, resulting in many reprojection failures. 7.1.9 Global variables affecting WMS This document details the set of global variables that can affect WMS behaviour. Each global variable can be set as an environment variable, as a servlet context variable, or as a Java system property, just like the well known GEOSERVER_DATA_DIR setting. Refer to Setting the data directory location for details on how a global variable can be specified. MAX_FILTER_RULES A integer number (defaults to 20) When drawing a style containing multiple active rules the renderer combines the filters of the rules in OR and adds them to the standard bounding box filter. This behaviour is active up until the maximum number of filter rules is reached, past that the rule filters are no more added to avoid huge queries. By default up to 20 rules are combined, past 20 rules only the bounding box filter is used. Turning it off (setting it to 0) can be useful if the styles are mostly classifications, detrimental if the rule filters are actually filtering a good amount of data out. OPTIMIZE_LINE_WIDTH Can be true or false (defaults to: false). When true any stroke whose width is less than 1.5 pixels gets slimmed down to “zero”, which is actually not zero, but a very thin line. That was the behaviour GeoServer used to default to before the 2.0 series. When false the stroke width is not modified and it’s possible to specify widths less than one pixel. This is the default behaviour starting from the 2.0.0 release ENABLE_JSONP Can be true or false (defaults to: false). When true the JSONP (text/javascript) output format is enabled. 7.1. Web Map Service (WMS) 1095 GeoServer User Manual, Release 2.15.1 7.1.10 GetLegendGraphic This chapter describes whether to use the GetLegendGraphics request. The SLD Specifications 1.0.0 gives a good description about GetLegendGraphic requests: The GetLegendGraphic operation itself is optional for an SLD-enabled WMS. It provides a general mechanism for acquiring legend symbols, beyond the LegendURL reference of WMS Capabilities. Servers supporting the GetLegendGraphic call might code LegendURL references as GetLegendGraphic for interface consistency. Vendor-specific parameters may be added to GetLegendGraphic requests and all of the usual OGC-interface options and rules apply. No XML-POST method for GetLegendGraphic is presently defined. Here is an example invocation: http://localhost:8080/geoserver/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0& ,→FORMAT=image/png&WIDTH=20&HEIGHT=20&LAYER=topp:states which would produce four 20x20 icons that graphically represent the rules of the default style of the topp:states layer. Fig. 7.5: Sample legend In the following table the whole set of GetLegendGraphic parameters that can be used. 1096 Chapter 7. Services GeoServer User Manual, Release 2.15.1 Parameter REQUEST LAYER STYLE Required Description Required Value must be “GetLegendGraphic”. Required Layer for which to produce legend graphic. Optional Style of layer for which to produce legend graphic. If not present, the default style is selected. The style may be any valid style available for a layer, including nonSLD internally-defined styles. FEATURETYPEOptional Feature type for which to produce the legend graphic. This is not needed if the layer has only a single feature type. RULE Optional Rule of style to produce legend graphic for, if applicable. In the case that a style has multiple rules but no specific rule is selected, then the map server is obligated to produce a graphic that is representative of all of the rules of the style. SCALE Optional In the case that a RULE is not specified for a style, this parameter may assist the server in selecting a more appropriate representative graphic by eliminating internal rules that are out-of-scope. This value is a standardized scale denominator, defined in Section 10.2. Specifying the scale will also make the symbolizers using Unit Of Measure resize according to the specified scale. SLD Optional This parameter specifies a reference to an external SLD document. It works in the same way as the SLD= parameter of the WMS GetMap operation. SLD_BODY Optional This parameter allows an SLD document to be included directly in an HTTP-GET request. It works in the same way as the SLD_BODY= parameter of the WMS GetMap operation. FORMAT Required This gives the MIME type of the file format in which to return the legend graphic. Allowed values are the same as for the FORMAT= parameter of the WMS GetMap request. WIDTH Optional This gives a hint for the width of the returned graphic in pixels. Vector-graphics can use this value as a hint for the level of detail to include. HEIGHT Optional This gives a hint for the height of the returned graphic in pixels. EXCEPTIONS Optional This gives the MIME type of the format in which to return exceptions. Allowed values are the same as for the EXCEPTIONS= parameter of the WMS GetMap request. LANGUAGE Optional Allows setting labels language for style titles and rules titles; needs a correctly localized SLD to work properly; if labels are not available in the requested language, the default text will be used; look at i18N in SLD for further details. Controlling legend appearance with LEGEND_OPTIONS GeoServer allows finer control over the legend appearance via the vendor parameter LEGEND_OPTIONS. The general format of LEGEND_OPTIONS is the same as FORMAT_OPTIONS, that is: ...&LEGEND_OPTIONS=key1:v1;key2:v2;...;keyn:vn Here is a description of the various parameters that can be used in LEGEND_OPTIONS: • fontName (string) the name of the font to be used when generating rule titles. The font must be available on the server • fontStyle (string) can be set to italic or bold to control the text style. Other combination are not allowed right now but we could implement that as well. • fontSize (integer) allows us to set the Font size for the various text elements. Notice that default size is 12. • fontColor (hex) allows us to set the color for the text of rules and labels (see above for recommendation on how to create values). Values are expressed in 0xRRGGBB format 7.1. Web Map Service (WMS) 1097 GeoServer User Manual, Release 2.15.1 • fontAntiAliasing (true/false) when true enables antialiasing for rule titles • bgColor (hex) background color for the generated legend, values are expressed in 0xRRGGBB format • dpi (integer) sets the DPI for the current request, in the same way as it is supported by GetMap. Setting a DPI larger than 91 (the default) makes all fonts, symbols and line widths grow without changing the current scale, making it possible to get a high resolution version of the legend suitable for inclusion in printouts • forceLabels “on” means labels will always be drawn, even if only one rule is available. “off” means labels will never be drawn, even if multiple rules are available. Off by default. • labelMargin margin (in pixels) to use between icons and labels. • layout sets icons layout to be vertical (default) or horizontal. • columnheight enables multicolumn layout when layout is vertical. Each column height is limited by the columnheight value (in pixels). • rowwidth enables multirow layout when layout is horizontal. Each row width is limited by the rowwidth value (in pixels). • columns enables multicolumn layout when layout is vertical. The value is the maximum columns number of legend. The rows used are equal to the next greater integer of /. • rows enables multirow layout when layout is horizontal. The value is the the maximum rows number of legend. The columns used are equal to the next greater integer of /. • grouplayout Orientation of groups of layer, possible values are horizontal and vertical (default if not specified). • countMatched When set to true, adds at the end of each label the number of features matching that rule in the current map. Requires extra parameters, see details in the dedicated section. Here is a sample request sporting most the options: http://localhost:8080/geoserver/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0& ,→FORMAT=image/png&WIDTH=20&HEIGHT=20&LAYER=topp:states&legend_options=fontName:Times ,→%20New%20Roman;fontAntiAliasing:true;fontColor:0x000033;fontSize:14; ,→bgColor:0xFFFFEE;dpi:180 Fig. 7.6: Using LEGEND_OPTIONS to control the output Controlling legend layout A set of LEGEND_OPTIONS keys are used to control icons layout in the produced legend images. In particular, a vertical or horizontal layout can be chosen. 1098 Chapter 7. Services GeoServer User Manual, Release 2.15.1 Multi column or multi row layouts are possible, and are controlled by the columnheight / rowwidth options (to limit each column / row size) or by the columns / rows options (to fix the # of columns / rows to be used). Both columnheight / columns and rowwidth / rows can be used to limit the whole size of the produced image (some icons are skipped id they do not fit into the given limits). In addition, orientation of legends in a layergroup can be configured using the grouplayout option. Raster Legends Explained This chapter aim to briefly describe the work that I have performed in order to support legends for raster data that draw information taken from the various bits of the SLD 1.0 RasterSymbolizer element. Recall, that up to now there was no way to create legends for raster data, therefore we have tried to fill the gap by providing an implementation of the getLegendGraphic request that would work with the ColorMap element of the SLD 1.0 RasterSymbolizer. Notice that some “debug” info about the style, like colormap type and band used are printed out as well. What’s a raster legend Here below I have drawn the structure of a typical legend, where some elements of interests are parameterized. Fig. 7.7: The structure of a typical legend Take as an instance one of the SLD files attached to this page, each row in the above table draws its essence from the ColorMapEntry element as shown here below: The producer for the raster legend will make use of this elements in order to build the legend, with this regards, notice that: • the width of the Color element is driven by the requested width for the GetLegendGraphic request • the width and height of label and rules is computed accordingly to the used Font and Font size for the prepared text (no new line management for the moment) • the height of the Color element is driven by the requested width for the GetLegendGraphic request, but notice that for ramps we expand this a little since the goal is to turn the various Color elements into a single long strip 7.1. Web Map Service (WMS) 1099 GeoServer User Manual, Release 2.15.1 • the height of each row is set to the maximum height of the single elements • the width of each row is set to the sum of the width of the various elements plus the various paddings • dx,dy the spaces between elements and rows are set to the 15% of the requested width and height. Notice that dy is ignored for the colormaps of type ramp since they must create a continuous color strip. • absoluteMargins true/false, used to change the uom of dx from percentage (when false) to a fixed number of pixels (when true). • mx,my the margins from the border of the legends are set to the 1.5% of the total size of the legend Just to jump right to the conclusions (which is a bad practice I know, but no one is perfect ), here below I am adding an image of a sample legend with all the various options at work. The request that generated it is the following: http://localhost:8081/geoserver/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0& ,→FORMAT=image/png&WIDTH=100&HEIGHT=20&LAYER=it.geosolutions:di08031_da&LEGEND_ ,→OPTIONS=forceRule:True;dx:0.2;dy:0.2;mx:0.2;my:0.2;fontStyle:bold; ,→borderColor:0000ff;border:true;fontColor:ff0000;fontSize:18 Do not worry if it seems like something written in ancient dead language, I am going to explain the various params here below. Fig. 7.8: Example of a raster legend Raster legends’ types As you may know (well, actually you might not since I never wrote any real docs about the RasterSymbolizer work I did) GeoServer supports three types of ColorMaps: • ramp this is what SLD 1.0 dictates, which means a linear interpolation weighted on values between the colors of the various ColorMapEntries. 1100 Chapter 7. Services GeoServer User Manual, Release 2.15.1 • values this is an extensions that allows link quantities to colors as specified by the ColorMapEntries quantities. Values not specified are translated into transparent pixels. • classes this is an extensions that allows pure classifications based o intervals created from the ColorMapEntries quantities. Values not specified are translated into transparent pixels. Here below I am going to list various examples that use the attached styles on a rainfall floating point geotiff. ColorMap type is VALUES Refer to the SLD rainfall.sld in attachment. Fig. 7.9: Raster legend - VALUES type ColorMap type is CLASSES Refer to the SLD rainfall_classes.sld in attachment. ColorMap type is RAMP Refer to the SLD rainfall_classes.sld in attachment. Notice that the first legend show the default border behavior while the second has been force to draw a border for the breakpoint color of the the colormap entry quantity described by the rendered text. Notice that each color element has a part that show the fixed color from the colormap entry it depicts (the lowest part of it, the one that has been outlined by the border in the second legend below) while the upper part of the element has a gradient that connects each element to the previous one to point out the fact that we are using linear interpolation. The various control parameters and how to set them I am now going to briefly explain the various parameters that we can use to control the layout and content of the legend. A request that puts all the various options is shown here: 7.1. Web Map Service (WMS) 1101 GeoServer User Manual, Release 2.15.1 Fig. 7.10: Raster legend - CLASSES type Fig. 7.11: Raster legend - RAMP type 1102 Chapter 7. Services GeoServer User Manual, Release 2.15.1 http://localhost:8081/geoserver/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0& ,→FORMAT=image/png&WIDTH=100&HEIGHT=20&LAYER=it.geosolutions:di08031_da&LEGEND_ ,→OPTIONS=forceRule:True;dx:0.2;dy:0.2;mx:0.2;my:0.2;fontStyle:bold; ,→borderColor:0000ff;border:true;fontColor:ff0000;fontSize:18 Let’s now examine all the interesting elements, one by one. Notice that I am not going to discuss the mechanics of the GetLegendGraphic operation, for that you may want to refer to the SLD 1.0 spec, my goal is to briefly discuss the LEGEND_OPTIONS parameter. • forceRule (boolean) by default rules for a ColorMapEntry are not drawn to keep the legend small and compact, unless there are no labels at all. You can change this behaviour by setting this parameter to true. • dx,dy,mx,my (double) can be used to set the margin and the buffers between elements • border (boolean) activates or deactivates the border on the color elements in order to make the separations clearer. Notice that I decided to always have a line that would split the various color elements for the ramp type of colormap. • borderColor (hex) allows us to set the color for the border in 0xRRGGBB format CQL Expressions and ENV If cql expressions are used in ColorMapEntry attributes (see here) to create a dynamic color map taking values from ENV, the same ENV parameters used for GetMap can be given to GetLegendGraphic to get the desired legend entries. Content dependent legends GeoServer allows building content dependent legend, that is, legends whose contents depend on the currently displayed map. In order to support it the GetLegendGraphic call needs the following extra parameters: • BBOX • SRS or CRS (depending on the WMS version, SRS for 1.1.1 and CRS for 1.3.0) • SRCWITH and SRCHEIGHT, the size of the reference map (width and height already have a different meaning in GetLegendGraphic) Other parameters can also be added to better match the GetMap request, for example, it is recommended to mirror filtering vendor parameters such as, for example, CQL_FILTER,FILTER,FEATUREID,TIME,ELEVATION. Content dependent evaluation is enabled via the following LEGEND_OPTIONS parameters: • countMatched: adds the number of features matching the particular rule at the end of the rule label (requires visible labels to work). Applicable only to vector layers. More approaches may be added in future (e.g., making rules that are not matching any feature disappear). For example, let’s assume the following layout is added to GeoServer (legend.xml to be placed in GEOSERVER_DATA_DIR/layouts): 7.1. Web Map Service (WMS) 1103 GeoServer User Manual, Release 2.15.1 This will make a legend appear in the GetMap response. The following preview request uses the layout to embed a legend and activates feature counting in it: http://localhost:8080/geoserver/topp/wms?service=WMS&version=1.1.0&request=GetMap& ,→layers=topp:states&styles=&bbox=-124.73142200000001,24.955967,-66.969849,49.371735& ,→width=768&height=330&srs=EPSG:4326&format=application/openlayers&format_ ,→options=layout:legend&legend_options=countMatched:true;fontAntiAliasing:true The result will look as follows: Fig. 7.12: Embedded legend, full map Fig. 7.13: Embedded legend, four states The same can be achieved using a stand-alone GetLegendGraphic request: http://localhost:8080/geoserver/topp/wms?service=WMS&version=1.1.0& ,→request=GetLegendGraphic&width=20&height=20&layer=topp:states&bbox=-124. ,→73142200000001,24.955967,-66.969849,49.371735&srcwidth=768&srcheight=330& ,→srs=EPSG:4326&format=image/png&legend_options=countMatched:true; ,→fontAntiAliasing:true 1104 Chapter 7. Services GeoServer User Manual, Release 2.15.1 Fig. 7.14: Embedded legend, single state Fig. 7.15: Direct legend request JSON Output Format Since version 2.15.0 it has been possible to use application/json as an output format in GetLegendGraphic requests. This allows a JSON aware client to receive a JSON representation of the legend graphic to use for its own rendering requirements. A simple http request can be used: http://localhost:9000/geoserver/wms?service=WMS&version=1.1.0& ,→request=GetLegendGraphic&layer=topp:states&format=application/json Which returns a JSON response: {"Legend": [{ "layerName": "states", "title": "USA Population", "rules": [ { "title": "< 2M", "filter": "[PERSONS < '2000000']", "symbolizers": [{"Polygon": { "fill": "#4DFF4D", "fill-opacity": "0.7" }}] }, { "title": "2M - 4M", "filter": "[PERSONS BETWEEN '2000000' AND '4000000']", "symbolizers": [{"Polygon": { "fill": "#FF4D4D", "fill-opacity": "0.7" }}] 7.1. Web Map Service (WMS) 1105 GeoServer User Manual, Release 2.15.1 }, { "title": "> 4M", "filter": "[PERSONS > '4000000']", "symbolizers": [{"Polygon": { "fill": "#4D4DFF", "fill-opacity": "0.7" }}] }, { "title": "Boundary", "symbolizers": [ {"Line": { "stroke": "#000000", "stroke-width": "0.2", "stroke-opacity": "1", "stroke-linecap": "butt", "stroke-linejoin": "miter" }}, {"Text": { "label": "[STATE_ABBR]", "fonts": [ { "font-family": ["Times New Roman"], "font-style": "Normal", "font-weight": "normal", "font-size": "14" }], "label-placement": { "x-anchor": "0.5", "y-anchor": "0.5", "rotation": "0.0" } }} ] } ] }]} This JSON contains an array of Legends (one for each layer requested) and each legend contains some metadata about the legend and an array of rule objects for each rule with in the feature type of the style. Each rule contains the metadata associated with the rule, any filter element and an array of symbolizer objects. Filters and Expressions Filters are encoded using ECQL, a rule with an ElseFilter has an element “ElseFilter” set to the value “true”. Expressions are also encoded in ECQL (wrapped in []) when encountered in the style. Symbolizers • PointSymbolizer A point symbolizer will be represented as a series of elements containing metadata and an array of graphics symbols (see here) , these can be well known marks or external graphics. The point 1106 Chapter 7. Services GeoServer User Manual, Release 2.15.1 symbolizer also provides an “url” element which allows a client to make a request back to GeoServer to fetch a png image of the point symbol. {"Point": { "title": "title", "abstract": "abstract", "url": "http://localhost:9000/geoserver/kml/icon/capitals?0.0.0=", "size": "6", "opacity": "1.0", "rotation": "0.0", "graphics": [ { "mark": "circle", "fill": "#FFFFFF", "fill-opacity": "1.0", "stroke": "#000000", "stroke-width": "2", "stroke-opacity": "1", "stroke-linecap": "butt", "stroke-linejoin": "miter" }]}} • LineSymbolizer A line symbolizer is represented as a list of metadata elements and the stroke parameters, it is possible for there to be a graphic-stroke element too. {"Line": { "stroke": "#AA3333", "stroke-width": "2", "stroke-opacity": "1", "stroke-linecap": "butt", "stroke-linejoin": "miter" }} {"Line": { "graphic-stroke": { "url": "http://local-test:8080/geoserver/kml/icon/Default Styler", "size": "6", "opacity": "0.4", "rotation": "[(rotation*-1)]", "graphics": [ { "mark": "square", "fill": "#FFFF00", "fill-opacity": "1.0" }] }, "stroke-opacity": "1", "stroke-linecap": "butt", "stroke-linejoin": "miter", "perpendicular-offset": "10" }} • PolygonSymbolizer A polygon symbolizer contains stroke parameters and fill parameters. {"Polygon": { "stroke": "#000000", 7.1. Web Map Service (WMS) 1107 GeoServer User Manual, Release 2.15.1 "stroke-width": "0.5", "stroke-opacity": "1", "stroke-linecap": "butt", "stroke-linejoin": "miter", "fill": "#0099CC", "fill-opacity": "1.0" }} Or a graphic stroke and/or a graphic fill (as described above). {"Polygon": { "graphic-stroke": { "url": "http://local-test:8080/geoserver/kml/icon/Default Styler", "size": "6", "opacity": "0.4", "rotation": "[(rotation*-1)]", "graphics": [ { "mark": "square", "fill": "#FFFF00", "fill-opacity": "1.0" }] }, "stroke-opacity": "1", "stroke-linecap": "butt", "stroke-linejoin": "miter", "graphic-fill": { "url": "http://local-test:8080/geoserver/kml/icon/Default Styler", "size": "4", "opacity": "0.4", "rotation": "[(rotation*-1)]", "graphics": [ { "mark": "circle", "fill": "#FFFFFF", "fill-opacity": "1.0" }] }}} • RasterSymbolizer Raster symbolizers contain a colormap with an array of entries, each entry contains a label, quantity and color element. {"Raster": { "colormap": { "entries": [ { "label": "values", "quantity": "0", "color": "#AAFFAA" }, { "quantity": "1000", "color": "#00FF00" }, { "label": "values", "quantity": "1200", "color": "#FFFF00" 1108 Chapter 7. Services GeoServer User Manual, Release 2.15.1 }, { "label": "values", "quantity": "1400", "color": "#FF7F00" }, { "label": "values", "quantity": "1600", "color": "#BF7F3F" }, { "label": "values", "quantity": "2000", "color": "#000000" } ], "type": "ramp" }, "opacity": "1.0" }} • TextSymbolizer A text symbolizer contains a label expression, followed by an array of fonts and a label-placement object containing details of how the label is placed. {"Text": { "label": "[STATE_ABBR]", "fonts": [ { "font-family": ["Times New Roman"], "font-style": "Normal", "font-weight": "normal", "font-size": "14" }], "label-placement": { "x-anchor": "0.5", "y-anchor": "0.5", "rotation": "0.0" } }} Vendor Options In any case where one or more vendor options is included in the symbolizer there will be a vendor-options element included in the output. This object will include one line for each vendor option. "vendor-options": { "labelAllGroup": "true", "spaceAround": "10", "followLine": "true", "autoWrap": "50" } 7.1. Web Map Service (WMS) 1109 GeoServer User Manual, Release 2.15.1 7.1.11 WMS Decorations WMS Decorations provide a framework for visually annotating images from WMS with absolute, rather than spatial, positioning. Examples of decorations include compasses, legends, and watermarks. Configuration To use decorations in a GetMap request, the administrator must first configure a decoration layout. These layouts are stored in a subdirectory called layouts in the GeoServer data directory as XML files, one file per layout. Each layout file must have the extension .xml. Once a layout foo.xml is defined, users can request it by adding &format_options=layout:foo to the request parameters. Layout files follow a very simple XML structure; a root node named layout containing any number of decoration elements. The order of the decoration elements is the order they are drawn so, in case they are overlapping, the first one will appear under the others. Each decoration element has several attributes: Attribute type affinity offset size Meaning the type of decoration to use (see Decoration Types) the region of the map image to which the decoration is anchored how far from the anchor point the decoration is drawn the maximum size to render the decoration. Note that some decorations may dynamically resize themselves. Each decoration element may also contain an arbitrary number of option elements providing a parameter name and value: