Bringing a map online with QGIS server and OpenLayers

QGIS server is a stable and easy to use alternative to geoserver. In this short tutorial you learn how to show your QGIS Desktop project as a online map using QGIS server and OpenLayers.
This post can be understood as a follow up to this fantastic posts by Paul Shapley. Installing QGIS server on Ubuntu explains all the steps to configure Apache2 with FastCGI module on Ubuntu 16.04. Bringing a map image into the browser shows how to display a map image from QGIS Desktop project file as a WMS layer.
As a starting point you should have an image output of your QGIS map in the browser, something like this. The necessary steps are explained in the mentioned tutorials.
To start with I use a simple QGIS project with only one layer, a geojson file of countries geometries. The QGIS Desktop file can be downloaded here, it was created with QGIS version 2.18.12. Keep in mind that I used coordinate system WGS 84 (EPSG:4326), this projection is supported by OpenLayers but has to be indicated when creating the view.
Here is the basic Javascript code to load a WMS layer and use it on a OpenLayers map:
var wmsLayer = new ol.layer.Tile({
source: new ol.source.TileWMS({
url: 'http://vps444389.ovh.net/cgi-bin/countries/qgis_mapserv.fcgi?map=/home/qgis/countries.qgs&',
params: {
'LAYERS': 'countries',
'TRANSPARENT': true,
},
serverType: 'qgis'
})
});
var map = new ol.Map({
target: 'map',
layers: [wmsLayer],
view: new ol.View({
projection: 'EPSG:4326',
center: [0, 0],
zoom: 3
})
});
The final output of the online map should look like that.
Tags: Linux, openlayers, QGIS, tutorial, WMS
