Leaflet.VectorGrid API reference

VectorGrid.Slicer

A VectorGrid for slicing up big GeoJSON or TopoJSON documents in vector tiles, leveraging geojson-vt.

Usage example

var geoJsonDocument = {
    type: 'FeatureCollection',
    features: [ ... ]
};
L.vectorGrid.slicer(geoJsonDocument, {
    vectorTileLayerStyles: {
        sliced: { ... }
    }
}).addTo(map);

VectorGrid.Slicer can also handle TopoJSON transparently:

var layer = L.vectorGrid.slicer(topojson, options);

The TopoJSON format implicitly groups features into "objects". These will be transformed into vector tile layer names when styling (the vectorTileLayerName option is ignored when using TopoJSON).

Options

Additionally to these options, VectorGrid.Slicer can take in any of the geojson-vt options.
Option Type Default Description
vectorTileLayerName String 'sliced' Vector tiles contain a set of data layers, and those data layers contain features. Thus, the slicer creates one data layer, with the name given in this option. This is important for symbolizing the data.

VectorGrid

A VectorGrid is a generic, abstract class for displaying tiled vector data. it provides facilities for symbolizing and rendering the data in the vector tiles, but lacks the functionality to fetch the vector tiles from wherever they are. Extends Leaflet's L.GridLayer.

Options

Option Type Default Description
rendererFactory L.svg.tile A factory method which will be used to instantiate the per-tile renderers.
vectorTileLayerStyles Object {} A data structure holding initial symbolizer definitions for the vector features.
interactive Boolean false Whether this VectorGrid fires Interactive Layer events.
getFeatureId Function undefined A function that, given a vector feature, returns an unique identifier for it, e.g. function(feat) { return feat.properties.uniqueIdField; }. Must be defined for setFeatureStyle to work.

Methods

Method Returns Description
setFeatureStyle(<Number> id, <L.Path Options> layerStyle) this

Given the unique ID for a vector features (as per the getFeatureId option), re-symbolizes that feature across all tiles it appears in. Reverts the effects of a previous setFeatureStyle call.

getDataLayerNames() Array

Returns an array of strings, with all the known names of data layers in the vector tiles displayed. Useful for introspection.

Extension methods

Classes inheriting from VectorGrid must define the _getVectorTilePromise private method.
Method Returns Description
getVectorTilePromise(<Object> coords) Promise

Given a coords object in the form of {x: Number, y: Number, z: Number}, this function must return a Promise for a vector tile.

FillSymbolizer

A symbolizer for filled areas. Applies only to polygon features.

VectorGrid.Protobuf

A VectorGrid for vector tiles fetched from the internet. Tiles are supposed to be protobufs (AKA "protobuffer" or "Protocol Buffers"), containing data which complies with the MapBox Vector Tile Specification. This is the format used by:

Usage example

You must initialize a VectorGrid.Protobuf with a URL template, just like in L.TileLayers. The difference is that the template must point to vector tiles (usually .pbf or .mvt) instead of raster (.png or .jpg) tiles, and that you should define the styling for all the features.

For OpenMapTiles, with a key from https://openmaptiles.org/docs/host/use-cdn/, initialization looks like this:

L.vectorGrid.protobuf("https://free-{s}.tilehosting.com/data/v3/{z}/{x}/{y}.pbf.pict?key={key}", {
    vectorTileLayerStyles: { ... },
    subdomains: "0123",
    key: 'abcdefghi01234567890',
    maxNativeZoom: 14
}).addTo(map);

And for Mapbox vector tiles, it looks like this:

L.vectorGrid.protobuf("https://{s}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/{z}/{x}/{y}.vector.pbf?access_token={token}", {
    vectorTileLayerStyles: { ... },
    subdomains: "abcd",
    token: "pk.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRTS.TUVWXTZ0123456789abcde"
}).addTo(map);

Creation

Factory Description
L.vectorGrid.protobuf(<String> url, options) Instantiates a new protobuf VectorGrid with the given URL template and options

Options

As with L.TileLayer, the URL template might contain a reference to any option (see the example above and note the {key} or token in the URL template, and the corresponding option).
Option Type Default Description
subdomains String 'abc' Akin to the subdomains option for L.TileLayer.

LineSymbolizer

A symbolizer for lines. Can be applied to line and polygon features.

PointSymbolizer

A symbolizer for points.

Symbolizer

The abstract Symbolizer class is mostly equivalent in concept to a L.Path - it's an interface for polylines, polygons and circles. But instead of representing leaflet Layers, it represents things that have to be drawn inside a vector tile.

