gridviz

Gridviz API reference

Table of contents

Anything unclear or missing? Feel free to ask !

Concepts

Here are few concepts on Gridviz to be aware of:

  1. A gridviz map is composed of a stack of layers. Layers may have different types (background image, boundaries, labels, etc.). The main layer type is GridLayer, for gridded data. Background layers are usually drawn below, usually a single one. Boundaries and label layers should also be drawn as foreground, on top of grid layers.

  2. Gridded datasets are defined independantly from their grid layer. Each gridded dataset may thus be reused by several layers: It is loaded and stored once, and reused several times. This reuse allows saving memory space and loading time.

  3. A gridded dataset may be multi-resolution. Gridviz then takes care of selecting the most suitable resolution according to the visualisation zoom level (and a predefined minPixelsPerCell parameter). This ensures only the relevant data for the visualisation view and zoom level is loaded and displayed.

  4. GridViz supports data tiling, and also Parquet format.

  5. A grid layer draws a single gridded dataset using one or several styles. It is thus possible to combine styles and draw them on top of each other to show different aspects of the data.

  6. A style specifies how to draw the cells within the view. The style is not defined at cell level only - it allows defining more advanced styling techniques using cell sets, based on the relations of each cell with its neigbours.

  7. Gridviz comes with a library of predefined styles. These styles are customisable. Users are also offered a full flexibility to define their own style and show their cells the way they need. Predefined style may be seen only as examples and inspiration sources.

  8. Predefined styles parameters are usually not static values, but functions of usually four parameters: The cell to be drawn, its resolution, the zoom level, and a viewscale object. Styling parameters (such as colors, size, etc.) may thus be computed depending on each cell, its resolution, and the zoom level. Size parameters are usually specified in the unit of measurement of the grid coordinate reference system, usually ground meters. They may also be specified in screen pixels. These functions allow adapting the cartographic styles (colors, dimensions, etc.) to the cell values, their size and the zoom level.

  9. For some predefined style parameters, viewscale parameter allows defining styling parameters based on the cells within the map view only. This parameter is an object computed only once from the cells within the view. It may be used for example to compute the minimum and maximum values of these cells and adapt a color scale to this for a better contrast. It should generally be used to compute scales that are view dependant - hence the name viewscale. See this section for some examples.

  10. Gridviz zoom level, usually noted z, is defined in ground UoM per pixel. The ground UoM is usually meter. z value can be used directly to transorm distances from ground distance to map screen distance, in pixels, as a division. resolution parameter is the cell size, in ground UoM. Its size in map screen pixel is thus ā€˜resolution / zā€™.

  11. A grid layer shows gridded data in the grid coordinate reference system. Several gridded datasets may be overlayed, as soon as they are defined in the same coordinate reference system. Other layers (background, labels, etc.) must be defined also in the grid coordinate reference system.

Defining the map

When building a gridviz map, in addition to the container element you can also specify an options object with the properties outlined in the table below.

For example:

new gridviz.Map(document.getElementById('map'), {
    x: 4500000,
    y: 2900000,
    z: 1000,
    legendContainer: document.getElementById('myLegendDiv'), // if you want your legend in an external container
    selectionRectangleColor: 'red', // cell hover
    selectionRectangleWidthPix: (resolution, z) => '1',
    backgroundColor: 'white',
    tooltip: {
        fontSize: '1.2em',
        transitionDuration: 100,
        maxWidth: '20em'
        fontSize:'1.2em'
        background :  'white'
        padding: '5px'
        border :'0px'
        'border-radius' : '0px'
        'box-shadow' : '5px 5px 5px grey'
        'font-family' :'Helvetica, Arial, sans-serif'
        transitionDuration : 100
        xOffset:  30
        yOffset:  20
        yMouseOffset : 0
        xMouseOffset : 0
        parentElement : document.body
    },
    onZoomStartFun: (event) => {
        console.log('pan/zoom start', event)
    },
    onZoomFun: (event) => {
        console.log('zoom', event)
    },
    onZoomEndFun: (event) => {
        console.log('pan/zoom end', event)
    },
})
Property Type Default Description
opts.legendDivId string ā€˜gvizLegendā€™ The identifier of the element upon which the legend will be appended.
opts.selectionRectangleColor string ā€˜redā€™ The colour of the outline when a cell is highlighted.
opts.selectionRectangleWidthPix Function (r,z) => 4 A function specifying the thickness in pixels of the outline when a cell is highlighted. The function parameter r is the cell resolution. z is the zoom level.
opts.transparentbackground boolean false Whether the background should be filled with colour (backgroundColor) or not. It is essentially the difference between using context.fillRect vs context.clearRect.
opts.backgroundColor string ā€˜whiteā€™ The background color of the canvas when transparentBackground is set to false.
opts.disableZoom Boolean false Disables d3 pan and zoom when set to true.
opts.onZoomStartFun Function null Event handler for when a pan/zoom event is initiated.
opts.onZoomFun Function null Event handler for when a pan/zoom event is occurring.
opts.onZoomEndFun Function null Event handler for when a pan/zoom event has finished.
opts.tooltip Object undefined See tooltip

