Basic usage

Applying an SLD to a layer as a style function

  /**
   * @param {object} vector layer
   * @param {string} text the xml text
   * apply sld
   */
  function applySLD(vectorLayer, text) {
    const sldObject = SLDReader.Reader(text);    
    const sldLayer = SLDReader.getLayer(sldObject);
    const style = SLDReader.getStyle(sldLayer, 'bestuurlijkegrenzen:provincies');
    const featureTypeStyle = style.featuretypestyles[0];

    const viewProjection = map.getView().getProjection();
    vectorLayer.setStyle(SLDReader.createOlStyleFunction(featureTypeStyle, {
      // Use the convertResolution option to calculate a more accurate resolution.
      convertResolution: viewResolution => {
        const viewCenter = map.getView().getCenter();
        return ol.proj.getPointResolution(viewProjection, viewResolution, viewCenter);
      },
      // If you use point icons with an ExternalGraphic, you have to use imageLoadCallback
      // to update the vector layer when an image finishes loading.
      // If you do not do this, the image will only be visible after next layer pan/zoom.
      imageLoadedCallback: () => {
        vectorLayer.changed();
      },
    }));
  }

  const vectorSource = new ol.source.Vector({
    format: new ol.format.GeoJSON(),
    url: 'assets/provincies.json',
    strategy: ol.loadingstrategy.bbox,
  });

  const vectorLayer = new ol.layer.Vector({
    source: vectorSource,
    style: new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: 'rgba(0, 0, 255, 1.0)',
        width: 2,
      }),
    }),
  });

  applySLD(vectorLayer, mySLDString);

Extracting static OpenLayers styles for a specific geometry type from an SLD rule

const sldObject = SLDReader.Reader(sldXml);
const sldLayer = SLDReader.getLayer(sldObject);
const style = SLDReader.getStyle(sldLayer);
const featureTypeStyle = style.featuretypestyles[0];

// There can be more than one symbolizer of a given type inside a style rule,
// therefore getOlStyle always returns an array of OpenLayers style instances.
// Valid geometry types are 'Point', 'LineString', and 'Polygon'.
const lineStyles = SLDReader.createOlStyle(featureTypeStyle.rules[0], 'LineString');

vectorLayer.setStyle(lineStyles);

Modules

Reader/filter

Factory methods for filterelements

Reader/index

Functions

categorizeSymbolizers(rules)CategorizedSymbolizers

Get styling from rules per geometry type

registerFunction(functionName, implementation)

Register a function implementation by name. When evaluating the function, it will be called with the values of the parameter elements evaluated for a single feature. If the function returns null, the fallback value given in the SLD function element will be used instead.

Note: take care of these possible gotcha's in the function implementation.

  • The function will be called with the number of parameters given in the SLD function element. This number can be different from the expected number of arguments.
  • Try to avoid throwing errors from the function implementation and return null if possible.
  • Literal values will always be provided as strings. Convert numeric parameters to numbers yourself.
  • Geometry valued parameters will be provided as OpenLayers geometry instances. Do not mutate these!
getFunction(functionName)function

Get a function implementation by name.

clearFunctionCache()

Clear the function cache.

createOlStyleFunction(featureTypeStyle, options)function

Create an OpenLayers style function from a FeatureTypeStyle object extracted from an SLD document.

Important! When using externalGraphics for point styling, make sure to call .changed() on the layer inside options.imageLoadedCallback to immediately see the loaded image. If you do not do this, the image icon will only become visible the next time OpenLayers draws the layer (after pan or zoom).

createOlStyle(styleRule, geometryType)Array.<ol.Style>

Create an array of OpenLayers style instances for features with the chosen geometry type from a style rule. Since this function creates a static OpenLayers style and not a style function, usage of this function is only suitable for simple symbolizers that do not depend on feature properties and do not contain external graphics. External graphic marks will be shown as a grey circle instead.

getLayerNames(sld)Array.<string>

get all layer names in sld

