Publishing GIS data on the web with Leaflet

When I was looking for a simple way to publish GIS data on the web, a colleague suggested Leaflet. This is an easy to use Javascript library that is ideal for publishing e.g. the content of shapefiles. Based on one of the examples, I’ve written a script that loads data stored in the GeoJSON format, and displays it using Leaflet.

You can create a GeoJSON file by exporting a dataset from QGIS in GeoJSON format. Make sure to use WGS84 geographic as coordinate system. My code uses the content of the color attribute of a feature to assign it a color. This means that you will have to add a string-type attribute column to your data in QGIS and fill it with the the desired color(s), in hex notation (#ff0000 for red, etc.) or given as rgb(255,0,0) e.g. for red.

You can see the result here. I’ve used the Dutch National Park dataset as example. You can obtain the code simply by saving the page or by downloading it from GitHub.

Adding a new dataset is done by editing line 89 of index.html:

var layers = ['NationaleParken'];

You can add datasets separated by comma. The name has to correspond with the file name of the GeoJSON file and is also used in the legend. I think it would be able to automatically load all GeoJSON files in a given directory (eliminating the need to edit index.html for a new dataset), but this seems to require the use of Node.JS.

The map center, zoom level, and default background map are selected in line 83 to 87:

var map = L.map('map', {
center: [52.1, 5.4],
zoom: 8,
layers: [grayscale]
});

Clicking on a feature opens a popup that shows all attributes. This is done in line 35 to 43 of the code:

const onEachFeature = (feature, layer) => {
var popupContent = [];
if (feature.properties) {
for (var prop in feature.properties) {
popupContent.push(prop + ": " + feature.properties[prop]);
}
}
layer.bindPopup(popupContent.join("<br />"));
};

You can of course change this to e.g. only display select attributes, but this is generic code that will work for all files. You could e.g. omit the color attribute by modifying line 39 to

if(prop!="color") popupContent.push(prop + ": " + feature.properties[prop]);

The style of a feature is set in line 45 to 49:

function setStyle(feature) {
return {
color: feature.properties.color
};
}

As explained above, this uses a color value given in the attribute table. You could change this to assign colors based on a different attribute (property), as explained in this Leaflet tutorial.

You can also copy the color used in your QGIS symbology into the color attribute, using the Color to Attribute plugin that is available from the QGIS plugin repository.

Leave a comment

Your email address will not be published. Required fields are marked *