Adding data

A gridviz dataset defines how to retrieve gridded data, as a list of grid cells. A grid cell is stored as a javascript object having a x and y property, which is usually the coordinates of the grid cell lower left corner in the grid coordinate reference system. The x and y values are usually multiples of the grid resolution value.

Gridviz proposed several types of datasets: Javascript, CSV, Parquet.

These datasets may be bundled into multi-resolution datasets, to be used for multi-scale maps:

Gridviz can also show tiled data. This ensures only the data within the viewshed are loaded and displayed. These tiled data should follow the tiled grid format.

For Parquet data support, see the gridviz-parquet extension.

For better efficiency, it is recommended to use multi-resolution tiled parquet data.

Layers

There are a few different types of layers that can be added to a gridviz map: Once you have constructed them, simply add them to the map like so:

map.layers = [yourLayer] // they will be drawn in order

GridLayer

new gridviz.GridLayer(dataset, [style], {
    minPixelsPerCell: 12, //optional
})

BackgroundLayer

const backgroundLayer = new gridviz.BackgroundLayer({
    url: 'https://raw.githubusercontent.com/jgaffuri/mbxyz/main/pub/elevation_shading/',
    resolutions: Array.from({ length: 9 }, (_, i) => 28.00132289714475 * Math.pow(2, 10 - i)),
    origin: [0, 6000000],
    filterColor: (z) => '#ffffff77',
})

BackgroundLayerImage

const backgroundLayer = new gridviz.BackgroundLayerImage({
    //the image URL
    url: 'https://raw.githubusercontent.com/jgaffuri/mbxyz/main/pub/img/reunion_relief_100k.png',

    //the georeferencing information:
    // - geo coordinates of the top left corner
    // - the image width and heigth in geo unit (meters). It is the image width/heigth in pixel multiplied by the resolution (meters/pixel)
    xMin: 314686,
    yMax: 7691260,
    width: 64590.2,
    height: 57178.2,
})

BackgroundLayerWMS

const backgroundLayer = new gridviz.BackgroundLayerWMS({
    url: 'yourWMSserver?&service=WMS&request=GetMap&layers=yourLayers&styles=&format=image%2Fjpeg',
})

GeoJSONLayer

const pointLayer = new gridviz.GeoJSONLayer({
    url: 'https://raw.githubusercontent.com/eurostat/Nuts2json/master/pub/v2/2024/3035/nutspt_3.json',
    shape: (f, z) => (f.properties.id.includes('DE') ? 'square' : 'circle'),
    size: (f, z) => Math.max(2, 10000 / z),
    strokeStyle: (f, z) => 'black',
    fillStyle: (f, z) => 'red',
    lineWidth: (f, z) => (z < 2000 ? 2 : 0),
})

LabelLayer