getLayer(sld, [layername])Layer

Get layer definition from sld

getStyleNames(layer)Array.<string>

getStyleNames, notice name is not required for userstyle, you might get undefined

getStyle(layer, [name])object

get style from array layer.styles, if name is undefined it returns default style. null is no style found

getRules(featureTypeStyle, feature, resolution)Array.<Rule>

get rules for specific feature after applying filters

getRuleSymbolizers(rule)Array.<object>

Get all symbolizers inside a given rule. Note: this will be a mix of Point/Line/Polygon/Text symbolizers.

Typedefs

CategorizedSymbolizers

contains for each geometry type the symbolizer from an array of rules

Expression

Modeled after SvgParameterType. Can be either a primitive value (string,integer,boolean), or an object with these properties:

Filter

filter operators, see also geoserver

StyledLayerDescriptor

a typedef for StyledLayerDescriptor xsd

Layer

a typedef for Layer, the actual style object for a single layer

FeatureTypeStyle

a typedef for FeatureTypeStyle: xsd

Rule

a typedef for Rule to match a feature: xsd

PolygonSymbolizer

a typedef for PolygonSymbolizer, see also geoserver docs

LineSymbolizer

a typedef for LineSymbolizer, see also geoserver docs

PointSymbolizer

a typedef for PointSymbolizer xsd & geoserver docs

Reader/filter

Factory methods for filterelements

See: http://schemas.opengis.net/filter/1.0.0/filter.xsd

module.exports(element) ⇒ Filter

Factory root filter element

Kind: Exported function

Param Type
element Element

Reader/index

module.exports(sld) ⇒ StyledLayerDescriptor

Creates a object from an sld xml string,

Kind: Exported function
Returns: StyledLayerDescriptor - object representing sld style

Param Type Description
sld string xml string

categorizeSymbolizers(rules) ⇒ CategorizedSymbolizers

Get styling from rules per geometry type

Kind: global function

Param Type Description
rules Array.<Rule> [description]

registerFunction(functionName, implementation)

Register a function implementation by name. When evaluating the function, it will be called with the values of the parameter elements evaluated for a single feature. If the function returns null, the fallback value given in the SLD function element will be used instead.

Note: take care of these possible gotcha’s in the function implementation.

  • The function will be called with the number of parameters given in the SLD function element. This number can be different from the expected number of arguments.
  • Try to avoid throwing errors from the function implementation and return null if possible.
  • Literal values will always be provided as strings. Convert numeric parameters to numbers yourself.
  • Geometry valued parameters will be provided as OpenLayers geometry instances. Do not mutate these!

Kind: global function

Param Type Description
functionName string Function name.
implementation function The function implementation.

getFunction(functionName) ⇒ function

Get a function implementation by name.

Kind: global function
Returns: function - The function implementation, or null if no function with the given name has been registered yet.

Param Type Description
functionName string Function name.

clearFunctionCache()

Clear the function cache.

Kind: global function

createOlStyleFunction(featureTypeStyle, options) ⇒ function

Create an OpenLayers style function from a FeatureTypeStyle object extracted from an SLD document.

Important! When using externalGraphics for point styling, make sure to call .changed() on the layer inside options.imageLoadedCallback to immediately see the loaded image. If you do not do this, the image icon will only become visible the next time OpenLayers draws the layer (after pan or zoom).

Kind: global function
Returns: function - A function that can be set as style function on an OpenLayers vector style layer.

Param Type Description
featureTypeStyle FeatureTypeStyle Feature Type Style object.
options object Options
options.convertResolution function An optional function to convert the resolution in map units/pixel to resolution in meters/pixel. When not given, the map resolution is used as-is.
options.imageLoadedCallback function Optional callback that will be called with the url of an externalGraphic when an image has been loaded (successfully or not). Call .changed() inside the callback on the layer to see the loaded image.
options.getProperty function Optional custom property getter: (feature, propertyName) => property value.

Example