Methods

Method Returns Description
initialize(<GeoJSON> feature, <Number> pxPerExtent)

Initializes a new Line Symbolizer given a GeoJSON feature and the pixel-to-coordinate-units ratio. Internal use only.

render(renderer, style)

Renders this symbolizer in the given tiled renderer, with the given L.Path options. Internal use only. Updates the L.Path options used to style this symbolizer, and re-renders it. Internal use only.

Styling VectorGrids

Vector tiles have a concept of "layer" different from the Leaflet concept of "layer".
In Leaflet, a "layer" is something that can be atomically added or removed from the map. In vector tiles, a "layer" is a named set of features (points, lines or polygons) which share a common theme.
A vector tile layer¹ can have several layers². In the mapbox-streets-v6 vector tiles layer¹ above, there are named layers² like admin, water or roads.
(¹ In Leaflet)
(² Groups of themed features)
Styling is done via per-layer² sets of L.Path options in the vectorTileLayerStyles layer¹ option:

var vectorTileOptions = {
    vectorTileLayerStyles: {
        // A plain set of L.Path options.
        landuse: {
            weight: 0,
            fillColor: '#9bc2c4',
            fillOpacity: 1,
            fill: true
        },
        // A function for styling features dynamically, depending on their
        // properties and the map's zoom level
        admin: function(properties, zoom) {
            var level = properties.admin_level;
            var weight = 1;
            if (level == 2) {weight = 4;}
            return {
                weight: weight,
                color: '#cf52d3',
                dashArray: '2, 6',
                fillOpacity: 0
            }
        },
        // A function for styling features dynamically, depending on their
        // properties, the map's zoom level, and the layer's geometry
        // dimension (point, line, polygon)
        water: function(properties, zoom, geometryDimension) {
	    if (geometryDimension === 1) {   // point
	        return ({
                    radius: 5,
                    color: '#cf52d3',
                });
	    }
	    
	    if (geometryDimension === 2) {   // line
                 return ({
                    weight: 1,
                    color: '#cf52d3',
                    dashArray: '2, 6',
                    fillOpacity: 0
                });
	    }
	    
	    if (geometryDimension === 3) {   // polygon
	         return ({
                    weight: 1,
                    fillColor: '#9bc2c4',
                    fillOpacity: 1,
                    fill: true
                });
	    }
        },
        // An 'icon' option means that a L.Icon will be used
        place: {
            icon: new L.Icon.Default()
        },
        road: []
    }
};
var pbfLayer = L.vectorGrid.protobuf(url, vectorTileOptions).addTo(map);

A layer² style can be either:

Updating Styles

In some cases it can be desirable to change the style of a feature on screen, for example for highlighting when a feature is clicked.
To do this, VectorGrid needs to know how to identify a feature. This is done through the getFeatureId option, which should be set to a function that returns an id given a feature as argument. For example:

var vectorGrid = L.vectorGrid.slicer(url, {
    ...
    getFeatureId: function(f) {
        return f.properties.osm_id;
    }
}

Note that features with the same id will be treated as one when changing style, this happens normally when for example a polygon spans more than one tile.
To update the style of a feature, use setFeatureStyle:

vectorGrid.setFeatureStyle(id, style);

The styling follows the same rules as described above, it accepts a single style, an array, or a function that returns styling.
To revert the style to the layer's default, use the resetFeatureStyle method:

vectorGrid.resetFeatureStyle(id);

Interactivity

You can enable interacting (click, mouseover, etc.) with layer features if you pass the option interactive: true; you can then add listeners to the VectorGrid layer. When an event fires, it will include the layer property, containing information about the feature.

SVG vs canvas

Leaflet.VectorGrid is able to render vector tiles with both SVG and <canvas>, in the same way that vanilla Leaflet can use SVG and <canvas> to draw lines and polygons.
To switch between the two, use the rendererFactory option for any L.VectorGrid layer, e.g.:

var sliced = L.vectorGrid.slicer(geojson, {
    rendererFactory: L.svg.tile,
    attribution: 'Something',
    vectorTileLayerStyles: { ... }
});
var pbf = L.vectorGrid.protobuf(url, {
    rendererFactory: L.canvas.tile,
    attribution: 'Something',
    vectorTileLayerStyles: { ... }
});

Internally, Leaflet.VectorGrid uses two classes named L.SVG.Tile and L.Canvas.Tile, with factory methods L.svg.tile and L.canvas.tile - a L.VectorGrid needs to be passed one of those factory methods.