const labelLayer = new gridviz.LabelLayer({
    url: 'https://raw.githubusercontent.com/eurostat/euronym/main/pub/v3/UTF_LATIN/50/EUR.csv', //The URL of the label data, as CSV file.
    preprocess: (label) => {
        //project from geo coordinates to ETRS89-LAEA
        const p = proj([label.lon, label.lat])
        label.x = p[0]
        label.y = p[1]
        delete label.lon
        delete label.lat
    },
    style: (label, zoom) => {
        if (label.rs < 0.9 * zoom) return
        if (label.r1 < 0.9 * zoom) return '1em Arial'
        return '1.5em Arial'
    },
    haloColor: () => 'white',
})

Filtering and formatting data

The gridded data may be pre-processed after loading, and filtered:

Basic styles

Shape/Color/Size Style

shape color size style shape color size style shape color size style shape color size style

This style is a generic style which allows to define the shape, color and size of each grid cell, independantly according to 3 different variables. Three shapes are currently available: square, circle, triangle (up, down, left or right) and donut (a disk with a hole of changing size). To show grid cells as small squares with only changing color, one of the styles based on web GL here or here should rather be used, for efficiency reasons.

Square color WebGL Style

square color webgl style square color webgl style

This style displays each cell as a square, with a changing color. This style uses webGL and should thus be used to display grid cells at detailed resolutions.

Square color category WebGL style

square color webgl category style

This style displays each cell as a square, with a changing color based on a categorical variable. This style uses webGL and should thus be used to display grid cells at detailed resolutions.

Composition style

composition style composition style composition style composition style composition style

This style shows a composition at cell level in various different ways: Flags, pie charts, rings, segments, radar, age pyramid and halftone.

Segment style

segment style segment style

This style displays each cell as a segment with a changeable color, length, width and orientation.

Stroke style

stroke style stroke style

This style shows the stroke of each cell with different colors, widths, shapes and sizes. This style can be used in addition to others to show the cell strokes on top of those other styles.

Advanced styles

Dot density style

dot density style dot density style

This style displays each cell as randomly located points, with changeable density and color.

Pillars style

pillars style pillars style

This style shows the grid cells as 3D pillars or, with changeable height, width and color.

Ternary style

ternary map style

Ternary maps use color to show a composition according to three categories. Three different color hue are defined, that correspond to each of the three categories. The cells color is then selected according to the relative importance of the three categories. When two of the three categories are more important that the third, a color mix is used. A central class may be defined to show cases where the three categories are relativelly well balanced.

Note that this style is not really a new style - it relies on a specific classifier.

Text style

text style text style

This style shows the grid cells as text labels. The text, its color and font size can be set according to some cell values.

Image style

image style chernoff faces image style

This style shows the grid cells as an image. The image and its size can be set according to some cell values.

Time series style

time series style

This style shows the grid cells as a time series chart. It is particulary suitable to show data that has high temporal granularity and low geographical granurality (variation across time rather than space). The time series charts can be colored and sized according to other variables.

Side styles

The side styles are special:They do not display the cells, but their sides. They can be used to show discontinuities between cell values with, for example, some shadow effect.

Side style

side style

This style displays the sides of the cells as segments with different colors and widths, depending on the values of the 2 adjacent cells.

Side category style

side category style

This style displays the sides of the cells as segments with different colors depending on the categories of the 2 adjacent cells.

Contour style

contour style

This style is experimental / under development. It displays the sides of the cells depending on discontinuities between the 2 adjacent cells, like contour lines.

Isometric fence style

Isometric fence style

This style shows the composition of a total quantity into categories as vertical cross-sections oriented toward North-South and East-West. It is an alternative to composition style. It may also be seen as a bi-directional joyplot style showing categories - note that when angle value is set to 90Ā°, the style is equivalent to a joyplot. This style was inspired by the USGS geologic isometric fence diagrams (1953).

Esthetic styles

JoyPlot Style

joyplot style joyplot style joyplot style

This style shows cell rows in the form of a ā€˜joyplotā€™ - named after Joy Divisionā€™s ā€œUnknown Pleasuresā€ album cover. For joyplot style showing composition by categories, or for various orientations and perspective angles, see isometric fence style.

Mosaic style

mosaic style mosaic style

This style shows the cell as pseudo-irregular square shapes giving a mosaic effect. The cells are colored depending on a variable.

Ninja star style

Ninja star style Ninja star style