myOlVectorLayer.setStyle(SLDReader.createOlStyleFunction(featureTypeStyle, {
  imageLoadedCallback: () => { myOlVectorLayer.changed(); }
}));

createOlStyle(styleRule, geometryType) ⇒ Array.<ol.Style>

Create an array of OpenLayers style instances for features with the chosen geometry type from a style rule. Since this function creates a static OpenLayers style and not a style function, usage of this function is only suitable for simple symbolizers that do not depend on feature properties and do not contain external graphics. External graphic marks will be shown as a grey circle instead.

Kind: global function
Returns: Array.<ol.Style> - An array of OpenLayers style instances.

Param Type Description
styleRule StyleRule Feature Type Style Rule object.
geometryType string One of ‘Point’, ‘LineString’ or ‘Polygon’

Example

myOlVectorLayer.setStyle(SLDReader.createOlStyle(featureTypeStyle.rules[0], 'Point');

getLayerNames(sld) ⇒ Array.<string>

get all layer names in sld

Kind: global function
Returns: Array.<string> - registered layernames

Param Type
sld StyledLayerDescriptor

getLayer(sld, [layername]) ⇒ Layer

Get layer definition from sld

Kind: global function
Returns: Layer - [description]

Param Type Description
sld StyledLayerDescriptor [description]
[layername] string optional layername

getStyleNames(layer) ⇒ Array.<string>

getStyleNames, notice name is not required for userstyle, you might get undefined

Kind: global function
Returns: Array.<string> - [description]

Param Type Description
layer Layer [description]

getStyle(layer, [name]) ⇒ object

get style from array layer.styles, if name is undefined it returns default style. null is no style found

Kind: global function
Returns: object - the style from layer.styles matching the name

Param Type Description
layer Layer [description]
[name] string of style. If not given, the style marked as default will be returned. If there is no default style, the first one will be returned.

getRules(featureTypeStyle, feature, resolution) ⇒ Array.<Rule>

get rules for specific feature after applying filters

Kind: global function

Param Type Description
featureTypeStyle FeatureTypeStyle  
feature object geojson
resolution number m/px
options.getProperty function An optional function with parameters (feature, propertyName) that can be used to extract a property value from a feature. When not given, properties are read from feature.properties directly.Error
options.getFeatureId function An optional function to extract the feature id from a feature.Error When not given, feature id is read from feature.id.

Example

const style = getStyle(sldLayer, stylename);
getRules(style.featuretypestyles['0'], geojson, resolution);

getRuleSymbolizers(rule) ⇒ Array.<object>

Get all symbolizers inside a given rule. Note: this will be a mix of Point/Line/Polygon/Text symbolizers.

Kind: global function
Returns: Array.<object> - Array of all symbolizers in a rule.

Param Type Description
rule object SLD rule object.

CategorizedSymbolizers

contains for each geometry type the symbolizer from an array of rules

Kind: global typedef
Properties

Name Type Description
polygonSymbolizers Array.<PolygonSymbolizer> polygonsymbolizers
lineSymbolizers Array.<LineSymbolizer> linesymbolizers
pointSymbolizers Array.<PointSymbolizer> pointsymbolizers, same as graphic prop from PointSymbolizer
textSymbolizers Array.<TextSymbolizer> textsymbolizers

Expression

Modeled after SvgParameterType. Can be either a primitive value (string,integer,boolean), or an object with these properties:

Kind: global typedef
Properties

Name Type Description
type string One of ‘literal’, ‘propertyname’, or ‘function’.
[typeHint] string Optional type hint, used when evaluating the expression. Defaults to ‘string’. Can be ‘number’.
[value] any The primitive type representing the value of a literal expresion, or a string representing the name of a propertyname expression .
[name] string Required for function expressions. Contains the function name.
[fallbackValue] any Optional fallback value when function evaluation returns null.
[params] Array.<Expression> Required array of function parameters for function expressions.

Filter

filter operators, see also geoserver

Kind: global typedef
Properties

Name Type Description
type string Can be ‘comparison’, ‘and’, ‘or’, ‘not’, or ‘featureid’.
[fids] Array.<string> An array of feature id’s. Required for type=’featureid’.
[operator] string Required for type=’comparison’. Can be one of ‘propertyisequalto’, ‘propertyisnotequalto’, ‘propertyislessthan’, ‘propertyislessthanorequalto’, ‘propertyisgreaterthan’, ‘propertyisgreaterthanorequalto’, ‘propertyislike’, ‘propertyisbetween’ ‘propertyisnull’
[predicates] Array.<Filter> Required for type=’and’ or type=’or’. An array of filter predicates that must all evaluate to true for ‘and’, or for which at least one must evaluate to true for ‘or’.
[predicate] Filter Required for type=’not’. A single predicate to negate.
[expression1] Expression First expression required for boolean comparison filters.
[expression2] Expression Second expression required for boolean comparison filters.
[expression] Expression Expression required for unary comparison filters.
[lowerboundary] Expression Lower boundary expression, required for operator=’propertyisbetween’.
[upperboundary] Expression Upper boundary expression, required for operator=’propertyisbetween’.
[wildcard] string Required wildcard character for operator=’propertyislike’.
[singlechar] string Required single char match character, required for operator=’propertyislike’.
[escapechar] string Required escape character for operator=’propertyislike’.

StyledLayerDescriptor

a typedef for StyledLayerDescriptor xsd

Kind: global typedef
Properties

Name Type Description
version string sld version
layers Array.<Layer> info extracted from NamedLayer element

Layer

a typedef for Layer, the actual style object for a single layer

Kind: global typedef
Properties

Name Type Description
name string layer name
styles Array.<Object> See explanation at Geoserver docs
styles[].default Boolean  
[styles[].name] String  
styles[].featuretypestyles Array.<FeatureTypeStyle> Geoserver will draw multiple, libraries as openlayers can only use one definition!

FeatureTypeStyle

a typedef for FeatureTypeStyle: xsd

Kind: global typedef
Properties

Name Type
rules Array.<Rule>

Rule

a typedef for Rule to match a feature: xsd

Kind: global typedef
Properties

Name Type Description
name string rule name
[filter] Filter Optional filter expression for the rule.
[elsefilter] boolean Set this to true when rule has no filter expression to catch everything not passing any other filter.
[minscaledenominator] integer  
[maxscaledenominator] integer  
[polygonsymbolizer] PolygonSymbolizer  
[linesymbolizer] LineSymbolizer  
[pointsymbolizer] PointSymbolizer  

PolygonSymbolizer

a typedef for PolygonSymbolizer, see also geoserver docs

Kind: global typedef
Properties

Name Type Description
fill Object  
fill.styling Object.<Expression> one object per SvgParameter with props name (camelCased)
stroke Object  
stroke.styling Object.<Expression> with camelcased name & value

LineSymbolizer

a typedef for LineSymbolizer, see also geoserver docs

Kind: global typedef
Properties

Name Type Description
stroke Object  
stroke.styling Object.<Expression> one object per SvgParameter with props name (camelCased)
graphicstroke Object  
graphicstroke.graphic Object  
graphicstroke.graphic.mark Object  
graphicstroke.graphic.mark.wellknownname string  
graphicstroke.graphic.mark.fill Object  
graphicstroke.graphic.mark.stroke Object  
graphicstroke.graphic.opacity Number  
graphicstroke.graphic.size Number  
graphicstroke.graphic.rotation Number  

PointSymbolizer

a typedef for PointSymbolizer xsd & geoserver docs

Kind: global typedef
Properties

Name Type
graphic Object
graphic.externalgraphic Object
graphic.externalgraphic.onlineresource string
graphic.mark Object
graphic.mark.wellknownname string
graphic.mark.fill Object
graphic.mark.stroke Object
graphic.opacity Number
graphic.size Expression
graphic.rotation Expression