This style shows the cell as a star polygon whose compacity depends on a variable. The higher the value, the more compact the star: Maximum values correspond to a square, and minimum values correspond to a thin star. The shapes in between correspond to 4 branches stars looking like a ninja star.

Tanaka style

tanaka style

This style shows the grid cells in a Tanaka style, that is with discrete colors and a shadow effect.

Lego style

lego style

This style shows the grid cells as lego bricks with changeable colors and height based on a quantitative variable.

Lego category style

lego style

This style shows the grid cells as lego bricks with changeable colors based on a categorical variable.

Kernel smoothing

kernel smoothing

This style allows applying a gaussian kernel smoothing to the input grid. Other styles can then be used on the smoothed grid - this style is thus more a ā€˜filterā€™ than a proper style.

Note that this style is available within the gridviz-smoothing extension which need to be added as: <script src="https://cdn.jsdelivr.net/npm/gridviz-smoothing"></script>.

The kernel smoothing computation relies on the fast-kde library, which produces smoothing approximation very fast. Note that the approximation degrades significantly for weak smoothing (for low sigma values).

Custom styles

The style can be freely defined through the drawFun, which specifies how to draw the list of cells within the view on the map canvas.

Background layer

Background image layers may be defined:

Foreground information

Foreground layers may be defined such as:

Transparency

To handle layer and style transparency, blending modes and alpha values may be defined at layer or style level. These values may be set according to the zoom level.

Tooltip

A tooltip may be customised for the grid cells passed over the mouse pointer. By default, the list of properties is shown.

Buttons

To show zoom and full screen mode buttons, see this example (code).

View scale

For some predefined style parameters, viewscale parameter allows defining styling parameters based on the cells within the map view only. This parameter is an object computed only once from the cells within the view. It may be used for example to compute the minimum and maximum values of these cells and adapt a color scale to this for a better contrast. It should generally be used to compute scales that are view dependant - hence the name viewscale.

Stretching

Most of Gridviz styles rely on a continuous mapping from a statistical variable to a visual variable (color, size, etc.). The statistical distribution can be stretched with one of the stretching functions listed below can be used. These are continuous bijective functions defined from [0,1] to [0,1] intervals. They have different properties and should be chosen according to the data distribution. The amplitude of the stretching can be adjusted with a parameter.

Stretching function Description Stretching parameter
powerScale Polynomial function Power exponent, from 0 to Infinity. No change: 1
powerInverseScale Polynomial inverse function Power exponent, from 0 to Infinity. No change: 1
logarithmicScale Exponential function Logarithmic base, from -Infinity to Infinity. No change: 0
exponentialScale Exponential Logarithmic base, from -Infinity to Infinity. No change: 0
circularScale Circular 0: no stretching. 1: perfect circle section
circularInverseScale Circular 0: no stretching. 1: perfect circle section

For more information on these functions and an overview of how they differ, see:

Legends

Gridviz offers several types of legends that are suited to different cartographic styles.

The legend elements are added within a default HTML element. To define where the legend elements should be added, see this example (code).

Each legend can be customised using the ā€˜D3-likeā€™ style() function after constructing the legend, like so:

new gridviz.SizeLegend({
    title: 'Number of inhabitants',
    exaggerationFactor: 0.8,
    shape: 'circle',
    fillColor: '#3E5791',
}).style('padding', '0px 5px')

Color legend

Color discrete legend

Color category legend

Orientation legend

Size legend

Width legend

Ternary color legend

Leaflet

Gridviz can be used with leaflet by using the leaflet-gridviz plugin

Limit panning and zooming

See this example (code) to limit the panning and zooming to some limit values, in order to prevent the user to move toward undesired positions and zoom levels. Note that the panning limit applies to the map center, not the map borders. The panning limit is specified as an array [xMin, yMin, xMax, yMax].

Mixed resolution grids

mixed resolution grid

A mixed-resolution grid is a grid which contains cells with different sizes.

Note that most pre-defined styles of GridViz may not apply for mixed-resolution grids. Custom styles can be defined.

Alright?

Anything unclear or missing? Feel free to ask !